Skip to content

Commit

Permalink
Merge branch 'main' into fix/fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
elsongabriel authored Apr 2, 2024
2 parents 133bb73 + 0c0e546 commit 4538f1f
Show file tree
Hide file tree
Showing 15 changed files with 176 additions and 100 deletions.
9 changes: 8 additions & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ cmake_minimum_required(VERSION 3.22 FATAL_ERROR)
# VCPKG
# cmake -DCMAKE_TOOLCHAIN_FILE=/opt/workspace/vcpkg/scripts/buildsystems/vcpkg.cmake ..
# Needed libs is in file vcpkg.json
# Windows required libs: .\vcpkg install --triplet x64-windows asio pugixml spdlog curl jsoncpp protobuf parallel-hashmap magic-enum mio luajit libmariadb mpir abseil
# Windows required libs: .\vcpkg install --triplet x64-windows asio pugixml spdlog curl protobuf parallel-hashmap magic-enum mio luajit libmariadb mpir abseil
if(DEFINED ENV{VCPKG_ROOT} AND NOT DEFINED CMAKE_TOOLCHAIN_FILE)
set(CMAKE_TOOLCHAIN_FILE "$ENV{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake"
CACHE STRING "")
Expand Down Expand Up @@ -48,11 +48,18 @@ include(LoggingHelper)
option(OPTIONS_ENABLE_CCACHE "Enable ccache" OFF)
option(OPTIONS_ENABLE_SCCACHE "Use sccache to speed up compilation process" OFF)
option(OPTIONS_ENABLE_IPO "Check and Enable interprocedural optimization (IPO/LTO)" ON)
option(FEATURE_METRICS "Enable metrics feature" OFF)

# *****************************************************************************
# Options Code
# *****************************************************************************

if(FEATURE_METRIC)
log_option_enabled("metrics")
else ()
log_option_disabled("metrics")
endif ()

# === CCACHE ===
if(OPTIONS_ENABLE_CCACHE)
find_program(CCACHE ccache)
Expand Down
7 changes: 4 additions & 3 deletions cmake/modules/BaseConfig.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,11 @@ find_package(ZLIB REQUIRED)
find_package(absl CONFIG REQUIRED)
find_package(asio CONFIG REQUIRED)
find_package(eventpp CONFIG REQUIRED)
find_package(jsoncpp CONFIG REQUIRED)
find_package(magic_enum CONFIG REQUIRED)
find_package(opentelemetry-cpp CONFIG REQUIRED)
find_package(prometheus-cpp CONFIG REQUIRED)
if(FEATURE_METRICS)
find_package(opentelemetry-cpp CONFIG REQUIRED)
find_package(prometheus-cpp CONFIG REQUIRED)
endif()
find_package(mio REQUIRED)
find_package(pugixml CONFIG REQUIRED)
find_package(spdlog REQUIRED)
Expand Down
28 changes: 17 additions & 11 deletions cmake/modules/CanaryLib.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -105,17 +105,25 @@ target_link_libraries(${PROJECT_NAME}_lib
unofficial::argon2::libargon2
unofficial::libmariadb
unofficial::mariadbclient
opentelemetry-cpp::common
opentelemetry-cpp::metrics
opentelemetry-cpp::api
opentelemetry-cpp::ext
opentelemetry-cpp::sdk
opentelemetry-cpp::logs
opentelemetry-cpp::ostream_metrics_exporter
opentelemetry-cpp::prometheus_exporter
protobuf
)

if(FEATURE_METRICS)
add_definitions(-DFEATURE_METRICS)

target_link_libraries(${PROJECT_NAME}_lib
PUBLIC
opentelemetry-cpp::common
opentelemetry-cpp::metrics
opentelemetry-cpp::api
opentelemetry-cpp::ext
opentelemetry-cpp::sdk
opentelemetry-cpp::logs
opentelemetry-cpp::ostream_metrics_exporter
opentelemetry-cpp::prometheus_exporter
)
endif()

if(CMAKE_BUILD_TYPE MATCHES Debug)
target_link_libraries(${PROJECT_NAME}_lib PUBLIC ${ZLIB_LIBRARY_DEBUG})
else()
Expand All @@ -124,16 +132,14 @@ endif()

if (MSVC)
if(BUILD_STATIC_LIBRARY)
target_link_libraries(${PROJECT_NAME}_lib PUBLIC jsoncpp_static)
set(VCPKG_TARGET_TRIPLET "x64-windows-static" CACHE STRING "")
else()
target_link_libraries(${PROJECT_NAME}_lib PUBLIC jsoncpp_lib)
set(VCPKG_TARGET_TRIPLET "x64-windows" CACHE STRING "")
endif()

