File: cgroup_map.cpp

package info (click to toggle)
android-platform-tools 34.0.5-12
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 150,900 kB
  • sloc: cpp: 805,786; java: 293,500; ansic: 128,288; xml: 127,491; python: 41,481; sh: 14,245; javascript: 9,665; cs: 3,846; asm: 2,049; makefile: 1,917; yacc: 440; awk: 368; ruby: 183; sql: 140; perl: 88; lex: 67
file content (249 lines) | stat: -rw-r--r-- 8,407 bytes parent folder | download | duplicates (2)
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

//#define LOG_NDEBUG 0
#define LOG_TAG "libprocessgroup"

#include <errno.h>
#include <fcntl.h>
#include <grp.h>
#include <pwd.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>

#include <regex>

#include <android-base/file.h>
#include <android-base/logging.h>
#include <android-base/properties.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
#include <android-base/unique_fd.h>
#include <cgroup_map.h>
#include <json/reader.h>
#include <json/value.h>
#include <processgroup/processgroup.h>

using android::base::GetBoolProperty;
using android::base::StartsWith;
using android::base::StringPrintf;
using android::base::unique_fd;
using android::base::WriteStringToFile;

static constexpr const char* CGROUP_PROCS_FILE = "/cgroup.procs";
static constexpr const char* CGROUP_TASKS_FILE = "/tasks";
static constexpr const char* CGROUP_TASKS_FILE_V2 = "/cgroup.threads";

uint32_t CgroupController::version() const {
    CHECK(HasValue());
    return ACgroupController_getVersion(controller_);
}

const char* CgroupController::name() const {
    CHECK(HasValue());
    return ACgroupController_getName(controller_);
}

const char* CgroupController::path() const {
    CHECK(HasValue());
    return ACgroupController_getPath(controller_);
}

bool CgroupController::HasValue() const {
    return controller_ != nullptr;
}

bool CgroupController::IsUsable() {
    if (!HasValue()) return false;

    if (state_ == UNKNOWN) {
        if (__builtin_available(android 30, *)) {
            uint32_t flags = ACgroupController_getFlags(controller_);
            state_ = (flags & CGROUPRC_CONTROLLER_FLAG_MOUNTED) != 0 ? USABLE : MISSING;
        } else {
            state_ = access(GetProcsFilePath("", 0, 0).c_str(), F_OK) == 0 ? USABLE : MISSING;
        }
    }

    return state_ == USABLE;
}

std::string CgroupController::GetTasksFilePath(const std::string& rel_path) const {
    std::string tasks_path = path();

    if (!rel_path.empty()) {
        tasks_path += "/" + rel_path;
    }
    return (version() == 1) ? tasks_path + CGROUP_TASKS_FILE : tasks_path + CGROUP_TASKS_FILE_V2;
}

std::string CgroupController::GetProcsFilePath(const std::string& rel_path, uid_t uid,
                                               pid_t pid) const {
    std::string proc_path(path());
    proc_path.append("/").append(rel_path);
    proc_path = regex_replace(proc_path, std::regex("<uid>"), std::to_string(uid));
    proc_path = regex_replace(proc_path, std::regex("<pid>"), std::to_string(pid));

    return proc_path.append(CGROUP_PROCS_FILE);
}

bool CgroupController::GetTaskGroup(int tid, std::string* group) const {
    std::string file_name = StringPrintf("/proc/%d/cgroup", tid);
    std::string content;
    if (!android::base::ReadFileToString(file_name, &content)) {
        PLOG(ERROR) << "Failed to read " << file_name;
        return false;
    }

    // if group is null and tid exists return early because
    // user is not interested in cgroup membership
    if (group == nullptr) {
        return true;
    }

    std::string cg_tag;

    if (version() == 2) {
        cg_tag = "0::";
    } else {
        cg_tag = StringPrintf(":%s:", name());
    }
    size_t start_pos = content.find(cg_tag);
    if (start_pos == std::string::npos) {
        return false;
    }

    start_pos += cg_tag.length() + 1;  // skip '/'
    size_t end_pos = content.find('\n', start_pos);
    if (end_pos == std::string::npos) {
        *group = content.substr(start_pos, std::string::npos);
    } else {
        *group = content.substr(start_pos, end_pos - start_pos);
    }

    return true;
}

