blob: 51c810e9886eab18905d32801783f1c44310811a [file] [log] [blame]
Colin Crosscf8d1c22014-06-03 13:24:21 -07001/*
2 * Copyright 2014 Google, Inc
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 <assert.h>
21#include <dirent.h>
Elliott Hughes0badbd62014-12-29 12:24:25 -080022#include <errno.h>
Colin Crosscf8d1c22014-06-03 13:24:21 -070023#include <fcntl.h>
Chih-Hung Hsiehfcc81152014-11-20 17:05:15 -080024#include <inttypes.h>
Tom Cherry574a0812018-02-23 13:04:40 -080025#include <signal.h>
Colin Crosscf8d1c22014-06-03 13:24:21 -070026#include <stdio.h>
27#include <stdlib.h>
Colin Crosscf8d1c22014-06-03 13:24:21 -070028#include <sys/stat.h>
29#include <sys/types.h>
Tom Cherry70a5ed42017-06-05 19:20:17 -070030#include <unistd.h>
Collin Mullinerf7e79b92016-06-01 21:03:55 +000031
32#include <chrono>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080033#include <map>
James Hawkins588a2ca2016-02-18 14:52:46 -080034#include <memory>
Elliott Hughes8d532e42016-06-06 21:19:55 -070035#include <mutex>
Tom Cherry70a5ed42017-06-05 19:20:17 -070036#include <set>
Tom Cherry574a0812018-02-23 13:04:40 -080037#include <string>
Elliott Hughes290a2282016-11-14 17:08:47 -080038#include <thread>
Colin Crosscf8d1c22014-06-03 13:24:21 -070039
Robert Benead4852262017-07-16 19:38:11 -070040#include <android-base/file.h>
Elliott Hughes171df0a2016-08-02 13:30:30 -070041#include <android-base/logging.h>
Suren Baghdasaryanbc131c32018-05-23 12:30:44 -070042#include <android-base/properties.h>
Tom Cherry574a0812018-02-23 13:04:40 -080043#include <android-base/stringprintf.h>
44#include <android-base/strings.h>
Suren Baghdasaryan7bf43812019-01-25 05:29:55 +000045#include <cutils/android_filesystem_config.h>
Colin Crosscf8d1c22014-06-03 13:24:21 -070046#include <processgroup/processgroup.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080047#include <task_profiles.h>
Martijn Coenenb82bab62016-01-20 16:39:16 -080048
Suren Baghdasaryanbc131c32018-05-23 12:30:44 -070049using android::base::GetBoolProperty;
Tom Cherry574a0812018-02-23 13:04:40 -080050using android::base::StartsWith;
51using android::base::StringPrintf;
Robert Benead4852262017-07-16 19:38:11 -070052using android::base::WriteStringToFile;
53
Elliott Hughes290a2282016-11-14 17:08:47 -080054using namespace std::chrono_literals;
55
Martijn Coenenb82bab62016-01-20 16:39:16 -080056#define PROCESSGROUP_CGROUP_PROCS_FILE "/cgroup.procs"
Martijn Coenenb82bab62016-01-20 16:39:16 -080057
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080058bool CgroupGetControllerPath(const std::string& cgroup_name, std::string* path) {
Yifan Hong53e0deb2019-03-22 17:01:08 -070059 auto controller = CgroupMap::GetInstance().FindController(cgroup_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080060
Yifan Hong53e0deb2019-03-22 17:01:08 -070061 if (!controller.HasValue()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080062 return false;
63 }
64
65 if (path) {
Yifan Hong53e0deb2019-03-22 17:01:08 -070066 *path = controller.path();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080067 }
68
69 return true;
70}
71
Bart Van Assche4c957122022-02-04 18:19:45 +000072static bool CgroupGetMemcgAppsPath(std::string* path) {
73 CgroupController controller = CgroupMap::GetInstance().FindController("memory");
74
75 if (!controller.HasValue()) {
76 return false;
77 }
78
79 if (path) {
80 *path = controller.path();
81 if (controller.version() == 1) {
82 *path += "/apps";
83 }
84 }
85
86 return true;
87}
88
Suren Baghdasaryan9e3ace52021-06-16 17:01:19 -070089bool CgroupGetControllerFromPath(const std::string& path, std::string* cgroup_name) {
90 auto controller = CgroupMap::GetInstance().FindControllerByPath(path);
91
92 if (!controller.HasValue()) {
93 return false;
94 }
95
96 if (cgroup_name) {
97 *cgroup_name = controller.name();
98 }
99
100 return true;
101}
102
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800103bool CgroupGetAttributePath(const std::string& attr_name, std::string* path) {
104 const TaskProfiles& tp = TaskProfiles::GetInstance();
Bart Van Assche4c99e962022-02-03 19:50:16 +0000105 const IProfileAttribute* attr = tp.GetAttribute(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800106
107 if (attr == nullptr) {
108 return false;
109 }
110
111 if (path) {
112 *path = StringPrintf("%s/%s", attr->controller()->path(), attr->file_name().c_str());
113 }
114
115 return true;
116}
117
118bool CgroupGetAttributePathForTask(const std::string& attr_name, int tid, std::string* path) {
119 const TaskProfiles& tp = TaskProfiles::GetInstance();
Bart Van Assche4c99e962022-02-03 19:50:16 +0000120 const IProfileAttribute* attr = tp.GetAttribute(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800121
122 if (attr == nullptr) {
123 return false;
124 }
125
126 if (!attr->GetPathForTask(tid, path)) {
127 PLOG(ERROR) << "Failed to find cgroup for tid " << tid;
128 return false;
129 }
130
131 return true;
132}
133
134bool UsePerAppMemcg() {
135 bool low_ram_device = GetBoolProperty("ro.config.low_ram", false);
136 return GetBoolProperty("ro.config.per_app_memcg", low_ram_device);
137}
138
Peter Collingbourned7157c22018-10-30 15:49:33 -0700139static bool isMemoryCgroupSupported() {
Suren Baghdasaryanfa7a05f2019-05-08 17:59:55 -0700140 static bool memcg_supported = CgroupMap::GetInstance().FindController("memory").IsUsable();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800141
Peter Collingbourned7157c22018-10-30 15:49:33 -0700142 return memcg_supported;
Martijn Coenenb82bab62016-01-20 16:39:16 -0800143}
144
Riddle Hsua6abd822019-06-18 15:53:53 -0600145void DropTaskProfilesResourceCaching() {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800146 TaskProfiles::GetInstance().DropResourceCaching(ProfileAction::RCT_TASK);
147 TaskProfiles::GetInstance().DropResourceCaching(ProfileAction::RCT_PROCESS);
Riddle Hsua6abd822019-06-18 15:53:53 -0600148}
149
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800150bool SetProcessProfiles(uid_t uid, pid_t pid, const std::vector<std::string>& profiles) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800151 return TaskProfiles::GetInstance().SetProcessProfiles(uid, pid, profiles, false);
152}
153
154bool SetProcessProfilesCached(uid_t uid, pid_t pid, const std::vector<std::string>& profiles) {
155 return TaskProfiles::GetInstance().SetProcessProfiles(uid, pid, profiles, true);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800156}
157
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800158bool SetTaskProfiles(int tid, const std::vector<std::string>& profiles, bool use_fd_cache) {
Rick Yiu0b211fa2019-09-16 19:07:17 +0800159 return TaskProfiles::GetInstance().SetTaskProfiles(tid, profiles, use_fd_cache);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800160}
161
Jiyong Park8bf59402022-04-01 12:24:22 +0900162// C wrapper for SetProcessProfiles.
163// No need to have this in the header file because this function is specifically for crosvm. Crosvm
164// which is written in Rust has its own declaration of this foreign function and doesn't rely on the
165// header. See
166// https://chromium-review.googlesource.com/c/chromiumos/platform/crosvm/+/3574427/5/src/linux/android.rs#12
167extern "C" bool android_set_process_profiles(uid_t uid, pid_t pid, size_t num_profiles,
168 const char* profiles[]) {
Jiyong Parkcc9932b2022-04-20 17:11:42 +0900169 std::vector<std::string> profiles_;
170 profiles_.reserve(num_profiles);
Jiyong Park8bf59402022-04-01 12:24:22 +0900171 for (size_t i = 0; i < num_profiles; i++) {
172 profiles_.emplace_back(profiles[i]);
173 }
174 return SetProcessProfiles(uid, pid, profiles_);
175}
176
Peter Collingbourned7157c22018-10-30 15:49:33 -0700177static std::string ConvertUidToPath(const char* cgroup, uid_t uid) {
178 return StringPrintf("%s/uid_%d", cgroup, uid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700179}
180
Peter Collingbourned7157c22018-10-30 15:49:33 -0700181static std::string ConvertUidPidToPath(const char* cgroup, uid_t uid, int pid) {
182 return StringPrintf("%s/uid_%d/pid_%d", cgroup, uid, pid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700183}
184
Marco Ballesio4dac8162021-02-10 16:35:44 -0800185static int RemoveProcessGroup(const char* cgroup, uid_t uid, int pid, unsigned int retries) {
186 int ret = 0;
Peter Collingbourned7157c22018-10-30 15:49:33 -0700187 auto uid_pid_path = ConvertUidPidToPath(cgroup, uid, pid);
Peter Collingbourned7157c22018-10-30 15:49:33 -0700188 auto uid_path = ConvertUidToPath(cgroup, uid);
Marco Ballesio4dac8162021-02-10 16:35:44 -0800189
Marco Ballesio4dac8162021-02-10 16:35:44 -0800190 while (retries--) {
191 ret = rmdir(uid_pid_path.c_str());
192 if (!ret || errno != EBUSY) break;
193 std::this_thread::sleep_for(5ms);
194 }
195
Colin Crosscf8d1c22014-06-03 13:24:21 -0700196 return ret;
197}
198
Suren Baghdasaryan4345f3f2022-04-28 13:24:28 -0700199static bool RemoveUidProcessGroups(const std::string& uid_path, bool empty_only) {
Tom Cherry574a0812018-02-23 13:04:40 -0800200 std::unique_ptr<DIR, decltype(&closedir)> uid(opendir(uid_path.c_str()), closedir);
Wei Wang858f3e52019-02-21 11:25:16 -0800201 bool empty = true;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700202 if (uid != NULL) {
Elliott Hughes9f206932016-09-28 13:29:54 -0700203 dirent* dir;
204 while ((dir = readdir(uid.get())) != nullptr) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700205 if (dir->d_type != DT_DIR) {
206 continue;
207 }
208
Tom Cherry574a0812018-02-23 13:04:40 -0800209 if (!StartsWith(dir->d_name, "pid_")) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700210 continue;
211 }
212
Tom Cherry574a0812018-02-23 13:04:40 -0800213 auto path = StringPrintf("%s/%s", uid_path.c_str(), dir->d_name);
Suren Baghdasaryan4345f3f2022-04-28 13:24:28 -0700214 if (empty_only) {
215 struct stat st;
216 auto procs_file = StringPrintf("%s/%s", path.c_str(),
217 PROCESSGROUP_CGROUP_PROCS_FILE);
218 if (stat(procs_file.c_str(), &st) == -1) {
219 PLOG(ERROR) << "Failed to get stats for " << procs_file;
220 continue;
221 }
222 if (st.st_size > 0) {
223 // skip non-empty groups
224 LOG(VERBOSE) << "Skipping non-empty group " << path;
225 empty = false;
226 continue;
227 }
228 }
Tom Cherry20514c42017-04-21 13:48:49 -0700229 LOG(VERBOSE) << "Removing " << path;
Wei Wang858f3e52019-02-21 11:25:16 -0800230 if (rmdir(path.c_str()) == -1) {
231 if (errno != EBUSY) {
232 PLOG(WARNING) << "Failed to remove " << path;
233 }
234 empty = false;
235 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700236 }
237 }
Wei Wang858f3e52019-02-21 11:25:16 -0800238 return empty;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700239}
240
Suren Baghdasaryan4345f3f2022-04-28 13:24:28 -0700241void removeAllProcessGroupsInternal(bool empty_only) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800242 std::vector<std::string> cgroups;
Bart Van Assche4c957122022-02-04 18:19:45 +0000243 std::string path, memcg_apps_path;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800244
Marco Ballesio4dac8162021-02-10 16:35:44 -0800245 if (CgroupGetControllerPath(CGROUPV2_CONTROLLER_NAME, &path)) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800246 cgroups.push_back(path);
247 }
Bart Van Assche4c957122022-02-04 18:19:45 +0000248 if (CgroupGetMemcgAppsPath(&memcg_apps_path) && memcg_apps_path != path) {
249 cgroups.push_back(memcg_apps_path);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800250 }
251
252 for (std::string cgroup_root_path : cgroups) {
253 std::unique_ptr<DIR, decltype(&closedir)> root(opendir(cgroup_root_path.c_str()), closedir);
Peter Collingbourned7157c22018-10-30 15:49:33 -0700254 if (root == NULL) {
Bart Van Assche6e814b02022-02-03 19:24:42 +0000255 PLOG(ERROR) << __func__ << " failed to open " << cgroup_root_path;
Peter Collingbourned7157c22018-10-30 15:49:33 -0700256 } else {
257 dirent* dir;
258 while ((dir = readdir(root.get())) != nullptr) {
259 if (dir->d_type != DT_DIR) {
260 continue;
261 }
Tom Cherry574a0812018-02-23 13:04:40 -0800262
Peter Collingbourned7157c22018-10-30 15:49:33 -0700263 if (!StartsWith(dir->d_name, "uid_")) {
264 continue;
265 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700266
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800267 auto path = StringPrintf("%s/%s", cgroup_root_path.c_str(), dir->d_name);
Suren Baghdasaryan4345f3f2022-04-28 13:24:28 -0700268 if (!RemoveUidProcessGroups(path, empty_only)) {
Wei Wang858f3e52019-02-21 11:25:16 -0800269 LOG(VERBOSE) << "Skip removing " << path;
270 continue;
271 }
Peter Collingbourned7157c22018-10-30 15:49:33 -0700272 LOG(VERBOSE) << "Removing " << path;
Wei Wang858f3e52019-02-21 11:25:16 -0800273 if (rmdir(path.c_str()) == -1 && errno != EBUSY) {
274 PLOG(WARNING) << "Failed to remove " << path;
275 }
Peter Collingbourned7157c22018-10-30 15:49:33 -0700276 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700277 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700278 }
279}
280
Suren Baghdasaryan4345f3f2022-04-28 13:24:28 -0700281void removeAllProcessGroups() {
282 LOG(VERBOSE) << "removeAllProcessGroups()";
283 removeAllProcessGroupsInternal(false);
284}
285
286void removeAllEmptyProcessGroups() {
287 LOG(VERBOSE) << "removeAllEmptyProcessGroups()";
288 removeAllProcessGroupsInternal(true);
289}
290
Marco Ballesio4dac8162021-02-10 16:35:44 -0800291/**
292 * Process groups are primarily created by the Zygote, meaning that uid/pid groups are created by
293 * the user root. Ownership for the newly created cgroup and all of its files must thus be
294 * transferred for the user/group passed as uid/gid before system_server can properly access them.
295 */
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800296static bool MkdirAndChown(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Suren Baghdasaryan29c9e262021-07-07 10:59:59 -0700297 if (mkdir(path.c_str(), mode) == -1) {
298 if (errno == EEXIST) {
299 // Directory already exists and permissions have been set at the time it was created
300 return true;
301 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800302 return false;
303 }
304
Marco Ballesio4dac8162021-02-10 16:35:44 -0800305 auto dir = std::unique_ptr<DIR, decltype(&closedir)>(opendir(path.c_str()), closedir);
306
307 if (dir == NULL) {
308 PLOG(ERROR) << "opendir failed for " << path;
309 goto err;
310 }
311
312 struct dirent* dir_entry;
313 while ((dir_entry = readdir(dir.get()))) {
314 if (!strcmp("..", dir_entry->d_name)) {
315 continue;
316 }
317
318 std::string file_path = path + "/" + dir_entry->d_name;
319
320 if (lchown(file_path.c_str(), uid, gid) < 0) {
321 PLOG(ERROR) << "lchown failed for " << file_path;
322 goto err;
323 }
324
325 if (fchmodat(AT_FDCWD, file_path.c_str(), mode, AT_SYMLINK_NOFOLLOW) != 0) {
326 PLOG(ERROR) << "fchmodat failed for " << file_path;
327 goto err;
328 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800329 }
330
331 return true;
Marco Ballesio4dac8162021-02-10 16:35:44 -0800332err:
333 int saved_errno = errno;
334 rmdir(path.c_str());
335 errno = saved_errno;
336
337 return false;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800338}
339
Tom Cherry20514c42017-04-21 13:48:49 -0700340// Returns number of processes killed on success
341// Returns 0 if there are no processes in the process cgroup left to kill
Tom Cherry574a0812018-02-23 13:04:40 -0800342// Returns -1 on error
Peter Collingbourned7157c22018-10-30 15:49:33 -0700343static int DoKillProcessGroupOnce(const char* cgroup, uid_t uid, int initialPid, int signal) {
344 auto path = ConvertUidPidToPath(cgroup, uid, initialPid) + PROCESSGROUP_CGROUP_PROCS_FILE;
Tom Cherry574a0812018-02-23 13:04:40 -0800345 std::unique_ptr<FILE, decltype(&fclose)> fd(fopen(path.c_str(), "re"), fclose);
346 if (!fd) {
Wei Wang858f3e52019-02-21 11:25:16 -0800347 if (errno == ENOENT) {
348 // This happens when process is already dead
349 return 0;
350 }
Bart Van Assche6e814b02022-02-03 19:24:42 +0000351 PLOG(WARNING) << __func__ << " failed to open process cgroup uid " << uid << " pid "
352 << initialPid;
Tom Cherry574a0812018-02-23 13:04:40 -0800353 return -1;
Tom Cherry20514c42017-04-21 13:48:49 -0700354 }
355
Tom Cherry70a5ed42017-06-05 19:20:17 -0700356 // We separate all of the pids in the cgroup into those pids that are also the leaders of
357 // process groups (stored in the pgids set) and those that are not (stored in the pids set).
358 std::set<pid_t> pgids;
359 pgids.emplace(initialPid);
360 std::set<pid_t> pids;
361
Colin Crosscf8d1c22014-06-03 13:24:21 -0700362 pid_t pid;
Tom Cherry20514c42017-04-21 13:48:49 -0700363 int processes = 0;
Tom Cherry574a0812018-02-23 13:04:40 -0800364 while (fscanf(fd.get(), "%d\n", &pid) == 1 && pid >= 0) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700365 processes++;
Dianne Hackborn2c5e7e12014-10-13 17:45:22 -0700366 if (pid == 0) {
367 // Should never happen... but if it does, trying to kill this
368 // will boomerang right back and kill us! Let's not let that happen.
Elliott Hughes171df0a2016-08-02 13:30:30 -0700369 LOG(WARNING) << "Yikes, we've been told to kill pid 0! How about we don't do that?";
Dianne Hackborn2c5e7e12014-10-13 17:45:22 -0700370 continue;
371 }
Tom Cherry70a5ed42017-06-05 19:20:17 -0700372 pid_t pgid = getpgid(pid);
373 if (pgid == -1) PLOG(ERROR) << "getpgid(" << pid << ") failed";
374 if (pgid == pid) {
375 pgids.emplace(pid);
376 } else {
377 pids.emplace(pid);
378 }
379 }
380
381 // Erase all pids that will be killed when we kill the process groups.
382 for (auto it = pids.begin(); it != pids.end();) {
fengshaobo950f6f32018-09-13 14:57:07 +0800383 pid_t pgid = getpgid(*it);
Tom Cherry70a5ed42017-06-05 19:20:17 -0700384 if (pgids.count(pgid) == 1) {
385 it = pids.erase(it);
386 } else {
387 ++it;
388 }
389 }
390
391 // Kill all process groups.
392 for (const auto pgid : pgids) {
393 LOG(VERBOSE) << "Killing process group " << -pgid << " in uid " << uid
394 << " as part of process cgroup " << initialPid;
395
Wei Wang858f3e52019-02-21 11:25:16 -0800396 if (kill(-pgid, signal) == -1 && errno != ESRCH) {
Tom Cherry70a5ed42017-06-05 19:20:17 -0700397 PLOG(WARNING) << "kill(" << -pgid << ", " << signal << ") failed";
398 }
399 }
400
401 // Kill remaining pids.
402 for (const auto pid : pids) {
Tom Cherry20514c42017-04-21 13:48:49 -0700403 LOG(VERBOSE) << "Killing pid " << pid << " in uid " << uid << " as part of process cgroup "
404 << initialPid;
Tom Cherry70a5ed42017-06-05 19:20:17 -0700405
Wei Wang858f3e52019-02-21 11:25:16 -0800406 if (kill(pid, signal) == -1 && errno != ESRCH) {
Elliott Hughes171df0a2016-08-02 13:30:30 -0700407 PLOG(WARNING) << "kill(" << pid << ", " << signal << ") failed";
Colin Crosscf8d1c22014-06-03 13:24:21 -0700408 }
409 }
410
Tom Cherry574a0812018-02-23 13:04:40 -0800411 return feof(fd.get()) ? processes : -1;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700412}
413
Tom Cherryd89ed132019-11-19 14:19:40 -0800414static int KillProcessGroup(uid_t uid, int initialPid, int signal, int retries,
415 int* max_processes) {
Marco Ballesio4dac8162021-02-10 16:35:44 -0800416 std::string hierarchy_root_path;
417 CgroupGetControllerPath(CGROUPV2_CONTROLLER_NAME, &hierarchy_root_path);
418 const char* cgroup = hierarchy_root_path.c_str();
Peter Collingbourned7157c22018-10-30 15:49:33 -0700419
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000420 std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
Colin Crosscf8d1c22014-06-03 13:24:21 -0700421
Tom Cherryd89ed132019-11-19 14:19:40 -0800422 if (max_processes != nullptr) {
423 *max_processes = 0;
424 }
425
Tom Cherry20514c42017-04-21 13:48:49 -0700426 int retry = retries;
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000427 int processes;
Peter Collingbourned7157c22018-10-30 15:49:33 -0700428 while ((processes = DoKillProcessGroupOnce(cgroup, uid, initialPid, signal)) > 0) {
Tom Cherryd89ed132019-11-19 14:19:40 -0800429 if (max_processes != nullptr && processes > *max_processes) {
430 *max_processes = processes;
431 }
Tom Cherry20514c42017-04-21 13:48:49 -0700432 LOG(VERBOSE) << "Killed " << processes << " processes for processgroup " << initialPid;
Yusuke Satod5039302015-06-16 13:51:14 -0700433 if (retry > 0) {
Elliott Hughes290a2282016-11-14 17:08:47 -0800434 std::this_thread::sleep_for(5ms);
Yusuke Satod5039302015-06-16 13:51:14 -0700435 --retry;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700436 } else {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700437 break;
438 }
439 }
440
Tom Cherry20514c42017-04-21 13:48:49 -0700441 if (processes < 0) {
442 PLOG(ERROR) << "Error encountered killing process cgroup uid " << uid << " pid "
443 << initialPid;
444 return -1;
445 }
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000446
Tom Cherry20514c42017-04-21 13:48:49 -0700447 std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
Elliott Hughes171df0a2016-08-02 13:30:30 -0700448 auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
Tom Cherry20514c42017-04-21 13:48:49 -0700449
450 // We only calculate the number of 'processes' when killing the processes.
451 // In the retries == 0 case, we only kill the processes once and therefore
452 // will not have waited then recalculated how many processes are remaining
453 // after the first signals have been sent.
454 // Logging anything regarding the number of 'processes' here does not make sense.
Dianne Hackborn2c5e7e12014-10-13 17:45:22 -0700455
Colin Crosscf8d1c22014-06-03 13:24:21 -0700456 if (processes == 0) {
Tom Cherry20514c42017-04-21 13:48:49 -0700457 if (retries > 0) {
458 LOG(INFO) << "Successfully killed process cgroup uid " << uid << " pid " << initialPid
459 << " in " << static_cast<int>(ms) << "ms";
460 }
Marco Ballesio4dac8162021-02-10 16:35:44 -0800461
Suren Baghdasaryanfd933782022-05-26 17:40:25 -0700462 // 400 retries correspond to 2 secs max timeout
463 int err = RemoveProcessGroup(cgroup, uid, initialPid, 400);
Marco Ballesio4dac8162021-02-10 16:35:44 -0800464
465 if (isMemoryCgroupSupported() && UsePerAppMemcg()) {
Bart Van Assche4c957122022-02-04 18:19:45 +0000466 std::string memcg_apps_path;
467 if (CgroupGetMemcgAppsPath(&memcg_apps_path) &&
Suren Baghdasaryanfd933782022-05-26 17:40:25 -0700468 RemoveProcessGroup(memcg_apps_path.c_str(), uid, initialPid, 400) < 0) {
Bart Van Assche4c957122022-02-04 18:19:45 +0000469 return -1;
470 }
Marco Ballesio4dac8162021-02-10 16:35:44 -0800471 }
472
473 return err;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700474 } else {
Tom Cherry20514c42017-04-21 13:48:49 -0700475 if (retries > 0) {
476 LOG(ERROR) << "Failed to kill process cgroup uid " << uid << " pid " << initialPid
477 << " in " << static_cast<int>(ms) << "ms, " << processes
478 << " processes remain";
479 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700480 return -1;
481 }
482}
483
Tom Cherryd89ed132019-11-19 14:19:40 -0800484int killProcessGroup(uid_t uid, int initialPid, int signal, int* max_processes) {
485 return KillProcessGroup(uid, initialPid, signal, 40 /*retries*/, max_processes);
Keun-young Parkfac4b632017-03-28 17:25:24 -0700486}
487
Tom Cherryd89ed132019-11-19 14:19:40 -0800488int killProcessGroupOnce(uid_t uid, int initialPid, int signal, int* max_processes) {
489 return KillProcessGroup(uid, initialPid, signal, 0 /*retries*/, max_processes);
Keun-young Parkfac4b632017-03-28 17:25:24 -0700490}
491
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700492static int createProcessGroupInternal(uid_t uid, int initialPid, std::string cgroup,
493 bool activate_controllers) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800494 auto uid_path = ConvertUidToPath(cgroup.c_str(), uid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700495
Marco Ballesio9e628a62021-02-11 14:44:53 -0800496 struct stat cgroup_stat;
497 mode_t cgroup_mode = 0750;
Bart Van Assche8eb7a6e2022-03-29 23:47:08 +0000498 uid_t cgroup_uid = AID_SYSTEM;
Bart Van Assche32a9b1c2022-03-10 21:42:40 +0000499 gid_t cgroup_gid = AID_SYSTEM;
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700500 int ret = 0;
Marco Ballesio9e628a62021-02-11 14:44:53 -0800501
Bart Van Assche55a9b1e2022-03-23 10:13:18 -0700502 if (stat(cgroup.c_str(), &cgroup_stat) < 0) {
Marco Ballesio9e628a62021-02-11 14:44:53 -0800503 PLOG(ERROR) << "Failed to get stats for " << cgroup;
504 } else {
505 cgroup_mode = cgroup_stat.st_mode;
Bart Van Assche8eb7a6e2022-03-29 23:47:08 +0000506 cgroup_uid = cgroup_stat.st_uid;
Marco Ballesio9e628a62021-02-11 14:44:53 -0800507 cgroup_gid = cgroup_stat.st_gid;
508 }
509
Bart Van Assche8eb7a6e2022-03-29 23:47:08 +0000510 if (!MkdirAndChown(uid_path, cgroup_mode, cgroup_uid, cgroup_gid)) {
Tom Cherry574a0812018-02-23 13:04:40 -0800511 PLOG(ERROR) << "Failed to make and chown " << uid_path;
Elliott Hughes171df0a2016-08-02 13:30:30 -0700512 return -errno;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700513 }
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700514 if (activate_controllers) {
515 ret = CgroupMap::GetInstance().ActivateControllers(uid_path);
516 if (ret) {
517 LOG(ERROR) << "Failed to activate controllers in " << uid_path;
518 return ret;
519 }
520 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700521
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800522 auto uid_pid_path = ConvertUidPidToPath(cgroup.c_str(), uid, initialPid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700523
Bart Van Assche8eb7a6e2022-03-29 23:47:08 +0000524 if (!MkdirAndChown(uid_pid_path, cgroup_mode, cgroup_uid, cgroup_gid)) {
Tom Cherry574a0812018-02-23 13:04:40 -0800525 PLOG(ERROR) << "Failed to make and chown " << uid_pid_path;
Elliott Hughes171df0a2016-08-02 13:30:30 -0700526 return -errno;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700527 }
528
Tom Cherry574a0812018-02-23 13:04:40 -0800529 auto uid_pid_procs_file = uid_pid_path + PROCESSGROUP_CGROUP_PROCS_FILE;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700530
Tom Cherry574a0812018-02-23 13:04:40 -0800531 if (!WriteStringToFile(std::to_string(initialPid), uid_pid_procs_file)) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700532 ret = -errno;
Tom Cherry574a0812018-02-23 13:04:40 -0800533 PLOG(ERROR) << "Failed to write '" << initialPid << "' to " << uid_pid_procs_file;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700534 }
535
Colin Crosscf8d1c22014-06-03 13:24:21 -0700536 return ret;
537}
Robert Benead4852262017-07-16 19:38:11 -0700538
Marco Ballesio4dac8162021-02-10 16:35:44 -0800539int createProcessGroup(uid_t uid, int initialPid, bool memControl) {
540 std::string cgroup;
541
542 if (memControl && !UsePerAppMemcg()) {
543 PLOG(ERROR) << "service memory controls are used without per-process memory cgroup support";
544 return -EINVAL;
545 }
546
Bart Van Assche4c957122022-02-04 18:19:45 +0000547 if (std::string memcg_apps_path;
548 isMemoryCgroupSupported() && UsePerAppMemcg() && CgroupGetMemcgAppsPath(&memcg_apps_path)) {
549 // Note by bvanassche: passing 'false' as fourth argument below implies that the v1
550 // hierarchy is used. It is not clear to me whether the above conditions guarantee that the
551 // v1 hierarchy is used.
552 int ret = createProcessGroupInternal(uid, initialPid, memcg_apps_path, false);
Marco Ballesio4dac8162021-02-10 16:35:44 -0800553 if (ret != 0) {
554 return ret;
555 }
556 }
557
558 CgroupGetControllerPath(CGROUPV2_CONTROLLER_NAME, &cgroup);
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700559 return createProcessGroupInternal(uid, initialPid, cgroup, true);
Marco Ballesio4dac8162021-02-10 16:35:44 -0800560}
561
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800562static bool SetProcessGroupValue(int tid, const std::string& attr_name, int64_t value) {
Peter Collingbourned7157c22018-10-30 15:49:33 -0700563 if (!isMemoryCgroupSupported()) {
Tom Cherry574a0812018-02-23 13:04:40 -0800564 PLOG(ERROR) << "Memcg is not mounted.";
Robert Benead4852262017-07-16 19:38:11 -0700565 return false;
566 }
567
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800568 std::string path;
569 if (!CgroupGetAttributePathForTask(attr_name, tid, &path)) {
570 PLOG(ERROR) << "Failed to find attribute '" << attr_name << "'";
571 return false;
572 }
Robert Benead4852262017-07-16 19:38:11 -0700573
574 if (!WriteStringToFile(std::to_string(value), path)) {
575 PLOG(ERROR) << "Failed to write '" << value << "' to " << path;
576 return false;
577 }
578 return true;
579}
580
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800581bool setProcessGroupSwappiness(uid_t, int pid, int swappiness) {
582 return SetProcessGroupValue(pid, "MemSwappiness", swappiness);
Robert Benead4852262017-07-16 19:38:11 -0700583}
584
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800585bool setProcessGroupSoftLimit(uid_t, int pid, int64_t soft_limit_in_bytes) {
586 return SetProcessGroupValue(pid, "MemSoftLimit", soft_limit_in_bytes);
Robert Benead4852262017-07-16 19:38:11 -0700587}
588
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800589bool setProcessGroupLimit(uid_t, int pid, int64_t limit_in_bytes) {
590 return SetProcessGroupValue(pid, "MemLimit", limit_in_bytes);
Robert Benead4852262017-07-16 19:38:11 -0700591}
Marco Ballesio4e644c42021-02-24 16:30:50 -0800592
593bool getAttributePathForTask(const std::string& attr_name, int tid, std::string* path) {
594 return CgroupGetAttributePathForTask(attr_name, tid, path);
595}