Skip to content

Commit

Permalink
Merge branch 'master' into ore_patches_generation
Browse files Browse the repository at this point in the history
  • Loading branch information
fluffyloafie authored Nov 10, 2023
2 parents 995d142 + 0753845 commit f7959a4
Show file tree
Hide file tree
Showing 16 changed files with 292 additions and 55 deletions.
21 changes: 21 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@ option(NO_GUI "Build without GUI" OFF)
option(STATIC_LINK "Link the binary statically" OFF)
option(GTEST "Build with Google Test" OFF)
option(ARM "Build for ARM" OFF)
option(PROMETHEUS "Build with Prometheus support" ON)

message(STATUS "Debugging network: ${DEBUG_NETWORK}")
message(STATUS "Building without GUI: ${NO_GUI}")
message(STATUS "Linking statically: ${STATIC_LINK}")
message(STATUS "Building with Google Test: ${GTEST}")
message(STATUS "Building for ARM: ${ARM}")
message(STATUS "Building with Prometheus support: ${PROMETHEUS}")

if (USE_CLANG)
find_program(CLANG_EXECUTABLE clang REQUIRED)
Expand Down Expand Up @@ -152,6 +154,20 @@ target_include_directories(spdlog SYSTEM INTERFACE ${spdlog_include})
get_target_property(yaml_cpp_include yaml-cpp INTERFACE_INCLUDE_DIRECTORIES)
target_include_directories(yaml-cpp SYSTEM INTERFACE ${yaml_cpp_include})

if(PROMETHEUS)
FetchContent_Declare(
prometheus-cpp
GIT_REPOSITORY https://github.com/jupp0r/prometheus-cpp.git
GIT_TAG v1.1.0
GIT_PROGRESS TRUE
GIT_SHALLOW TRUE
)

FetchContent_MakeAvailable(
prometheus-cpp
)
endif()

