blob: 12cfb7e62679d36819fe09b23a5531e22cf99ea8 [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,
131 CgroupDescriptor(1, name, cgroups[i]["Path"].asString(), cgroups[i]["Mode"].asInt(),
132 cgroups[i]["UID"].asString(), cgroups[i]["GID"].asString())));
133 }
134
135 Json::Value cgroups2 = root["Cgroups2"];
136 descriptors->emplace(std::make_pair(
137 CGROUPV2_CONTROLLER_NAME,
138 CgroupDescriptor(2, CGROUPV2_CONTROLLER_NAME, cgroups2["Path"].asString(),
139 cgroups2["Mode"].asInt(), cgroups2["UID"].asString(),
140 cgroups2["GID"].asString())));
141
142 return true;
143}
144
Suren Baghdasaryanff25a5f2019-02-02 23:12:01 -0800145// To avoid issues in sdk_mac build
146#if defined(__ANDROID__)
147
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800148static bool SetupCgroup(const CgroupDescriptor& descriptor) {
149 const CgroupController* controller = descriptor.controller();
150
151 // mkdir <path> [mode] [owner] [group]
152 if (!Mkdir(controller->path(), descriptor.mode(), descriptor.uid(), descriptor.gid())) {
153 PLOG(ERROR) << "Failed to create directory for " << controller->name() << " cgroup";
154 return false;
155 }
156
157 int result;
158 if (controller->version() == 2) {
159 result = mount("none", controller->path(), "cgroup2", MS_NODEV | MS_NOEXEC | MS_NOSUID,
160 nullptr);
161 } else {
162 // Unfortunately historically cpuset controller was mounted using a mount command
163 // different from all other controllers. This results in controller attributes not
164 // to be prepended with controller name. For example this way instead of
165 // /dev/cpuset/cpuset.cpus the attribute becomes /dev/cpuset/cpus which is what
166 // the system currently expects.
167 if (!strcmp(controller->name(), "cpuset")) {
168 // mount cpuset none /dev/cpuset nodev noexec nosuid
169 result = mount("none", controller->path(), controller->name(),
170 MS_NODEV | MS_NOEXEC | MS_NOSUID, nullptr);
171 } else {
172 // mount cgroup none <path> nodev noexec nosuid <controller>
173 result = mount("none", controller->path(), "cgroup", MS_NODEV | MS_NOEXEC | MS_NOSUID,
174 controller->name());
175 }
176 }
177
178 if (result < 0) {
179 PLOG(ERROR) << "Failed to mount " << controller->name() << " cgroup";
180 return false;
181 }
182
183 return true;
184}
185
Suren Baghdasaryanff25a5f2019-02-02 23:12:01 -0800186#else
187
188// Stubs for non-Android targets.
189static bool SetupCgroup(const CgroupDescriptor&) {
190 return false;
191}
192
193#endif
194
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800195static bool WriteRcFile(const std::map<std::string, CgroupDescriptor>& descriptors) {
196 std::string cgroup_rc_path = StringPrintf("%s/%s", CGROUPS_RC_DIR, CgroupMap::CGROUPS_RC_FILE);
197 unique_fd fd(TEMP_FAILURE_RETRY(open(cgroup_rc_path.c_str(),
198 O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC,
199 S_IRUSR | S_IRGRP | S_IROTH)));
200 if (fd < 0) {
201 PLOG(ERROR) << "open() failed for " << cgroup_rc_path;
202 return false;
203 }
204
205 CgroupFile fl;
206 fl.version_ = CgroupFile::FILE_CURR_VERSION;
207 fl.controller_count_ = descriptors.size();
208 int ret = TEMP_FAILURE_RETRY(write(fd, &fl, sizeof(fl)));
209 if (ret < 0) {
210 PLOG(ERROR) << "write() failed for " << cgroup_rc_path;
211 return false;
212 }
213
214 for (const auto& [name, descriptor] : descriptors) {
215 ret = TEMP_FAILURE_RETRY(write(fd, descriptor.controller(), sizeof(CgroupController)));
216 if (ret < 0) {
217 PLOG(ERROR) << "write() failed for " << cgroup_rc_path;
218 return false;
219 }
220 }
221
222 return true;
223}
224
225CgroupController::CgroupController(uint32_t version, const std::string& name,
226 const std::string& path) {
227 version_ = version;
228 strncpy(name_, name.c_str(), sizeof(name_) - 1);
229 name_[sizeof(name_) - 1] = '\0';
230 strncpy(path_, path.c_str(), sizeof(path_) - 1);
231 path_[sizeof(path_) - 1] = '\0';
232}
233
234std::string CgroupController::GetTasksFilePath(const std::string& path) const {
235 std::string tasks_path = path_;
236
237 if (!path.empty()) {
238 tasks_path += "/" + path;
239 }
240 return (version_ == 1) ? tasks_path + CGROUP_TASKS_FILE : tasks_path + CGROUP_TASKS_FILE_V2;
241}
242
243std::string CgroupController::GetProcsFilePath(const std::string& path, uid_t uid,
244 pid_t pid) const {
245 std::string proc_path(path_);
246 proc_path.append("/").append(path);
247 proc_path = regex_replace(proc_path, std::regex("<uid>"), std::to_string(uid));
248 proc_path = regex_replace(proc_path, std::regex("<pid>"), std::to_string(pid));
249
250 return proc_path.append(CGROUP_PROCS_FILE);
251}
252
253bool CgroupController::GetTaskGroup(int tid, std::string* group) const {
254 std::string file_name = StringPrintf("/proc/%d/cgroup", tid);
255 std::string content;
256 if (!android::base::ReadFileToString(file_name, &content)) {
257 LOG(ERROR) << "Failed to read " << file_name;
258 return false;
259 }
260
261 // if group is null and tid exists return early because
262 // user is not interested in cgroup membership
263 if (group == nullptr) {
264 return true;
265 }
266
267 std::string cg_tag = StringPrintf(":%s:", name_);
268 size_t start_pos = content.find(cg_tag);
269 if (start_pos == std::string::npos) {
270 return false;
271 }
272
273 start_pos += cg_tag.length() + 1; // skip '/'
274 size_t end_pos = content.find('\n', start_pos);
275 if (end_pos == std::string::npos) {
276 *group = content.substr(start_pos, std::string::npos);
277 } else {
278 *group = content.substr(start_pos, end_pos - start_pos);
279 }
280
281 return true;
282}
283
284CgroupDescriptor::CgroupDescriptor(uint32_t version, const std::string& name,
285 const std::string& path, mode_t mode, const std::string& uid,
286 const std::string& gid)
287 : controller_(version, name, path), mode_(mode), uid_(uid), gid_(gid) {}
288
289CgroupMap::CgroupMap() : cg_file_data_(nullptr), cg_file_size_(0) {
290 if (!LoadRcFile()) {
291 PLOG(ERROR) << "CgroupMap::LoadRcFile called for [" << getpid() << "] failed";
292 }
293}
294
295CgroupMap::~CgroupMap() {
296 if (cg_file_data_) {
297 munmap(cg_file_data_, cg_file_size_);
298 cg_file_data_ = nullptr;
299 cg_file_size_ = 0;
300 }
301}
302
303CgroupMap& CgroupMap::GetInstance() {
304 static CgroupMap instance;
305 return instance;
306}
307
308bool CgroupMap::LoadRcFile() {
309 struct stat sb;
310
311 if (cg_file_data_) {
312 // Data already initialized
313 return true;
314 }
315
316 std::string cgroup_rc_path = StringPrintf("%s/%s", CGROUPS_RC_DIR, CGROUPS_RC_FILE);
317 unique_fd fd(TEMP_FAILURE_RETRY(open(cgroup_rc_path.c_str(), O_RDONLY | O_CLOEXEC)));
318 if (fd < 0) {
319 PLOG(ERROR) << "open() failed for " << cgroup_rc_path;
320 return false;
321 }
322
323 if (fstat(fd, &sb) < 0) {
324 PLOG(ERROR) << "fstat() failed for " << cgroup_rc_path;
325 return false;
326 }
327
328 cg_file_size_ = sb.st_size;
329 if (cg_file_size_ < sizeof(CgroupFile)) {
330 PLOG(ERROR) << "Invalid file format " << cgroup_rc_path;
331 return false;
332 }
333
334 cg_file_data_ = (CgroupFile*)mmap(nullptr, cg_file_size_, PROT_READ, MAP_SHARED, fd, 0);
335 if (cg_file_data_ == MAP_FAILED) {
336 PLOG(ERROR) << "Failed to mmap " << cgroup_rc_path;
337 return false;
338 }
339
340 if (cg_file_data_->version_ != CgroupFile::FILE_CURR_VERSION) {
341 PLOG(ERROR) << cgroup_rc_path << " file version mismatch";
342 return false;
343 }
344
345 return true;
346}
347
348void CgroupMap::Print() {
349 LOG(INFO) << "File version = " << cg_file_data_->version_;
350 LOG(INFO) << "File controller count = " << cg_file_data_->controller_count_;
351
352 LOG(INFO) << "Mounted cgroups:";
353 CgroupController* controller = (CgroupController*)(cg_file_data_ + 1);
354 for (int i = 0; i < cg_file_data_->controller_count_; i++, controller++) {
355 LOG(INFO) << "\t" << controller->name() << " ver " << controller->version() << " path "
356 << controller->path();
357 }
358}
359
360bool CgroupMap::SetupCgroups() {
361 std::map<std::string, CgroupDescriptor> descriptors;
362
363 // load cgroups.json file
364 if (!ReadDescriptors(&descriptors)) {
365 PLOG(ERROR) << "Failed to load cgroup description file";
366 return false;
367 }
368
369 // setup cgroups
370 for (const auto& [name, descriptor] : descriptors) {
371 if (!SetupCgroup(descriptor)) {
372 // issue a warning and proceed with the next cgroup
373 // TODO: mark the descriptor as invalid and skip it in WriteRcFile()
374 LOG(WARNING) << "Failed to setup " << name << " cgroup";
375 }
376 }
377
378 // mkdir <CGROUPS_RC_DIR> 0711 system system
379 if (!Mkdir(CGROUPS_RC_DIR, 0711, "system", "system")) {
380 PLOG(ERROR) << "Failed to create directory for <CGROUPS_RC_FILE> file";
381 return false;
382 }
383
384 // Generate <CGROUPS_RC_FILE> file which can be directly mmapped into
385 // process memory. This optimizes performance, memory usage
386 // and limits infrormation shared with unprivileged processes
387 // to the minimum subset of information from cgroups.json
388 if (!WriteRcFile(descriptors)) {
389 LOG(ERROR) << "Failed to write " << CGROUPS_RC_FILE << " file";
390 return false;
391 }
392
393 std::string cgroup_rc_path = StringPrintf("%s/%s", CGROUPS_RC_DIR, CGROUPS_RC_FILE);
394 // chmod 0644 <cgroup_rc_path>
395 if (fchmodat(AT_FDCWD, cgroup_rc_path.c_str(), 0644, AT_SYMLINK_NOFOLLOW) < 0) {
396 LOG(ERROR) << "fchmodat() failed";
397 return false;
398 }
399
400 return true;
401}
402
403const CgroupController* CgroupMap::FindController(const std::string& name) const {
404 if (!cg_file_data_) {
405 return nullptr;
406 }
407
408 // skip the file header to get to the first controller
409 CgroupController* controller = (CgroupController*)(cg_file_data_ + 1);
410 for (int i = 0; i < cg_file_data_->controller_count_; i++, controller++) {
411 if (name == controller->name()) {
412 return controller;
413 }
414 }
415
416 return nullptr;
417}