aboutsummaryrefslogtreecommitdiff
path: root/src/libutil/cgroup.cc
blob: 9320d2371473ae1eac982049c9809b5f124c14e3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
#if __linux__

#include "cgroup.hh"
#include "util.hh"
#include "finally.hh"

#include <chrono>
#include <cmath>
#include <regex>
#include <unordered_set>
#include <thread>

#include <dirent.h>
#include <mntent.h>

namespace nix {

std::optional<Path> getCgroupFS()
{
    static auto res = [&]() -> std::optional<Path> {
        auto fp = fopen("/proc/mounts", "r");
        if (!fp) return std::nullopt;
        Finally delFP = [&]() { fclose(fp); };
        while (auto ent = getmntent(fp))
            if (std::string_view(ent->mnt_type) == "cgroup2")
                return ent->mnt_dir;

        return std::nullopt;
    }();
    return res;
}

// FIXME: obsolete, check for cgroup2
std::map<std::string, std::string> getCgroups(const Path & cgroupFile)
{
    std::map<std::string, std::string> cgroups;

    for (auto & line : tokenizeString<std::vector<std::string>>(readFile(cgroupFile), "\n")) {
        static std::regex regex("([0-9]+):([^:]*):(.*)");
        std::smatch match;
        if (!std::regex_match(line, match, regex))
            throw Error("invalid line '%s' in '%s'", line, cgroupFile);

        std::string name = std::string(match[2]).starts_with("name=") ? std::string(match[2], 5) : match[2];
        cgroups.insert_or_assign(name, match[3]);
    }

    return cgroups;
}

static CgroupStats destroyCgroup(const Path & cgroup, bool returnStats)
{
    if (!pathExists(cgroup)) return {};

    auto procsFile = cgroup + "/cgroup.procs";

    if (!pathExists(procsFile))
        throw Error("'%s' is not a cgroup", cgroup);

    /* Use the fast way to kill every process in a cgroup, if
       available. */
    auto killFile = cgroup + "/cgroup.kill";
    if (pathExists(killFile))
        writeFile(killFile, "1");

    /* Otherwise, manually kill every process in the subcgroups and
       this cgroup. */
    for (auto & entry : readDirectory(cgroup)) {
        if (entry.type != DT_DIR) continue;
        destroyCgroup(cgroup + "/" + entry.name, false);
    }

    int round = 1;

    std::unordered_set<pid_t> pidsShown;

    while (true) {
        auto pids = tokenizeString<std::vector<std::string>>(readFile(procsFile));

        if (pids.empty()) break;

        if (round > 20)
            throw Error("cannot kill cgroup '%s'", cgroup);

        for (auto & pid_s : pids) {
            pid_t pid;
            if (auto o = string2Int<pid_t>(pid_s))
                pid = *o;
            else
                throw Error("invalid pid '%s'", pid);
            if (pidsShown.insert(pid).second) {
                try {
                    auto cmdline = readFile(fmt("/proc/%d/cmdline", pid));
                    using namespace std::string_literals;
                    warn("killing stray builder process %d (%s)...",
                        pid, trim(replaceStrings(cmdline, "\0"s, " ")));
                } catch (SysError &) {
                }
            }
            // FIXME: pid wraparound
            if (kill(pid, SIGKILL) == -1 && errno != ESRCH)
                throw SysError("killing member %d of cgroup '%s'", pid, cgroup);
        }

        auto sleep = std::chrono::milliseconds((int) std::pow(2.0, std::min(round, 10)));
        if (sleep.count() > 100)
            printError("waiting for %d ms for cgroup '%s' to become empty", sleep.count(), cgroup);
        std::this_thread::sleep_for(sleep);
        round++;
    }

    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 (line.starts_with(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 (line.starts_with(systemPrefix)) {
                    auto n = string2Int<uint64_t>(line.substr(systemPrefix.size()));
                    if (n) stats.cpuSystem = std::chrono::microseconds(*n);
                }
            }
        }

    }

    if (rmdir(cgroup.c_str()) == -1)
        throw SysError("deleting cgroup '%s'", cgroup);

    return stats;
}

CgroupStats destroyCgroup(const Path & cgroup)
{
    return destroyCgroup(cgroup, true);
}

}

#endif