Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 29 additions & 22 deletions src/libutil/linux/cgroup.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -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);
Expand Down
6 changes: 6 additions & 0 deletions src/libutil/linux/include/nix/util/cgroup.hh
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

#include <chrono>
#include <optional>
#include <filesystem>

#include "nix/util/types.hh"

Expand All @@ -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
Expand Down
Loading