From e463d2f0f14790ea7f5e48c2b05fd61c433c075a Mon Sep 17 00:00:00 2001 From: Krunal Gandhi Date: Mon, 22 Jan 2024 08:10:39 +0000 Subject: [PATCH] export swap used in /metrics.json end-point (#1499) * export swap used in /metrics.json end-point * remove logs * add macro to run on linux only * update the swap usage fetch approach * remove check to maintain consistent API response --- include/system_metrics.h | 2 ++ src/system_metrics.cpp | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/include/system_metrics.h b/include/system_metrics.h index 94363afa..721e8e08 100644 --- a/include/system_metrics.h +++ b/include/system_metrics.h @@ -143,6 +143,8 @@ private: static uint64_t get_memory_non_proc_bytes(); + static uint64_t linux_get_swap_used_bytes(); + public: SystemMetrics() { diff --git a/src/system_metrics.cpp b/src/system_metrics.cpp index 972026c9..97781b4a 100644 --- a/src/system_metrics.cpp +++ b/src/system_metrics.cpp @@ -72,6 +72,10 @@ void SystemMetrics::get(const std::string &data_dir_path, nlohmann::json &result result["system_memory_total_bytes"] = std::to_string(get_memory_total_bytes()); result["system_memory_used_bytes"] = std::to_string(get_memory_used_bytes()); +#ifdef __linux__ + auto swap_bytes = linux_get_swap_used_bytes(); + result["system_memory_used_swap_bytes"] = std::to_string(swap_bytes); +#endif // CPU and Network metrics #if __linux__ const std::vector& cpu_stats = get_cpu_stats(); @@ -227,3 +231,18 @@ void SystemMetrics::linux_get_network_data(const std::string & stat_path, } } } + +uint64_t SystemMetrics::linux_get_swap_used_bytes() { + std::string filename = "/proc/" + std::to_string(::getpid()) + "/status"; + std::string token; + std::ifstream file(filename); + while(file >> token) { + if(token == "VmSwap:") { + uint64_t mem_kB; + if(file >> mem_kB) { + return mem_kB * 1024; + } + } + } + return 0; +} \ No newline at end of file