target_link_libraries(${PROJECT_NAME}_lib PUBLIC ${CMAKE_THREAD_LIBS_INIT} ${MYSQL_CLIENT_LIBS})
else()
target_link_libraries(${PROJECT_NAME}_lib PUBLIC jsoncpp_static Threads::Threads)
target_link_libraries(${PROJECT_NAME}_lib PUBLIC Threads::Threads)
endif (MSVC)

# === OpenMP ===
Expand Down
10 changes: 4 additions & 6 deletions data/modules/scripts/daily_reward/daily_reward.lua
Original file line number Diff line number Diff line change
Expand Up @@ -462,14 +462,12 @@ function Player.selectDailyReward(self, msg)
local description = ""
for k, v in ipairs(items) do
if dailyTable.itemCharges then
for i = 1, rewardCount do
local inboxItem = inbox:addItem(v.itemId, dailyTable.itemCharges) -- adding charges for each item
if inboxItem then
inboxItem:setAttribute(ITEM_ATTRIBUTE_STORE, systemTime())
end
local inboxItem = inbox:addItem(v.itemId, dailyTable.itemCharges) -- adding charges for each item
if inboxItem then
inboxItem:setAttribute(ITEM_ATTRIBUTE_STORE, systemTime())
end
else
local inboxItem = inbox:addItem(v.itemId, rewardCount) -- adding single item w/o charges
local inboxItem = inbox:addItem(v.itemId, v.count) -- adding single item w/o charges
if inboxItem then
inboxItem:setAttribute(ITEM_ATTRIBUTE_STORE, systemTime())
end
Expand Down
3 changes: 2 additions & 1 deletion src/canary_server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ int CanaryServer::run() {
loadConfigLua();

logger.info("Server protocol: {}.{}{}", CLIENT_VERSION_UPPER, CLIENT_VERSION_LOWER, g_configManager().getBoolean(OLD_PROTOCOL, __FUNCTION__) ? " and 10x allowed!" : "");
#ifdef FEATURE_METRICS
metrics::Options metricsOptions;
metricsOptions.enablePrometheusExporter = g_configManager().getBoolean(METRICS_ENABLE_PROMETHEUS, __FUNCTION__);
if (metricsOptions.enablePrometheusExporter) {
Expand All @@ -71,7 +72,7 @@ int CanaryServer::run() {
metricsOptions.ostreamOptions.export_interval_millis = std::chrono::milliseconds(g_configManager().getNumber(METRICS_OSTREAM_INTERVAL, __FUNCTION__));
}
g_metrics().init(metricsOptions);

#endif
rsa.start();
initializeDatabase();
loadModules();
Expand Down
8 changes: 5 additions & 3 deletions src/game/game.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,8 @@ Game::Game() {
// Create instance of IOWheel to Game class
m_IOWheel = std::make_unique<IOWheel>();

wildcardTree = std::make_shared<WildcardTreeNode>(false);

m_highscoreCategoriesNames = {
{ static_cast<uint8_t>(HighscoreCategories_t::ACHIEVEMENTS), "Achievement Points" },
{ static_cast<uint8_t>(HighscoreCategories_t::AXE_FIGHTING), "Axe Fighting" },
Expand Down Expand Up @@ -886,7 +888,7 @@ ReturnValue Game::getPlayerByNameWildcard(const std::string &s, std::shared_ptr<
if (s.back() == '~') {
const std::string &query = asLowerCaseString(s.substr(0, strlen - 1));
std::string result;
ReturnValue ret = wildcardTree.findOne(query, result);
ReturnValue ret = wildcardTree->findOne(query, result);
if (ret != RETURNVALUE_NOERROR) {
return ret;
}
Expand Down Expand Up @@ -9691,14 +9693,14 @@ void Game::updatePlayerSaleItems(uint32_t playerId) {
void Game::addPlayer(std::shared_ptr<Player> player) {
const std::string &lowercase_name = asLowerCaseString(player->getName());
mappedPlayerNames[lowercase_name] = player;
wildcardTree.insert(lowercase_name);
wildcardTree->insert(lowercase_name);
players[player->getID()] = player;
}

void Game::removePlayer(std::shared_ptr<Player> player) {
const std::string &lowercase_name = asLowerCaseString(player->getName());
mappedPlayerNames.erase(lowercase_name);
wildcardTree.remove(lowercase_name);
wildcardTree->remove(lowercase_name);
players.erase(player->getID());
}

Expand Down
2 changes: 1 addition & 1 deletion src/game/game.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -840,7 +840,7 @@ class Game {
size_t lastBucket = 0;
size_t lastImbuedBucket = 0;

WildcardTreeNode wildcardTree { false };
std::shared_ptr<WildcardTreeNode> wildcardTree;

std::map<uint32_t, std::shared_ptr<Npc>> npcs;
std::map<uint32_t, std::shared_ptr<Monster>> monsters;
Expand Down
5 changes: 4 additions & 1 deletion src/lib/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
target_sources(${PROJECT_NAME}_lib PRIVATE
di/soft_singleton.cpp
logging/log_with_spd_log.cpp
metrics/metrics.cpp
thread/thread_pool.cpp
)

if(FEATURE_METRICS)
target_sources(${PROJECT_NAME}_lib PRIVATE metrics/metrics.cpp)
endif()
9 changes: 6 additions & 3 deletions src/lib/metrics/metrics.cpp
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#ifdef FEATURE_METRICS
/**
* Canary - A free and open-source MMORPG server emulator
* Copyright (©) 2019-2024 OpenTibiaBR <[email protected]>
Expand All @@ -7,8 +8,8 @@
* Website: https://docs.opentibiabr.com/
*/

#include "metrics.hpp"
#include "lib/di/container.hpp"
#include "metrics.hpp"
#include "lib/di/container.hpp"

using namespace metrics;

Expand Down Expand Up @@ -41,7 +42,7 @@ void Metrics::init(Options opts) {
initHistograms();
}

void Metrics ::initHistograms() {
void Metrics::initHistograms() {
for (auto name : latencyNames) {
auto instrumentSelector = metrics_sdk::InstrumentSelectorFactory::Create(metrics_sdk::InstrumentType::kHistogram, name, "us");
auto meterSelector = metrics_sdk::MeterSelectorFactory::Create("performance", otelVersion, otelSchema);
Expand Down Expand Up @@ -108,3 +109,5 @@ void ScopedLatency::stop() {
auto attrskv = opentelemetry::common::KeyValueIterableView<decltype(attrs)> { attrs };
histogram->Record(elapsed, attrskv, context);
}

#endif // FEATURE_METRICS
127 changes: 90 additions & 37 deletions src/lib/metrics/metrics.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,43 +9,29 @@

#pragma once

#include "game/scheduling/dispatcher.hpp"
#include <opentelemetry/exporters/ostream/metric_exporter_factory.h>
#include <opentelemetry/sdk/metrics/export/periodic_exporting_metric_reader_factory.h>
#include <opentelemetry/exporters/prometheus/exporter_factory.h>
#include <opentelemetry/exporters/prometheus/exporter_options.h>
#include <opentelemetry/metrics/provider.h>
#include <opentelemetry/sdk/metrics/aggregation/default_aggregation.h>
#include <opentelemetry/sdk/metrics/aggregation/histogram_aggregation.h>
#include <opentelemetry/sdk/metrics/push_metric_exporter.h>
#include <opentelemetry/sdk/metrics/aggregation/base2_exponential_histogram_indexer.h>
#include <opentelemetry/sdk/metrics/meter.h>
#include <opentelemetry/sdk/metrics/meter_provider.h>
#include <opentelemetry/sdk/metrics/meter_provider_factory.h>
#include <opentelemetry/sdk/metrics/view/instrument_selector_factory.h>
#include <opentelemetry/sdk/metrics/view/meter_selector_factory.h>
#include <opentelemetry/sdk/metrics/view/view_factory.h>
#ifdef FEATURE_METRICS
#include "game/scheduling/dispatcher.hpp"
#include <opentelemetry/exporters/ostream/metric_exporter_factory.h>
#include <opentelemetry/sdk/metrics/export/periodic_exporting_metric_reader_factory.h>
#include <opentelemetry/exporters/prometheus/exporter_factory.h>
#include <opentelemetry/exporters/prometheus/exporter_options.h>
#include <opentelemetry/metrics/provider.h>
#include <opentelemetry/sdk/metrics/aggregation/default_aggregation.h>
#include <opentelemetry/sdk/metrics/aggregation/histogram_aggregation.h>
#include <opentelemetry/sdk/metrics/push_metric_exporter.h>
#include <opentelemetry/sdk/metrics/aggregation/base2_exponential_histogram_indexer.h>
#include <opentelemetry/sdk/metrics/meter.h>
#include <opentelemetry/sdk/metrics/meter_provider.h>
#include <opentelemetry/sdk/metrics/meter_provider_factory.h>
#include <opentelemetry/sdk/metrics/view/instrument_selector_factory.h>
#include <opentelemetry/sdk/metrics/view/meter_selector_factory.h>
#include <opentelemetry/sdk/metrics/view/view_factory.h>

namespace metrics_sdk = opentelemetry::sdk::metrics;
namespace common = opentelemetry::common;
namespace metrics_exporter = opentelemetry::exporter::metrics;
namespace metrics_api = opentelemetry::metrics;

constexpr std::string_view methodName(const char* s) {
std::string_view prettyFunction(s);
size_t bracket = prettyFunction.rfind("(");
size_t space = prettyFunction.rfind(" ", bracket) + 1;
return prettyFunction.substr(space, bracket - space);
}

#if defined(__GNUC__) || defined(__clang__)
#define __METHOD_NAME__ methodName(__PRETTY_FUNCTION__)
#elif defined(_MSC_VER)
#define __METHOD_NAME__ methodName(__FUNCSIG__)
#else
#error "Compiler not supported"
#endif

namespace metrics {
using Meter = opentelemetry::nostd::shared_ptr<metrics_api::Meter>;

Expand Down Expand Up @@ -85,12 +71,12 @@ namespace metrics {
bool stopped { false };
};

#define DEFINE_LATENCY_CLASS(class_name, histogram_name, category) \
class class_name##_latency final : public ScopedLatency { \
public: \
class_name##_latency(std::string_view name) : \
ScopedLatency(name, histogram_name "_latency", category) { } \
}
#define DEFINE_LATENCY_CLASS(class_name, histogram_name, category) \
class class_name##_latency final : public ScopedLatency { \
public: \
class_name##_latency(std::string_view name) : \
ScopedLatency(name, histogram_name "_latency", category) { } \
}

DEFINE_LATENCY_CLASS(method, "method", "method");
DEFINE_LATENCY_CLASS(lua, "lua", "scope");
Expand Down Expand Up @@ -170,3 +156,70 @@ namespace metrics {

constexpr auto g_metrics
= metrics::Metrics::getInstance;

#else // FEATURE_METRICS

#include "lib/di/container.hpp"

struct Options {
bool enablePrometheusExporter;
bool enableOStreamExporter;
};

class ScopedLatency {
public:
explicit ScopedLatency([[maybe_unused]] std::string_view name, [[maybe_unused]] const std::string &histogramName, [[maybe_unused]] const std::string &scopeKey) {};
explicit ScopedLatency([[maybe_unused]] std::string_view name, [[maybe_unused]] std::set<double> &histogram, [[maybe_unused]] const std::map<std::string, std::string> &attrs = {}, [[maybe_unused]] const std::string &context = std::string()) {};

void stop() {};

~ScopedLatency() = default;
};

namespace metrics {
#define DEFINE_LATENCY_CLASS(class_name, histogram_name, category) \
class class_name##_latency final : public ScopedLatency { \
public: \
class_name##_latency(std::string_view name) : \
ScopedLatency(name, histogram_name "_latency", category) { } \
}

DEFINE_LATENCY_CLASS(method, "method", "method");
DEFINE_LATENCY_CLASS(lua, "lua", "scope");
DEFINE_LATENCY_CLASS(query, "query", "truncated_query");
DEFINE_LATENCY_CLASS(task, "task", "task");
DEFINE_LATENCY_CLASS(lock, "lock", "scope");

const std::vector<std::string> latencyNames {
"method_latency",
"lua_latency",
"query_latency",
"task_latency",
"lock_latency",
};

class Metrics final {
public:
Metrics() = default;
~Metrics() = default;

void init([[maybe_unused]] Options opts) {};
void initHistograms() {};
void shutdown() {};

static Metrics &getInstance() {
return inject<Metrics>();
};

void addCounter([[maybe_unused]] std::string_view name, [[maybe_unused]] double value, [[maybe_unused]] const std::map<std::string, std::string> &attrs = {}) { }

void addUpDownCounter([[maybe_unused]] std::string_view name, [[maybe_unused]] int value, [[maybe_unused]] const std::map<std::string, std::string> &attrs = {}) { }

friend class ScopedLatency;
};
}

constexpr auto g_metrics
= metrics::Metrics::getInstance;

#endif // FEATURE_METRICS
Loading

0 comments on commit 4538f1f

Please sign in to comment.