Skip to content

Commit

Permalink
feat: add server start time measurement
Browse files Browse the repository at this point in the history
  • Loading branch information
OEOTYAN committed Oct 14, 2023
1 parent 7df9474 commit 0fe1e8f
Show file tree
Hide file tree
Showing 18 changed files with 114 additions and 84 deletions.
26 changes: 13 additions & 13 deletions src/ll/api/LoggerAPI.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -86,42 +86,42 @@ bool checkLogLevel(int level, int outLevel) {
fmt::text_style getModeColor(std::string const& a1) {
if (!ll::globalConfig.colorLog) return {};
switch (do_hash(a1)) {
case do_hash("INFO"):
case "INFO"_h:
return fmt::fg(fmt::color::light_sea_green);
case do_hash("WARN"):
case "WARN"_h:
return fmt::fg(fmt::color::yellow);
case do_hash("DEBUG"):
case "DEBUG"_h:
return fmt::fg(fmt::color::white);
case do_hash("ERROR"):
case "ERROR"_h:
return fmt::fg(fmt::terminal_color::bright_red);
case do_hash("FATAL"):
case "FATAL"_h:
return fmt::fg(fmt::color::red);
}
return fmt::fg(fmt::color::white);
}

template <typename S, typename Char>
std::string applyTextStyle(fmt::v9::text_style const& ts, S const& format_str, bool reset) {
fmt::v9::basic_memory_buffer<Char> buf;
auto fmt = fmt::detail::to_string_view(format_str);
bool has_style = false;
std::string applyTextStyle(fmt::text_style const& ts, S const& format_str, bool reset) {
fmt::basic_memory_buffer<Char> buf;
auto fmt = fmt::detail::to_string_view(format_str);
bool has_style = false;
if (ts.has_emphasis()) {
has_style = true;
auto emphasis = fmt::v9::detail::make_emphasis<Char>(ts.get_emphasis());
auto emphasis = fmt::detail::make_emphasis<Char>(ts.get_emphasis());
buf.append(emphasis.begin(), emphasis.end());
}
if (ts.has_foreground()) {
has_style = true;
auto foreground = fmt::v9::detail::make_foreground_color<Char>(ts.get_foreground());
auto foreground = fmt::detail::make_foreground_color<Char>(ts.get_foreground());
buf.append(foreground.begin(), foreground.end());
}
if (ts.has_background()) {
has_style = true;
auto background = fmt::v9::detail::make_background_color<Char>(ts.get_background());
auto background = fmt::detail::make_background_color<Char>(ts.get_background());
buf.append(background.begin(), background.end());
}
buf.append(fmt.begin(), fmt.end());
if (has_style && reset) fmt::v9::detail::reset_color<Char>(buf);
if (has_style && reset) fmt::detail::reset_color<Char>(buf);
return fmt::to_string(buf);
}

Expand Down
4 changes: 2 additions & 2 deletions src/ll/api/LoggerAPI.h
Original file line number Diff line number Diff line change
Expand Up @@ -167,5 +167,5 @@ class Logger {
LLAPI static std::mutex& getLocker();
};

template <typename S, typename Char = fmt::v9::char_t<S>>
std::string applyTextStyle(fmt::v9::text_style const& ts, S const& format_str, bool reset = true);
template <typename S, typename Char = fmt::char_t<S>>
std::string applyTextStyle(fmt::text_style const& ts, S const& format_str, bool reset = true);
8 changes: 4 additions & 4 deletions src/ll/api/ScheduleAPI.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ ScheduleTaskQueueType taskQueue;

namespace Schedule {
ScheduleTask delay(std::function<void(void)> task, uint64 tickDelay, HMODULE handle) {
if (ll::globalRuntimeConfig.serverStatus >= ll::LLServerStatus::Stopping) return {(uint)-1};
if (ll::globalRuntimeConfig.serverStatus >= ll::ServerStatus::Stopping) return {(uint)-1};
ScheduleTaskData sche(ScheduleTaskData::TaskType::Delay, std::move(task), tickDelay, -1, -1, handle);
locker.lock();
pendingTaskList.push_back(sche);
Expand All @@ -176,7 +176,7 @@ ScheduleTask delay(std::function<void(void)> task, uint64 tickDelay, HMODULE han
}

ScheduleTask repeat(std::function<void(void)> task, uint64 tickRepeat, int maxCount, HMODULE handle) {
if (ll::globalRuntimeConfig.serverStatus >= ll::LLServerStatus::Stopping) return {(uint)-1};
if (ll::globalRuntimeConfig.serverStatus >= ll::ServerStatus::Stopping) return {(uint)-1};
ScheduleTaskData::TaskType type =
maxCount < 0 ? ScheduleTaskData::TaskType::InfiniteRepeat : ScheduleTaskData::TaskType::Repeat;
ScheduleTaskData
Expand All @@ -189,7 +189,7 @@ ScheduleTask repeat(std::function<void(void)> task, uint64 tickRepeat, int maxCo

ScheduleTask
delayRepeat(std::function<void(void)> task, uint64 tickDelay, uint64 tickRepeat, int maxCount, HMODULE handle) {
if (ll::globalRuntimeConfig.serverStatus >= ll::LLServerStatus::Stopping) return {(uint)-1};
if (ll::globalRuntimeConfig.serverStatus >= ll::ServerStatus::Stopping) return {(uint)-1};
ScheduleTaskData::TaskType type =
maxCount < 0 ? ScheduleTaskData::TaskType::InfiniteRepeat : ScheduleTaskData::TaskType::Repeat;
ScheduleTaskData sche(type, std::move(task), tickDelay, std::max(tickRepeat, 1ull), maxCount, handle);
Expand All @@ -200,7 +200,7 @@ delayRepeat(std::function<void(void)> task, uint64 tickDelay, uint64 tickRepeat,
}

ScheduleTask nextTick(std::function<void(void)> task, HMODULE handle) {
if (ll::globalRuntimeConfig.serverStatus >= ll::LLServerStatus::Stopping) return {(uint)-1};
if (ll::globalRuntimeConfig.serverStatus >= ll::ServerStatus::Stopping) return {(uint)-1};
ScheduleTaskData sche(ScheduleTaskData::TaskType::Delay, std::move(task), 1, -1, -1, handle);
locker.lock();
pendingTaskList.push_back(sche);
Expand Down
7 changes: 3 additions & 4 deletions src/ll/api/command/DynamicCommandAPI.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -704,9 +704,8 @@ DynamicCommandInstance const* DynamicCommand::setup(std::unique_ptr<class Dynami
auto ptr = commandInstance.get();
if (!ptr) throw std::runtime_error("DynamicCommand::setup - commandInstance is null");
if (!serverCommandsRegistered) {
delaySetupLock.lock();
auto& uptr = delaySetupCommandInstances.emplace_back(std::move(commandInstance));
delaySetupLock.unlock();
SRWLockHolder locker(delaySetupLock);
auto& uptr = delaySetupCommandInstances.emplace_back(std::move(commandInstance));
return uptr.get();
}
Schedule::nextTick([instance{commandInstance.release()}]() {
Expand Down Expand Up @@ -798,7 +797,7 @@ inline std::unique_ptr<DynamicCommandInstance> DynamicCommandInstance::create(
CommandFlag flag,
HMODULE handle
) {
if (ll::globalRuntimeConfig.serverStatus != ll::LLServerStatus::Running) {
if (ll::globalRuntimeConfig.serverStatus != ll::ServerStatus::Running) {
for (auto& cmd : delaySetupCommandInstances) {
if (cmd->name_ == name) {
logger.error("Command \"{}\" already exists", name);
Expand Down
10 changes: 5 additions & 5 deletions src/ll/api/command/DynamicCommandAPI.h
Original file line number Diff line number Diff line change
Expand Up @@ -111,19 +111,19 @@ class DynamicCommandInstance;
* auto& action = results["testEnum"].get<std::string>();
* switch (do_hash(action.c_str()))
* {
* case do_hash("add"):
* case "add"_h:
* if (results["testInt"].isSet)
* output.success(fmt::format("add {}", results["testInt"].getRaw<int>()));
* else
* output.success("add nothing");
* break;
* case do_hash("remove"):
* case "remove"_h:
* if (results["testInt"].isSet)
* output.success(fmt::format("remove {}", results["testInt"].getRaw<int>()));
* else
* output.success("remove nothing");
* break;
* case do_hash("list"):
* case "list"_h:
* output.success("list");
* break;
* default:
Expand Down Expand Up @@ -734,11 +734,11 @@ class DynamicCommandInstance {
LLAPI static std::vector<std::string> getSoftEnumNames();

template <typename T>
inline std::enable_if_t<fmt::v9::detail::is_string<T>::value, ParameterIndex> toIndex(T const& arg) {
inline std::enable_if_t<fmt::detail::is_string<T>::value, ParameterIndex> toIndex(T const& arg) {
return findParameterIndex(arg);
}
template <typename T>
inline std::enable_if_t<!fmt::v9::detail::is_string<T>::value, ParameterIndex> toIndex(T const& arg) = delete;
inline std::enable_if_t<!fmt::detail::is_string<T>::value, ParameterIndex> toIndex(T const& arg) = delete;
template <>
inline ParameterIndex toIndex(ParameterIndex const& arg) {
return arg;
Expand Down
14 changes: 7 additions & 7 deletions src/ll/api/service/GlobalService.h
Original file line number Diff line number Diff line change
Expand Up @@ -42,16 +42,16 @@ class GlobalService {
LLAPI GlobalService();
void init(T* ptr);

T* get() { return value; }
T* operator->() { return value; }
T& operator*() { return *value; }
operator T*() { return value; } // NOLINT(google-explicit-constructor)
constexpr T* get() { return value; }
constexpr T* operator->() { return value; }
constexpr T& operator*() { return *value; }
constexpr operator T*() { return value; } // NOLINT(google-explicit-constructor)
template <typename U>
explicit operator U*() {
constexpr explicit operator U*() {
return static_cast<U*>(value);
}
explicit operator bool() { return value != nullptr; }
bool has_value() { return value != nullptr; }
constexpr explicit operator bool() { return value != nullptr; }
constexpr bool has_value() { return value != nullptr; }
};

template <IsGlobalService T>
Expand Down
4 changes: 2 additions & 2 deletions src/ll/api/utils/Base64.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ inline size_t getEncodeLength(size_t len) { return (len + 2 - ((len + 2) % 3)) /
inline size_t getEncodeLength(std::string const& str) { return getEncodeLength(str.length()); }

inline size_t getDecodeLength(std::string const& in) {
unsigned char count = 0;
size_t input_size = in.size();
uchar count = 0;
size_t input_size = in.size();
for (auto it = in.rbegin(); *it == '='; ++it) { ++count; }
input_size -= count; // remove padding size
count = 0; // reset padding counter
Expand Down
1 change: 1 addition & 0 deletions src/ll/api/utils/FileHelper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

#include <filesystem>

#include "ll/api/LoggerAPI.h"
#include "ll/api/utils/StringUtils.h"
#include "ll/api/utils/WinHelper.h"
#include "ll/core/Config.h"
Expand Down
1 change: 0 additions & 1 deletion src/ll/api/utils/FileHelper.h
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#pragma once
#include "ll/api/LoggerAPI.h"
#include "ll/api/base/Global.h"
#include <fstream>
#include <optional>
Expand Down
2 changes: 2 additions & 0 deletions src/ll/api/utils/Hash.h
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ constexpr uint64 do_hash(const char* x, size_t len) {
return rval;
}

constexpr uint64 operator""_h(const char* x, size_t len) { return do_hash(x, len); }

constexpr uint64 do_hash2(std::string_view x) {
// ap hash
uint64 rval = 0;
Expand Down
3 changes: 1 addition & 2 deletions src/ll/core/Config.h
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ namespace ll {
struct CommandLineOption {
bool noColorOption = false;
};
enum class LLServerStatus { Starting, Running, Stopping };
struct LLConfig {
bool debugMode = false;
bool colorLog = true;
Expand Down Expand Up @@ -54,7 +53,7 @@ struct LLConfig {
};

struct LLRuntimeConfig {
LLServerStatus serverStatus = LLServerStatus::Starting;
ServerStatus serverStatus = ServerStatus::Starting;
std::thread::id tickThreadId;
};

Expand Down
26 changes: 18 additions & 8 deletions src/ll/core/LeviLamina.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@
#include "windows.h"


Logger ll::logger("LeviLamina");
time_t ll::startTime;
time_t ll::endTime;
Logger ll::logger("LeviLamina");
std::chrono::steady_clock::time_point ll::SeverStartBeginTime;
std::chrono::steady_clock::time_point ll::SeverStartEndTime;

using namespace ll;

Expand Down Expand Up @@ -334,18 +334,28 @@ void leviLaminaMain() {

using namespace ll::memory;

// int main(int argc, char* argv[]);

LL_AUTO_STATIC_HOOK(LeviLaminaMainHook, HookPriority::Normal, "main", int, int argc, char* argv[]) {
startTime = clock();

SeverStartBeginTime = std::chrono::steady_clock::now();

for (int i = 0; i < argc; ++i) {
if (strcmp(argv[i], "--noColor") == 0) {
switch (do_hash(argv[i])) {
case "--noColor"_h:
ll::commandLineOption.noColorOption = true;
break;
case "-v"_h:
case "--version"_h:
fmt::print("{}", ll::getBdsVersion());
return 0;
case "--protocolversion"_h:
fmt::print("{}", ll::getServerProtocolVersion());
return 0;
default:
break;
}
}
leviLaminaMain();
return origin(argc, argv);
}

[[maybe_unused]] BOOL WINAPI DllMain(HMODULE, DWORD , LPVOID) { return TRUE; }
[[maybe_unused]] BOOL WINAPI DllMain(HMODULE, DWORD, LPVOID) { return TRUE; }
4 changes: 2 additions & 2 deletions src/ll/core/LeviLamina.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
#include "ll/api/LoggerAPI.h"
namespace ll {
extern Logger logger;
extern time_t startTime;
extern time_t endTime;
extern std::chrono::steady_clock::time_point SeverStartBeginTime;
extern std::chrono::steady_clock::time_point SeverStartEndTime;
} // namespace ll
63 changes: 40 additions & 23 deletions src/ll/core/ModifyInfomation.cpp
Original file line number Diff line number Diff line change
@@ -1,47 +1,45 @@
#include "ll/api/LoggerAPI.h"
#include "ll/api/memory/Hook.h"
#include "ll/core/LeviLamina.h"
#include "mc/common/Common.h"

#include "mc/deps/core/common/debug/LogDetails.h"

Logger serverLogger("Server");

std::unordered_map<unsigned int, decltype(serverLogger.debug)&> loggerMap = {
static std::unordered_map<uint, decltype(serverLogger.debug)&> loggerMap = {
{1u, serverLogger.debug},
{2u, serverLogger.info },
{4u, serverLogger.warn },
{8u, serverLogger.error}
};

// Block BDS from adding LOG metadata
static bool serverStarted = false;

LL_AUTO_TYPED_INSTANCE_HOOK(
AppendLogEntryMetadataHook,
HookPriority::Normal,
::BedrockLog::LogDetails,
&::BedrockLog::LogDetails::_appendLogEntryMetadata,
void,
std::string&,
std::string, // NOLINT
::LogAreaID,
uint,
std::string, // NOLINT
int,
int
) {}
void tryLogServerStarted(std::string& s) {
if (s != "Server started.") return;
serverStarted = true;

MCAPI void BedrockLogOut(unsigned int priority, const char* pszFormat, ...);
ll::SeverStartEndTime = std::chrono::steady_clock::now();

s = std::format(
R"(Server started in ({:.1f}s)! For help, type "help" or "?")",
std::chrono::duration_cast<std::chrono::duration<double>>(ll::SeverStartEndTime - ll::SeverStartBeginTime)
.count()
);
}

MCAPI void BedrockLogOut(uint priority, const char* pszFormat, ...);

LL_AUTO_STATIC_HOOK(
BedrockLogOutHook,
HookPriority::Normal,
BedrockLogOut,
void,
unsigned int priority,
const char* pszFormat,
uint priority,
const char* pszFormat,
...
) {
constexpr const int BUFFER_SIZE = 4096;
constexpr const int BUFFER_SIZE = 4096; // from ida
char Buffer[BUFFER_SIZE];
va_list va;
va_start(va, pszFormat);
Expand All @@ -52,10 +50,29 @@ LL_AUTO_STATIC_HOOK(
std::istringstream iss(Buffer);
std::string line;

auto& logger = loggerMap.contains(priority) ? loggerMap.at(priority) : serverLogger.info;

while (std::getline(iss, line)) {
if (!line.empty() && line.back() == '\n') { line.pop_back(); }
auto loggerIter = loggerMap.find(priority);
auto& logger = (loggerIter != loggerMap.end()) ? loggerIter->second : serverLogger.info;
if (!serverStarted) tryLogServerStarted(line);
logger << line << Logger::endl;
}
}


// Block BDS from adding LOG metadata

LL_AUTO_TYPED_INSTANCE_HOOK(
AppendLogEntryMetadataHook,
HookPriority::Normal,
::BedrockLog::LogDetails,
&::BedrockLog::LogDetails::_appendLogEntryMetadata,
void,
std::string&,
std::string, // NOLINT
::LogAreaID,
uint,
std::string, // NOLINT
int,
int
) {}
Loading

0 comments on commit 0fe1e8f

Please sign in to comment.