1
1
Fork 0
mirror of https://github.com/NixOS/nix.git synced 2025-12-08 18:11:02 +01:00

Merge pull request #14681 from NixOS/cgroup-stats

Add getCgroupStats() function
This commit is contained in:
Sergei Zimmerman 2025-12-04 01:04:18 +00:00 committed by GitHub
commit 7f1712957a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 35 additions and 22 deletions

View file

@ -49,6 +49,33 @@ StringMap getCgroups(const Path & cgroupFile)
return cgroups;
}
CgroupStats getCgroupStats(const std::filesystem::path & cgroup)
{
CgroupStats stats;
auto cpustatPath = cgroup / "cpu.stat";
if (pathExists(cpustatPath)) {
for (auto & line : tokenizeString<std::vector<std::string>>(readFile(cpustatPath), "\n")) {
std::string_view userPrefix = "user_usec ";
if (hasPrefix(line, userPrefix)) {
auto n = string2Int<uint64_t>(line.substr(userPrefix.size()));
if (n)
stats.cpuUser = std::chrono::microseconds(*n);
}
std::string_view systemPrefix = "system_usec ";
if (hasPrefix(line, systemPrefix)) {
auto n = string2Int<uint64_t>(line.substr(systemPrefix.size()));
if (n)
stats.cpuSystem = std::chrono::microseconds(*n);
}
}
}
return stats;
}
static CgroupStats destroyCgroup(const std::filesystem::path & cgroup, bool returnStats)
{
if (!pathExists(cgroup))
@ -114,28 +141,8 @@ static CgroupStats destroyCgroup(const std::filesystem::path & cgroup, bool retu
}
CgroupStats stats;
if (returnStats) {
auto cpustatPath = cgroup / "cpu.stat";
if (pathExists(cpustatPath)) {
for (auto & line : tokenizeString<std::vector<std::string>>(readFile(cpustatPath), "\n")) {
std::string_view userPrefix = "user_usec ";
if (hasPrefix(line, userPrefix)) {
auto n = string2Int<uint64_t>(line.substr(userPrefix.size()));
if (n)
stats.cpuUser = std::chrono::microseconds(*n);
}
std::string_view systemPrefix = "system_usec ";
if (hasPrefix(line, systemPrefix)) {
auto n = string2Int<uint64_t>(line.substr(systemPrefix.size()));
if (n)
stats.cpuSystem = std::chrono::microseconds(*n);
}
}
}
}
if (returnStats)
stats = getCgroupStats(cgroup);
if (rmdir(cgroup.c_str()) == -1)
throw SysError("deleting cgroup %s", cgroup);

View file

@ -3,6 +3,7 @@
#include <chrono>
#include <optional>
#include <filesystem>
#include "nix/util/types.hh"
@ -17,6 +18,11 @@ struct CgroupStats
std::optional<std::chrono::microseconds> cpuUser, cpuSystem;
};
/**
* Read statistics from the given cgroup.
*/
CgroupStats getCgroupStats(const std::filesystem::path & cgroup);
/**
* Destroy the cgroup denoted by 'path'. The postcondition is that
* 'path' does not exist, and thus any processes in the cgroup have