CgroupMap::CgroupMap() {
    if (!LoadRcFile()) {
        LOG(ERROR) << "CgroupMap::LoadRcFile called for [" << getpid() << "] failed";
    }
}

CgroupMap& CgroupMap::GetInstance() {
    // Deliberately leak this object to avoid a race between destruction on
    // process exit and concurrent access from another thread.
    static auto* instance = new CgroupMap;
    return *instance;
}

bool CgroupMap::LoadRcFile() {
    if (!loaded_) {
        loaded_ = (ACgroupFile_getVersion() != 0);
    }
    return loaded_;
}

void CgroupMap::Print() const {
    if (!loaded_) {
        LOG(ERROR) << "CgroupMap::Print called for [" << getpid()
                   << "] failed, RC file was not initialized properly";
        return;
    }
    LOG(INFO) << "File version = " << ACgroupFile_getVersion();
    LOG(INFO) << "File controller count = " << ACgroupFile_getControllerCount();

    LOG(INFO) << "Mounted cgroups:";

    auto controller_count = ACgroupFile_getControllerCount();
    for (uint32_t i = 0; i < controller_count; ++i) {
        const ACgroupController* controller = ACgroupFile_getController(i);
        if (__builtin_available(android 30, *)) {
            LOG(INFO) << "\t" << ACgroupController_getName(controller) << " ver "
                      << ACgroupController_getVersion(controller) << " path "
                      << ACgroupController_getPath(controller) << " flags "
                      << ACgroupController_getFlags(controller);
        } else {
            LOG(INFO) << "\t" << ACgroupController_getName(controller) << " ver "
                      << ACgroupController_getVersion(controller) << " path "
                      << ACgroupController_getPath(controller);
        }
    }
}

CgroupController CgroupMap::FindController(const std::string& name) const {
    if (!loaded_) {
        LOG(ERROR) << "CgroupMap::FindController called for [" << getpid()
                   << "] failed, RC file was not initialized properly";
        return CgroupController(nullptr);
    }

    auto controller_count = ACgroupFile_getControllerCount();
    for (uint32_t i = 0; i < controller_count; ++i) {
        const ACgroupController* controller = ACgroupFile_getController(i);
        if (name == ACgroupController_getName(controller)) {
            return CgroupController(controller);
        }
    }

    return CgroupController(nullptr);
}

CgroupController CgroupMap::FindControllerByPath(const std::string& path) const {
    if (!loaded_) {
        LOG(ERROR) << "CgroupMap::FindControllerByPath called for [" << getpid()
                   << "] failed, RC file was not initialized properly";
        return CgroupController(nullptr);
    }

    auto controller_count = ACgroupFile_getControllerCount();
    for (uint32_t i = 0; i < controller_count; ++i) {
        const ACgroupController* controller = ACgroupFile_getController(i);
        if (StartsWith(path, ACgroupController_getPath(controller))) {
            return CgroupController(controller);
        }
    }

    return CgroupController(nullptr);
}

int CgroupMap::ActivateControllers(const std::string& path) const {
    if (__builtin_available(android 30, *)) {
        auto controller_count = ACgroupFile_getControllerCount();
        for (uint32_t i = 0; i < controller_count; ++i) {
            const ACgroupController* controller = ACgroupFile_getController(i);
            const uint32_t flags = ACgroupController_getFlags(controller);
            if (flags & CGROUPRC_CONTROLLER_FLAG_NEEDS_ACTIVATION) {
                std::string str("+");
                str.append(ACgroupController_getName(controller));
                if (!WriteStringToFile(str, path + "/cgroup.subtree_control")) {
                    if (flags & CGROUPRC_CONTROLLER_FLAG_OPTIONAL) {
                        PLOG(WARNING) << "Activation of cgroup controller " << str
                                      << " failed in path " << path;
                    } else {
                        return -errno;
                    }
                }
            }
        }
        return 0;
    }
    return -ENOSYS;
}