blob: 4fc085e322cb0d188ea69a9d895c2c4bb378e71a [file] [log] [blame]
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -08001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "libprocessgroup"
19
20#include <errno.h>
21#include <fcntl.h>
22#include <pwd.h>
23#include <sys/mman.h>
24#include <sys/mount.h>
25#include <sys/stat.h>
26#include <sys/types.h>
27#include <time.h>
28#include <unistd.h>
29
30#include <regex>
31
32#include <android-base/file.h>
33#include <android-base/logging.h>
34#include <android-base/properties.h>
35#include <android-base/stringprintf.h>
36#include <android-base/unique_fd.h>
37#include <cgroup_map.h>
38#include <json/reader.h>
39#include <json/value.h>
40#include <processgroup/processgroup.h>
41
42using android::base::GetBoolProperty;
43using android::base::StringPrintf;
44using android::base::unique_fd;
45
46static constexpr const char* CGROUPS_DESC_FILE = "/etc/cgroups.json";
47
48static constexpr const char* CGROUP_PROCS_FILE = "/cgroup.procs";
49static constexpr const char* CGROUP_TASKS_FILE = "/tasks";
50static constexpr const char* CGROUP_TASKS_FILE_V2 = "/cgroup.tasks";
51
52static bool Mkdir(const std::string& path, mode_t mode, const std::string& uid,
53 const std::string& gid) {
54 if (mode == 0) {
55 mode = 0755;
56 }
57
58 if (mkdir(path.c_str(), mode) != 0) {
59 /* chmod in case the directory already exists */
60 if (errno == EEXIST) {
61 if (fchmodat(AT_FDCWD, path.c_str(), mode, AT_SYMLINK_NOFOLLOW) != 0) {
62 // /acct is a special case when the directory already exists
63 // TODO: check if file mode is already what we want instead of using EROFS
64 if (errno != EROFS) {
65 PLOG(ERROR) << "fchmodat() failed for " << path;
66 return false;
67 }
68 }
69 } else {
70 PLOG(ERROR) << "mkdir() failed for " << path;
71 return false;
72 }
73 }
74
75 passwd* uid_pwd = nullptr;
76 passwd* gid_pwd = nullptr;
77
78 if (!uid.empty()) {
79 uid_pwd = getpwnam(uid.c_str());
80 if (!uid_pwd) {
81 PLOG(ERROR) << "Unable to decode UID for '" << uid << "'";
82 return false;
83 }
84
85 if (!gid.empty()) {
86 gid_pwd = getpwnam(gid.c_str());
87 if (!gid_pwd) {
88 PLOG(ERROR) << "Unable to decode GID for '" << gid << "'";
89 return false;
90 }
91 }
92 }
93
94 if (uid_pwd && lchown(path.c_str(), uid_pwd->pw_uid, gid_pwd ? gid_pwd->pw_uid : -1) < 0) {
95 PLOG(ERROR) << "lchown() failed for " << path;
96 return false;
97 }
98
99 /* chown may have cleared S_ISUID and S_ISGID, chmod again */
100 if (mode & (S_ISUID | S_ISGID)) {
101 if (fchmodat(AT_FDCWD, path.c_str(), mode, AT_SYMLINK_NOFOLLOW) != 0) {
102 PLOG(ERROR) << "fchmodat() failed for " << path;
103 return false;
104 }
105 }
106
107 return true;
108}
109
110static bool ReadDescriptors(std::map<std::string, CgroupDescriptor>* descriptors) {
111 std::vector<CgroupDescriptor> result;
112 std::string json_doc;
113
114 if (!android::base::ReadFileToString(CGROUPS_DESC_FILE, &json_doc)) {
115 LOG(ERROR) << "Failed to read task profiles from " << CGROUPS_DESC_FILE;
116 return false;
117 }
118
119 Json::Reader reader;
120 Json::Value root;
121 if (!reader.parse(json_doc, root)) {
122 LOG(ERROR) << "Failed to parse cgroups description: " << reader.getFormattedErrorMessages();
123 return false;
124 }
125
126 Json::Value cgroups = root["Cgroups"];
127 for (Json::Value::ArrayIndex i = 0; i < cgroups.size(); ++i) {
128 std::string name = cgroups[i]["Controller"].asString();
129 descriptors->emplace(std::make_pair(
130 name,
Suren Baghdasaryanc7602312019-02-02 16:09:17 -0800131 CgroupDescriptor(1, name, cgroups[i]["Path"].asString(),
132 std::strtoul(cgroups[i]["Mode"].asString().c_str(), 0, 8),
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800133 cgroups[i]["UID"].asString(), cgroups[i]["GID"].asString())));
134 }
135
136 Json::Value cgroups2 = root["Cgroups2"];
137 descriptors->emplace(std::make_pair(
138 CGROUPV2_CONTROLLER_NAME,
139 CgroupDescriptor(2, CGROUPV2_CONTROLLER_NAME, cgroups2["Path"].asString(),
Suren Baghdasaryanc7602312019-02-02 16:09:17 -0800140 std::strtoul(cgroups2["Mode"].asString().c_str(), 0, 8),
141 cgroups2["UID"].asString(), cgroups2["GID"].asString())));
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800142
143 return true;
144}
145
Suren Baghdasaryanff25a5f2019-02-02 23:12:01 -0800146// To avoid issues in sdk_mac build
147#if defined(__ANDROID__)
148
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800149static bool SetupCgroup(const CgroupDescriptor& descriptor) {
150 const CgroupController* controller = descriptor.controller();
151
152 // mkdir <path> [mode] [owner] [group]
153 if (!Mkdir(controller->path(), descriptor.mode(), descriptor.uid(), descriptor.gid())) {
154 PLOG(ERROR) << "Failed to create directory for " << controller->name() << " cgroup";
155 return false;
156 }
157
158 int result;
159 if (controller->version() == 2) {
160 result = mount("none", controller->path(), "cgroup2", MS_NODEV | MS_NOEXEC | MS_NOSUID,
161 nullptr);
162 } else {
163 // Unfortunately historically cpuset controller was mounted using a mount command
164 // different from all other controllers. This results in controller attributes not
165 // to be prepended with controller name. For example this way instead of
166 // /dev/cpuset/cpuset.cpus the attribute becomes /dev/cpuset/cpus which is what
167 // the system currently expects.
168 if (!strcmp(controller->name(), "cpuset")) {
169 // mount cpuset none /dev/cpuset nodev noexec nosuid
170 result = mount("none", controller->path(), controller->name(),
171 MS_NODEV | MS_NOEXEC | MS_NOSUID, nullptr);
172 } else {
173 // mount cgroup none <path> nodev noexec nosuid <controller>
174 result = mount("none", controller->path(), "cgroup", MS_NODEV | MS_NOEXEC | MS_NOSUID,
175 controller->name());
176 }
177 }
178
179 if (result < 0) {
180 PLOG(ERROR) << "Failed to mount " << controller->name() << " cgroup";
181 return false;
182 }
183
184 return true;
185}
186
Suren Baghdasaryanff25a5f2019-02-02 23:12:01 -0800187#else
188
189// Stubs for non-Android targets.
190static bool SetupCgroup(const CgroupDescriptor&) {
191 return false;
192}
193
194#endif
195
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800196static bool WriteRcFile(const std::map<std::string, CgroupDescriptor>& descriptors) {
197 std::string cgroup_rc_path = StringPrintf("%s/%s", CGROUPS_RC_DIR, CgroupMap::CGROUPS_RC_FILE);
198 unique_fd fd(TEMP_FAILURE_RETRY(open(cgroup_rc_path.c_str(),
199 O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC,
200 S_IRUSR | S_IRGRP | S_IROTH)));
201 if (fd < 0) {
202 PLOG(ERROR) << "open() failed for " << cgroup_rc_path;
203 return false;
204 }
205
206 CgroupFile fl;
207 fl.version_ = CgroupFile::FILE_CURR_VERSION;
208 fl.controller_count_ = descriptors.size();
209 int ret = TEMP_FAILURE_RETRY(write(fd, &fl, sizeof(fl)));
210 if (ret < 0) {
211 PLOG(ERROR) << "write() failed for " << cgroup_rc_path;
212 return false;
213 }
214
215 for (const auto& [name, descriptor] : descriptors) {
216 ret = TEMP_FAILURE_RETRY(write(fd, descriptor.controller(), sizeof(CgroupController)));
217 if (ret < 0) {
218 PLOG(ERROR) << "write() failed for " << cgroup_rc_path;
219 return false;
220 }
221 }
222
223 return true;
224}
225
226CgroupController::CgroupController(uint32_t version, const std::string& name,
227 const std::string& path) {
228 version_ = version;
229 strncpy(name_, name.c_str(), sizeof(name_) - 1);
230 name_[sizeof(name_) - 1] = '\0';
231 strncpy(path_, path.c_str(), sizeof(path_) - 1);
232 path_[sizeof(path_) - 1] = '\0';
233}
234
235std::string CgroupController::GetTasksFilePath(const std::string& path) const {
236 std::string tasks_path = path_;
237
238 if (!path.empty()) {
239 tasks_path += "/" + path;
240 }
241 return (version_ == 1) ? tasks_path + CGROUP_TASKS_FILE : tasks_path + CGROUP_TASKS_FILE_V2;
242}
243
244std::string CgroupController::GetProcsFilePath(const std::string& path, uid_t uid,
245 pid_t pid) const {
246 std::string proc_path(path_);
247 proc_path.append("/").append(path);
248 proc_path = regex_replace(proc_path, std::regex("<uid>"), std::to_string(uid));
249 proc_path = regex_replace(proc_path, std::regex("<pid>"), std::to_string(pid));
250
251 return proc_path.append(CGROUP_PROCS_FILE);
252}
253
254bool CgroupController::GetTaskGroup(int tid, std::string* group) const {
255 std::string file_name = StringPrintf("/proc/%d/cgroup", tid);
256 std::string content;
257 if (!android::base::ReadFileToString(file_name, &content)) {
258 LOG(ERROR) << "Failed to read " << file_name;
259 return false;
260 }
261
262 // if group is null and tid exists return early because
263 // user is not interested in cgroup membership
264 if (group == nullptr) {
265 return true;
266 }
267
268 std::string cg_tag = StringPrintf(":%s:", name_);
269 size_t start_pos = content.find(cg_tag);
270 if (start_pos == std::string::npos) {
271 return false;
272 }
273
274 start_pos += cg_tag.length() + 1; // skip '/'
275 size_t end_pos = content.find('\n', start_pos);
276 if (end_pos == std::string::npos) {
277 *group = content.substr(start_pos, std::string::npos);
278 } else {
279 *group = content.substr(start_pos, end_pos - start_pos);
280 }
281
282 return true;
283}
284
285CgroupDescriptor::CgroupDescriptor(uint32_t version, const std::string& name,
286 const std::string& path, mode_t mode, const std::string& uid,
287 const std::string& gid)
288 : controller_(version, name, path), mode_(mode), uid_(uid), gid_(gid) {}
289
290CgroupMap::CgroupMap() : cg_file_data_(nullptr), cg_file_size_(0) {
291 if (!LoadRcFile()) {
292 PLOG(ERROR) << "CgroupMap::LoadRcFile called for [" << getpid() << "] failed";
293 }
294}
295
296CgroupMap::~CgroupMap() {
297 if (cg_file_data_) {
298 munmap(cg_file_data_, cg_file_size_);
299 cg_file_data_ = nullptr;
300 cg_file_size_ = 0;
301 }
302}
303
304CgroupMap& CgroupMap::GetInstance() {
305 static CgroupMap instance;
306 return instance;
307}
308
309bool CgroupMap::LoadRcFile() {
310 struct stat sb;
311
312 if (cg_file_data_) {
313 // Data already initialized
314 return true;
315 }
316
317 std::string cgroup_rc_path = StringPrintf("%s/%s", CGROUPS_RC_DIR, CGROUPS_RC_FILE);
318 unique_fd fd(TEMP_FAILURE_RETRY(open(cgroup_rc_path.c_str(), O_RDONLY | O_CLOEXEC)));
319 if (fd < 0) {
320 PLOG(ERROR) << "open() failed for " << cgroup_rc_path;
321 return false;
322 }
323
324 if (fstat(fd, &sb) < 0) {
325 PLOG(ERROR) << "fstat() failed for " << cgroup_rc_path;
326 return false;
327 }
328
329 cg_file_size_ = sb.st_size;
330 if (cg_file_size_ < sizeof(CgroupFile)) {
331 PLOG(ERROR) << "Invalid file format " << cgroup_rc_path;
332 return false;
333 }
334
335 cg_file_data_ = (CgroupFile*)mmap(nullptr, cg_file_size_, PROT_READ, MAP_SHARED, fd, 0);
336 if (cg_file_data_ == MAP_FAILED) {
337 PLOG(ERROR) << "Failed to mmap " << cgroup_rc_path;
338 return false;
339 }
340
341 if (cg_file_data_->version_ != CgroupFile::FILE_CURR_VERSION) {
342 PLOG(ERROR) << cgroup_rc_path << " file version mismatch";
343 return false;
344 }
345
346 return true;
347}
348
349void CgroupMap::Print() {
350 LOG(INFO) << "File version = " << cg_file_data_->version_;
351 LOG(INFO) << "File controller count = " << cg_file_data_->controller_count_;
352
353 LOG(INFO) << "Mounted cgroups:";
354 CgroupController* controller = (CgroupController*)(cg_file_data_ + 1);
355 for (int i = 0; i < cg_file_data_->controller_count_; i++, controller++) {
356 LOG(INFO) << "\t" << controller->name() << " ver " << controller->version() << " path "
357 << controller->path();
358 }
359}
360
361bool CgroupMap::SetupCgroups() {
362 std::map<std::string, CgroupDescriptor> descriptors;
363
364 // load cgroups.json file
365 if (!ReadDescriptors(&descriptors)) {
366 PLOG(ERROR) << "Failed to load cgroup description file";
367 return false;
368 }
369
370 // setup cgroups
371 for (const auto& [name, descriptor] : descriptors) {
372 if (!SetupCgroup(descriptor)) {
373 // issue a warning and proceed with the next cgroup
374 // TODO: mark the descriptor as invalid and skip it in WriteRcFile()
375 LOG(WARNING) << "Failed to setup " << name << " cgroup";
376 }
377 }
378
379 // mkdir <CGROUPS_RC_DIR> 0711 system system
380 if (!Mkdir(CGROUPS_RC_DIR, 0711, "system", "system")) {
381 PLOG(ERROR) << "Failed to create directory for <CGROUPS_RC_FILE> file";
382 return false;
383 }
384
385 // Generate <CGROUPS_RC_FILE> file which can be directly mmapped into
386 // process memory. This optimizes performance, memory usage
387 // and limits infrormation shared with unprivileged processes
388 // to the minimum subset of information from cgroups.json
389 if (!WriteRcFile(descriptors)) {
390 LOG(ERROR) << "Failed to write " << CGROUPS_RC_FILE << " file";
391 return false;
392 }
393
394 std::string cgroup_rc_path = StringPrintf("%s/%s", CGROUPS_RC_DIR, CGROUPS_RC_FILE);
395 // chmod 0644 <cgroup_rc_path>
396 if (fchmodat(AT_FDCWD, cgroup_rc_path.c_str(), 0644, AT_SYMLINK_NOFOLLOW) < 0) {
397 LOG(ERROR) << "fchmodat() failed";
398 return false;
399 }
400
401 return true;
402}
403
404const CgroupController* CgroupMap::FindController(const std::string& name) const {
405 if (!cg_file_data_) {
406 return nullptr;
407 }
408
409 // skip the file header to get to the first controller
410 CgroupController* controller = (CgroupController*)(cg_file_data_ + 1);
411 for (int i = 0; i < cg_file_data_->controller_count_; i++, controller++) {
412 if (name == controller->name()) {
413 return controller;
414 }
415 }
416
417 return nullptr;
418}