if(GTEST) # if the flag GTEST is true
FetchContent_Declare(
googletest
Expand Down Expand Up @@ -195,6 +211,7 @@ target_compile_definitions(${CMAKE_PROJECT_NAME} PRIVATE
PROGRAM_VERSION="${CMAKE_PROJECT_VERSION}"
MINECRAFT_VERSION="${MINECRAFT_VERSION}"
GUI_UNAVAILABLE=$<BOOL:${NO_GUI}>
PROMETHEUS_SUPPORT=$<BOOL:${PROMETHEUS}>
)

if (STATIC_LINK)
Expand Down Expand Up @@ -237,6 +254,10 @@ target_link_libraries (${CMAKE_PROJECT_NAME} PRIVATE
$<$<NOT:$<BOOL:${Boost_FOUND}>>:Boost::circular_buffer>
)

if (PROMETHEUS)
target_link_libraries (${CMAKE_PROJECT_NAME} PRIVATE prometheus-cpp::pull)
endif ()

if (CMAKE_BUILD_TYPE MATCHES RELWITHDEBINFO)
target_link_libraries (${CMAKE_PROJECT_NAME} PRIVATE
asan
Expand Down
7 changes: 7 additions & 0 deletions cubic-server/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ target_sources (${CMAKE_PROJECT_NAME} PRIVATE
CompressionUtils.hpp
)

if(PROMETHEUS)
target_sources (${CMAKE_PROJECT_NAME} PRIVATE
PrometheusExporter.cpp
PrometheusExporter.hpp
)
endif()

file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/plugins)

if (GTEST)
Expand Down
1 change: 1 addition & 0 deletions cubic-server/Client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ void Client::handleParsedClientPacket(std::unique_ptr<protocol::BaseServerPacket
{
using namespace protocol;

PEXP(incrementPacketRxCounter);
switch (_status) {
case ClientStatus::Initial:
switch (packetID) {
Expand Down
2 changes: 2 additions & 0 deletions cubic-server/Player.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,13 @@ Player::Player(std::weak_ptr<Client> cli, std::shared_ptr<Dimension> dim, u128 u
nbt_tag_compound_append(root, display);

this->_inventory->playerInventory().at(14) = protocol::Slot(true, 1, 12, root);
PEXP(incrementPlayerCountGlobal);
}

Player::~Player()
{
this->_dim->getWorld()->sendPlayerInfoRemovePlayer(this);
PEXP(decrementPlayerCountGlobal);

// Send a disconnect message
onEvent(Server::getInstance()->getPluginManager(), onPlayerLeave, this);
Expand Down
52 changes: 52 additions & 0 deletions cubic-server/PrometheusExporter.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#include <memory>

#include <prometheus/counter.h>
#include <prometheus/gauge.h>
#include <prometheus/info.h>
#include <prometheus/registry.h>

#include "PrometheusExporter.hpp"
#include "options.hpp"

PrometheusExporter::PrometheusExporter(const std::string &bind):
_exposer(bind),
_ready(false)
{
}

void PrometheusExporter::registerMetrics()
{
_registry = std::make_shared<prometheus::Registry>();

// clang-format off
auto &packet_counter = prometheus::BuildCounter()
.Name("observed_packets_total")
.Help("Number of observed packets")
.Register(*_registry);
// clang-format on
_packet_rx_counter = &packet_counter.Add({{"direction", "rx"}});
_packet_tx_counter = &packet_counter.Add({{"direction", "tx"}});

// clang-format off
auto& version_info = prometheus::BuildInfo()
.Name("versions")
.Help("Static info about the server")
.Register(*_registry);
// clang-format on
_version_info = &version_info.Add({{PROGRAM_NAME, PROGRAM_VERSION}});

// clang-format off
auto &player_gauge = prometheus::BuildGauge()
.Name("player_count")
.Help("Number of players connected")
.Register(*_registry);
// clang-format on
_player_global_gauge = &player_gauge.Add({{"dimension", "global"}});
_player_overworld_gauge = &player_gauge.Add({{"dimension", "overworld"}});
_player_nether_gauge = &player_gauge.Add({{"dimension", "nether"}});
_player_end_gauge = &player_gauge.Add({{"dimension", "end"}});

_exposer.RegisterCollectable(_registry);

_ready = true;
}
103 changes: 103 additions & 0 deletions cubic-server/PrometheusExporter.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
#ifndef D5AEBC4C_6028_4506_86F2_DA6261F54832
#define D5AEBC4C_6028_4506_86F2_DA6261F54832

#include <memory>
#include <string>

#include "prometheus/counter.h"
#include "prometheus/exposer.h"
#include "prometheus/registry.h"

class PrometheusExporter {
public:
PrometheusExporter(const std::string &bind);
void registerMetrics();
void incrementPacketRxCounter()
{
if (_ready)
_packet_rx_counter->Increment();
}
void incrementPacketTxCounter()
{
if (_ready)
_packet_tx_counter->Increment();
}
void setPlayerCountGlobal(size_t n)
{
if (_ready)
_player_global_gauge->Set(n);
}
void setPlayerCountOverworld(size_t n)
{
if (_ready)
_player_overworld_gauge->Set(n);
}
void setPlayerCountNether(size_t n)
{
if (_ready)
_player_nether_gauge->Set(n);
}
void setPlayerCountEnd(size_t n)
{
if (_ready)
_player_end_gauge->Set(n);
}
void incrementPlayerCountGlobal()
{
if (_ready)
_player_global_gauge->Increment();
}
void incrementPlayerCountOverworld()
{
if (_ready)
_player_overworld_gauge->Increment();
}
void incrementPlayerCountNether()
{
if (_ready)
_player_nether_gauge->Increment();
}
void incrementPlayerCountEnd()
{
if (_ready)
_player_end_gauge->Increment();
}
void decrementPlayerCountGlobal()
{
if (_ready)
_player_global_gauge->Decrement();
}
void decrementPlayerCountOverworld()
{
if (_ready)
_player_overworld_gauge->Decrement();
}
void decrementPlayerCountNether()
{
if (_ready)
_player_nether_gauge->Decrement();
}
void decrementPlayerCountEnd()
{
if (_ready)
_player_end_gauge->Decrement();
}

private:
prometheus::Exposer _exposer;
std::shared_ptr<prometheus::Registry> _registry;

prometheus::Counter *_packet_tx_counter;
prometheus::Counter *_packet_rx_counter;

prometheus::Info *_version_info; // This is not dynamic yet, but it can be in the future

prometheus::Gauge *_player_global_gauge;
prometheus::Gauge *_player_overworld_gauge;
prometheus::Gauge *_player_nether_gauge;
prometheus::Gauge *_player_end_gauge;

std::atomic<bool> _ready;
};

#endif /* D5AEBC4C_6028_4506_86F2_DA6261F54832 */
65 changes: 11 additions & 54 deletions cubic-server/Server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

#include <mbedtls/rsa.h>

#include "PrometheusExporter.hpp"
#include "Server.hpp"
#include "World.hpp"

Expand All @@ -37,20 +38,10 @@ using boost::asio::ip::tcp;

Server::Server():
_running(false),
// _sockfd(-1),
_config(),
_pluginManager(this),
_toSend(1024)
{
// _config.load("./config.yml");
// _config.parse("./config.yml");
// _config.parse(2, (const char * const *){"./CubicServer", "--nogui"});
// _host = _config.getIP();
// _port = _config.getPort();
// _maxPlayer = _config.getMaxPlayers();
// _motd = _config.getMotd();
// _enforceWhitelist = _config.getEnforceWhitelist();

_commands.emplace_back(std::make_unique<command_parser::Help>());
_commands.emplace_back(std::make_unique<command_parser::QuestionMark>());
_commands.emplace_back(std::make_unique<command_parser::Stop>());
Expand Down Expand Up @@ -165,32 +156,21 @@ void Server::launch(const configuration::ConfigHandler &config)

_writeThread = std::thread(&Server::_writeLoop, this);

#if PROMETHEUS_SUPPORT == 1
if (CONFIG["monitoring-prometheus-enable"].as<bool>()) {
_prometheusExporter =
std::make_unique<PrometheusExporter>(CONFIG["monitoring-prometheus-ip"].as<std::string>() + std::string(":") + CONFIG["monitoring-prometheus-port"].as<std::string>());
_prometheusExporter->registerMetrics();
_prometheusExporterOn = true;
}
#endif

_doAccept();

_io_context.run();

// Cleanup stuff here
this->_stop();
// this->_writeThread.join();
// std::unique_lock _(clientsMutex);

// for (auto [id, cli] : _clients)
// cli->stop();

// for (auto [id, cli] : _clients) {
// if (cli->getThread().joinable())
// cli->getThread().join();
// }

// _clients.clear();

// using namespace std::chrono_literals;
// // Wait for 5 seconds max for all data to be out
// for (int i = 0; i < 500; i++) {
// if (_toSend.empty())
// break;
// std::this_thread::sleep_for(10ms);
// }
}

void Server::sendData(size_t clientID, std::unique_ptr<std::vector<uint8_t>> &&data) { _toSend.push({clientID, data.release()}); }
Expand Down Expand Up @@ -225,6 +205,7 @@ void Server::_writeLoop()
}
boost::system::error_code ec;
boost::asio::write(client->getSocket(), boost::asio::buffer(data.data->data(), data.data->size()), ec);
PEXP(incrementPacketTxCounter);
// TODO(huntears): Handle errors properly xd
if (ec) {
client->disconnect("Network error");
Expand All @@ -245,15 +226,6 @@ void Server::triggerClientCleanup(size_t clientID)
_clients.erase(clientID);
return;
}
// boost::lockfree::queue<size_t> toDelete(_clients.size());
// for (auto [id, cli] : _clients) {
// if (!cli) {
// _clients.erase(id);
// } else if (cli->isDisconnected()) {
// cli->getThread().join();
// _clients.erase(id);
// }
// }
std::erase_if(_clients, [](const auto augh) {
if (augh.second->isDisconnected()) {
if (augh.second->getThread().joinable())
Expand All @@ -268,17 +240,6 @@ void Server::addCommand(std::unique_ptr<CommandBase> command) { this->_commands.

void Server::_doAccept()
{
// while (_running) {
// boost::system::error_code ec;
// tcp::socket socket(_io_context);

// _acceptor->accept(socket, ec);
// if (!ec) {
// std::shared_ptr<Client> _cli(new Client(std::move(socket), currentClientID));
// _clients.emplace(currentClientID++, _cli);
// _cli->run();
// }
// }
tcp::socket *socket = new tcp::socket(_io_context);

_acceptor->async_accept(*socket, [socket, this](const boost::system::error_code &error) {
Expand All @@ -290,10 +251,6 @@ void Server::_doAccept()
}
delete socket;
if (this->_running) {
// for (auto [id, cli] : _clients) {
// if (!cli || cli->isDisconnected()) // Somehow they can already be freed before we get here...
// _clients.erase(id);
// }
this->_doAccept();
}
});
Expand Down
Loading

0 comments on commit f7959a4

Please sign in to comment.