blob: b3b497f684343dc38bfef11c603364ca925a4d67 [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>
Suren Baghdasaryane3ad8882019-02-06 13:25:29 -080022#include <grp.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080023#include <pwd.h>
24#include <sys/mman.h>
25#include <sys/mount.h>
26#include <sys/stat.h>
27#include <sys/types.h>
28#include <time.h>
29#include <unistd.h>
30
31#include <regex>
32
33#include <android-base/file.h>
34#include <android-base/logging.h>
35#include <android-base/properties.h>
36#include <android-base/stringprintf.h>
37#include <android-base/unique_fd.h>
38#include <cgroup_map.h>
39#include <json/reader.h>
40#include <json/value.h>
41#include <processgroup/processgroup.h>
42
43using android::base::GetBoolProperty;
44using android::base::StringPrintf;
45using android::base::unique_fd;
46
47static constexpr const char* CGROUPS_DESC_FILE = "/etc/cgroups.json";
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -080048static constexpr const char* CGROUPS_DESC_VENDOR_FILE = "/vendor/etc/cgroups.json";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080049
50static constexpr const char* CGROUP_PROCS_FILE = "/cgroup.procs";
51static constexpr const char* CGROUP_TASKS_FILE = "/tasks";
52static constexpr const char* CGROUP_TASKS_FILE_V2 = "/cgroup.tasks";
53
54static bool Mkdir(const std::string& path, mode_t mode, const std::string& uid,
55 const std::string& gid) {
56 if (mode == 0) {
57 mode = 0755;
58 }
59
60 if (mkdir(path.c_str(), mode) != 0) {
61 /* chmod in case the directory already exists */
62 if (errno == EEXIST) {
63 if (fchmodat(AT_FDCWD, path.c_str(), mode, AT_SYMLINK_NOFOLLOW) != 0) {
64 // /acct is a special case when the directory already exists
65 // TODO: check if file mode is already what we want instead of using EROFS
66 if (errno != EROFS) {
67 PLOG(ERROR) << "fchmodat() failed for " << path;
68 return false;
69 }
70 }
71 } else {
72 PLOG(ERROR) << "mkdir() failed for " << path;
73 return false;
74 }
75 }
76
Suren Baghdasaryane3ad8882019-02-06 13:25:29 -080077 if (uid.empty()) {
78 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080079 }
80
Suren Baghdasaryane3ad8882019-02-06 13:25:29 -080081 passwd* uid_pwd = getpwnam(uid.c_str());
82 if (!uid_pwd) {
83 PLOG(ERROR) << "Unable to decode UID for '" << uid << "'";
84 return false;
85 }
86
87 uid_t pw_uid = uid_pwd->pw_uid;
88 gid_t gr_gid = -1;
89 if (!gid.empty()) {
90 group* gid_pwd = getgrnam(gid.c_str());
91 if (!gid_pwd) {
92 PLOG(ERROR) << "Unable to decode GID for '" << gid << "'";
93 return false;
94 }
95 gr_gid = gid_pwd->gr_gid;
96 }
97
98 if (lchown(path.c_str(), pw_uid, gr_gid) < 0) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080099 PLOG(ERROR) << "lchown() failed for " << path;
100 return false;
101 }
102
103 /* chown may have cleared S_ISUID and S_ISGID, chmod again */
104 if (mode & (S_ISUID | S_ISGID)) {
105 if (fchmodat(AT_FDCWD, path.c_str(), mode, AT_SYMLINK_NOFOLLOW) != 0) {
106 PLOG(ERROR) << "fchmodat() failed for " << path;
107 return false;
108 }
109 }
110
111 return true;
112}
113
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800114static bool ReadDescriptorsFromFile(const std::string& file_name,
115 std::map<std::string, CgroupDescriptor>* descriptors) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800116 std::vector<CgroupDescriptor> result;
117 std::string json_doc;
118
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800119 if (!android::base::ReadFileToString(file_name, &json_doc)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800120 PLOG(ERROR) << "Failed to read task profiles from " << file_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800121 return false;
122 }
123
124 Json::Reader reader;
125 Json::Value root;
126 if (!reader.parse(json_doc, root)) {
127 LOG(ERROR) << "Failed to parse cgroups description: " << reader.getFormattedErrorMessages();
128 return false;
129 }
130
Suren Baghdasaryand032a922019-02-12 18:20:38 -0800131 if (root.isMember("Cgroups")) {
132 const Json::Value& cgroups = root["Cgroups"];
133 for (Json::Value::ArrayIndex i = 0; i < cgroups.size(); ++i) {
134 std::string name = cgroups[i]["Controller"].asString();
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800135 auto iter = descriptors->find(name);
136 if (iter == descriptors->end()) {
137 descriptors->emplace(name, CgroupDescriptor(1, name, cgroups[i]["Path"].asString(),
Suren Baghdasaryand032a922019-02-12 18:20:38 -0800138 std::strtoul(cgroups[i]["Mode"].asString().c_str(), 0, 8),
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800139 cgroups[i]["UID"].asString(), cgroups[i]["GID"].asString()));
140 } else {
141 iter->second = CgroupDescriptor(1, name, cgroups[i]["Path"].asString(),
142 std::strtoul(cgroups[i]["Mode"].asString().c_str(), 0, 8),
143 cgroups[i]["UID"].asString(), cgroups[i]["GID"].asString());
144 }
Suren Baghdasaryand032a922019-02-12 18:20:38 -0800145 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800146 }
147
Suren Baghdasaryand032a922019-02-12 18:20:38 -0800148 if (root.isMember("Cgroups2")) {
149 const Json::Value& cgroups2 = root["Cgroups2"];
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800150 auto iter = descriptors->find(CGROUPV2_CONTROLLER_NAME);
151 if (iter == descriptors->end()) {
152 descriptors->emplace(CGROUPV2_CONTROLLER_NAME, CgroupDescriptor(2, CGROUPV2_CONTROLLER_NAME, cgroups2["Path"].asString(),
Suren Baghdasaryand032a922019-02-12 18:20:38 -0800153 std::strtoul(cgroups2["Mode"].asString().c_str(), 0, 8),
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800154 cgroups2["UID"].asString(), cgroups2["GID"].asString()));
155 } else {
156 iter->second = CgroupDescriptor(2, CGROUPV2_CONTROLLER_NAME, cgroups2["Path"].asString(),
157 std::strtoul(cgroups2["Mode"].asString().c_str(), 0, 8),
158 cgroups2["UID"].asString(), cgroups2["GID"].asString());
159 }
160 }
161
162 return true;
163}
164
165static bool ReadDescriptors(std::map<std::string, CgroupDescriptor>* descriptors) {
166 // load system cgroup descriptors
167 if (!ReadDescriptorsFromFile(CGROUPS_DESC_FILE, descriptors)) {
168 return false;
169 }
170
171 // load vendor cgroup descriptors if the file exists
172 if (!access(CGROUPS_DESC_VENDOR_FILE, F_OK) &&
173 !ReadDescriptorsFromFile(CGROUPS_DESC_VENDOR_FILE, descriptors)) {
174 return false;
Suren Baghdasaryand032a922019-02-12 18:20:38 -0800175 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800176
177 return true;
178}
179
Suren Baghdasaryanff25a5f2019-02-02 23:12:01 -0800180// To avoid issues in sdk_mac build
181#if defined(__ANDROID__)
182
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800183static bool SetupCgroup(const CgroupDescriptor& descriptor) {
184 const CgroupController* controller = descriptor.controller();
185
186 // mkdir <path> [mode] [owner] [group]
187 if (!Mkdir(controller->path(), descriptor.mode(), descriptor.uid(), descriptor.gid())) {
Wei Wangd71d3012019-03-07 11:59:12 -0800188 LOG(ERROR) << "Failed to create directory for " << controller->name() << " cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800189 return false;
190 }
191
192 int result;
193 if (controller->version() == 2) {
194 result = mount("none", controller->path(), "cgroup2", MS_NODEV | MS_NOEXEC | MS_NOSUID,
195 nullptr);
196 } else {
197 // Unfortunately historically cpuset controller was mounted using a mount command
198 // different from all other controllers. This results in controller attributes not
199 // to be prepended with controller name. For example this way instead of
200 // /dev/cpuset/cpuset.cpus the attribute becomes /dev/cpuset/cpus which is what
201 // the system currently expects.
202 if (!strcmp(controller->name(), "cpuset")) {
203 // mount cpuset none /dev/cpuset nodev noexec nosuid
204 result = mount("none", controller->path(), controller->name(),
205 MS_NODEV | MS_NOEXEC | MS_NOSUID, nullptr);
206 } else {
207 // mount cgroup none <path> nodev noexec nosuid <controller>
208 result = mount("none", controller->path(), "cgroup", MS_NODEV | MS_NOEXEC | MS_NOSUID,
209 controller->name());
210 }
211 }
212
213 if (result < 0) {
214 PLOG(ERROR) << "Failed to mount " << controller->name() << " cgroup";
215 return false;
216 }
217
218 return true;
219}
220
Suren Baghdasaryanff25a5f2019-02-02 23:12:01 -0800221#else
222
223// Stubs for non-Android targets.
224static bool SetupCgroup(const CgroupDescriptor&) {
225 return false;
226}
227
228#endif
229
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800230static bool WriteRcFile(const std::map<std::string, CgroupDescriptor>& descriptors) {
231 std::string cgroup_rc_path = StringPrintf("%s/%s", CGROUPS_RC_DIR, CgroupMap::CGROUPS_RC_FILE);
232 unique_fd fd(TEMP_FAILURE_RETRY(open(cgroup_rc_path.c_str(),
233 O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC,
234 S_IRUSR | S_IRGRP | S_IROTH)));
235 if (fd < 0) {
236 PLOG(ERROR) << "open() failed for " << cgroup_rc_path;
237 return false;
238 }
239
240 CgroupFile fl;
241 fl.version_ = CgroupFile::FILE_CURR_VERSION;
242 fl.controller_count_ = descriptors.size();
243 int ret = TEMP_FAILURE_RETRY(write(fd, &fl, sizeof(fl)));
244 if (ret < 0) {
245 PLOG(ERROR) << "write() failed for " << cgroup_rc_path;
246 return false;
247 }
248
249 for (const auto& [name, descriptor] : descriptors) {
250 ret = TEMP_FAILURE_RETRY(write(fd, descriptor.controller(), sizeof(CgroupController)));
251 if (ret < 0) {
252 PLOG(ERROR) << "write() failed for " << cgroup_rc_path;
253 return false;
254 }
255 }
256
257 return true;
258}
259
260CgroupController::CgroupController(uint32_t version, const std::string& name,
261 const std::string& path) {
262 version_ = version;
263 strncpy(name_, name.c_str(), sizeof(name_) - 1);
264 name_[sizeof(name_) - 1] = '\0';
265 strncpy(path_, path.c_str(), sizeof(path_) - 1);
266 path_[sizeof(path_) - 1] = '\0';
267}
268
269std::string CgroupController::GetTasksFilePath(const std::string& path) const {
270 std::string tasks_path = path_;
271
272 if (!path.empty()) {
273 tasks_path += "/" + path;
274 }
275 return (version_ == 1) ? tasks_path + CGROUP_TASKS_FILE : tasks_path + CGROUP_TASKS_FILE_V2;
276}
277
278std::string CgroupController::GetProcsFilePath(const std::string& path, uid_t uid,
279 pid_t pid) const {
280 std::string proc_path(path_);
281 proc_path.append("/").append(path);
282 proc_path = regex_replace(proc_path, std::regex("<uid>"), std::to_string(uid));
283 proc_path = regex_replace(proc_path, std::regex("<pid>"), std::to_string(pid));
284
285 return proc_path.append(CGROUP_PROCS_FILE);
286}
287
288bool CgroupController::GetTaskGroup(int tid, std::string* group) const {
289 std::string file_name = StringPrintf("/proc/%d/cgroup", tid);
290 std::string content;
291 if (!android::base::ReadFileToString(file_name, &content)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800292 PLOG(ERROR) << "Failed to read " << file_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800293 return false;
294 }
295
296 // if group is null and tid exists return early because
297 // user is not interested in cgroup membership
298 if (group == nullptr) {
299 return true;
300 }
301
302 std::string cg_tag = StringPrintf(":%s:", name_);
303 size_t start_pos = content.find(cg_tag);
304 if (start_pos == std::string::npos) {
305 return false;
306 }
307
308 start_pos += cg_tag.length() + 1; // skip '/'
309 size_t end_pos = content.find('\n', start_pos);
310 if (end_pos == std::string::npos) {
311 *group = content.substr(start_pos, std::string::npos);
312 } else {
313 *group = content.substr(start_pos, end_pos - start_pos);
314 }
315
316 return true;
317}
318
319CgroupDescriptor::CgroupDescriptor(uint32_t version, const std::string& name,
320 const std::string& path, mode_t mode, const std::string& uid,
321 const std::string& gid)
322 : controller_(version, name, path), mode_(mode), uid_(uid), gid_(gid) {}
323
324CgroupMap::CgroupMap() : cg_file_data_(nullptr), cg_file_size_(0) {
325 if (!LoadRcFile()) {
Wei Wangd71d3012019-03-07 11:59:12 -0800326 LOG(ERROR) << "CgroupMap::LoadRcFile called for [" << getpid() << "] failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800327 }
328}
329
330CgroupMap::~CgroupMap() {
331 if (cg_file_data_) {
332 munmap(cg_file_data_, cg_file_size_);
333 cg_file_data_ = nullptr;
334 cg_file_size_ = 0;
335 }
336}
337
338CgroupMap& CgroupMap::GetInstance() {
Peter Collingbournedba6d442019-03-20 21:09:46 -0700339 // Deliberately leak this object to avoid a race between destruction on
340 // process exit and concurrent access from another thread.
341 static auto* instance = new CgroupMap;
342 return *instance;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800343}
344
345bool CgroupMap::LoadRcFile() {
346 struct stat sb;
347
348 if (cg_file_data_) {
349 // Data already initialized
350 return true;
351 }
352
353 std::string cgroup_rc_path = StringPrintf("%s/%s", CGROUPS_RC_DIR, CGROUPS_RC_FILE);
354 unique_fd fd(TEMP_FAILURE_RETRY(open(cgroup_rc_path.c_str(), O_RDONLY | O_CLOEXEC)));
355 if (fd < 0) {
356 PLOG(ERROR) << "open() failed for " << cgroup_rc_path;
357 return false;
358 }
359
360 if (fstat(fd, &sb) < 0) {
361 PLOG(ERROR) << "fstat() failed for " << cgroup_rc_path;
362 return false;
363 }
364
Wei Wangd71d3012019-03-07 11:59:12 -0800365 size_t file_size = sb.st_size;
366 if (file_size < sizeof(CgroupFile)) {
367 LOG(ERROR) << "Invalid file format " << cgroup_rc_path;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800368 return false;
369 }
370
Wei Wangd71d3012019-03-07 11:59:12 -0800371 CgroupFile* file_data = (CgroupFile*)mmap(nullptr, file_size, PROT_READ, MAP_SHARED, fd, 0);
372 if (file_data == MAP_FAILED) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800373 PLOG(ERROR) << "Failed to mmap " << cgroup_rc_path;
374 return false;
375 }
376
Wei Wangd71d3012019-03-07 11:59:12 -0800377 if (file_data->version_ != CgroupFile::FILE_CURR_VERSION) {
378 LOG(ERROR) << cgroup_rc_path << " file version mismatch";
379 munmap(file_data, file_size);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800380 return false;
381 }
382
Wei Wangd71d3012019-03-07 11:59:12 -0800383 if (file_size != sizeof(CgroupFile) + file_data->controller_count_ * sizeof(CgroupController)) {
384 LOG(ERROR) << cgroup_rc_path << " file has invalid size";
385 munmap(file_data, file_size);
386 return false;
387 }
388
389 cg_file_data_ = file_data;
390 cg_file_size_ = file_size;
391
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800392 return true;
393}
394
Wei Wangd71d3012019-03-07 11:59:12 -0800395void CgroupMap::Print() const {
396 if (!cg_file_data_) {
397 LOG(ERROR) << "CgroupMap::Print called for [" << getpid()
398 << "] failed, RC file was not initialized properly";
399 return;
400 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800401 LOG(INFO) << "File version = " << cg_file_data_->version_;
402 LOG(INFO) << "File controller count = " << cg_file_data_->controller_count_;
403
404 LOG(INFO) << "Mounted cgroups:";
405 CgroupController* controller = (CgroupController*)(cg_file_data_ + 1);
406 for (int i = 0; i < cg_file_data_->controller_count_; i++, controller++) {
407 LOG(INFO) << "\t" << controller->name() << " ver " << controller->version() << " path "
408 << controller->path();
409 }
410}
411
412bool CgroupMap::SetupCgroups() {
413 std::map<std::string, CgroupDescriptor> descriptors;
414
415 // load cgroups.json file
416 if (!ReadDescriptors(&descriptors)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800417 LOG(ERROR) << "Failed to load cgroup description file";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800418 return false;
419 }
420
421 // setup cgroups
422 for (const auto& [name, descriptor] : descriptors) {
423 if (!SetupCgroup(descriptor)) {
424 // issue a warning and proceed with the next cgroup
425 // TODO: mark the descriptor as invalid and skip it in WriteRcFile()
426 LOG(WARNING) << "Failed to setup " << name << " cgroup";
427 }
428 }
429
430 // mkdir <CGROUPS_RC_DIR> 0711 system system
431 if (!Mkdir(CGROUPS_RC_DIR, 0711, "system", "system")) {
Wei Wangd71d3012019-03-07 11:59:12 -0800432 LOG(ERROR) << "Failed to create directory for <CGROUPS_RC_FILE> file";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800433 return false;
434 }
435
436 // Generate <CGROUPS_RC_FILE> file which can be directly mmapped into
437 // process memory. This optimizes performance, memory usage
438 // and limits infrormation shared with unprivileged processes
439 // to the minimum subset of information from cgroups.json
440 if (!WriteRcFile(descriptors)) {
441 LOG(ERROR) << "Failed to write " << CGROUPS_RC_FILE << " file";
442 return false;
443 }
444
445 std::string cgroup_rc_path = StringPrintf("%s/%s", CGROUPS_RC_DIR, CGROUPS_RC_FILE);
446 // chmod 0644 <cgroup_rc_path>
447 if (fchmodat(AT_FDCWD, cgroup_rc_path.c_str(), 0644, AT_SYMLINK_NOFOLLOW) < 0) {
Wei Wangd71d3012019-03-07 11:59:12 -0800448 PLOG(ERROR) << "fchmodat() failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800449 return false;
450 }
451
452 return true;
453}
454
455const CgroupController* CgroupMap::FindController(const std::string& name) const {
456 if (!cg_file_data_) {
Wei Wangd71d3012019-03-07 11:59:12 -0800457 LOG(ERROR) << "CgroupMap::FindController called for [" << getpid()
458 << "] failed, RC file was not initialized properly";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800459 return nullptr;
460 }
461
462 // skip the file header to get to the first controller
463 CgroupController* controller = (CgroupController*)(cg_file_data_ + 1);
464 for (int i = 0; i < cg_file_data_->controller_count_; i++, controller++) {
465 if (name == controller->name()) {
466 return controller;
467 }
468 }
469
470 return nullptr;
471}