diff --git a/package/src/memmon.cpp b/package/src/memmon.cpp index 07ad006..4b6cc0a 100644 --- a/package/src/memmon.cpp +++ b/package/src/memmon.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include "utils.h" @@ -136,3 +137,44 @@ void const memmon::get_unit_info(nlohmann::json& unit_json) { prmon::fill_units(unit_json, params); return; } + +// Toggle on fast memmory monitoring +void const memmon::do_fastmon() { + // Fast monitoring reads the data from a special file + // This file is called smaps_rollup instead of smaps + input_filename = "smaps_rollup"; + + // First discover all available metrics by peeking into self smaps_rollup file + std::set available_metrics; + std::stringstream smaps_fname{"/proc/self/smaps_rollup"}; + std::ifstream smap_stat{smaps_fname.str()}; + std::string key_str{}, value_str{}; + while (smap_stat) { + smap_stat >> key_str >> value_str; + smap_stat.ignore(std::numeric_limits::max(), '\n'); + if (smap_stat) { + if (key_str == "Size:") { + available_metrics.insert("vmem"); + } else if (key_str == "Pss:") { + available_metrics.insert("pss"); + } else if (key_str == "Rss:") { + available_metrics.insert("rss"); + } else if (key_str == "Swap:") { + available_metrics.insert("swap"); + } + } + } + + // Delete unavailable metrics from the monitored stats + // In C++17/20 there are more elegant ways to do this + for (auto it = mem_stats.cbegin(); it != mem_stats.cend();) { + // Delete unavailable metrics + if (available_metrics.count(it->first) == 0) { + spdlog::warn("Metric " + it->first + + " is not available in fast monitoring"); + it = mem_stats.erase(it); + } else { + it++; + } + } +}; diff --git a/package/src/memmon.h b/package/src/memmon.h index a3618cf..b9fe9ea 100644 --- a/package/src/memmon.h +++ b/package/src/memmon.h @@ -53,7 +53,7 @@ class memmon final : public Imonitor, public MessageBase { bool const is_valid() { return true; } // Toggle on fast memmory monitoring - inline void const do_fastmon() { input_filename = "smaps_rollup"; }; + void const do_fastmon(); }; REGISTER_MONITOR(Imonitor, memmon, "Monitor memory usage")