blob: 6d075384f982edc12cfa1a1d2cfddc794f6235f2 [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
Nikita Ioffec2b16542022-10-20 14:14:39 +010058bool CgroupsAvailable() {
59 static bool cgroups_available = access("/proc/cgroups", F_OK) == 0;
60 return cgroups_available;
61}
62
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080063bool CgroupGetControllerPath(const std::string& cgroup_name, std::string* path) {
Yifan Hong53e0deb2019-03-22 17:01:08 -070064 auto controller = CgroupMap::GetInstance().FindController(cgroup_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080065
Yifan Hong53e0deb2019-03-22 17:01:08 -070066 if (!controller.HasValue()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080067 return false;
68 }
69
70 if (path) {
Yifan Hong53e0deb2019-03-22 17:01:08 -070071 *path = controller.path();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080072 }
73
74 return true;
75}
76
Bart Van Assche4c957122022-02-04 18:19:45 +000077static bool CgroupGetMemcgAppsPath(std::string* path) {
78 CgroupController controller = CgroupMap::GetInstance().FindController("memory");
79
80 if (!controller.HasValue()) {
81 return false;
82 }
83
84 if (path) {
85 *path = controller.path();
86 if (controller.version() == 1) {
87 *path += "/apps";
88 }
89 }
90
91 return true;
92}
93
Suren Baghdasaryan9e3ace52021-06-16 17:01:19 -070094bool CgroupGetControllerFromPath(const std::string& path, std::string* cgroup_name) {
95 auto controller = CgroupMap::GetInstance().FindControllerByPath(path);
96
97 if (!controller.HasValue()) {
98 return false;
99 }
100
101 if (cgroup_name) {
102 *cgroup_name = controller.name();
103 }
104
105 return true;
106}
107
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800108bool CgroupGetAttributePath(const std::string& attr_name, std::string* path) {
109 const TaskProfiles& tp = TaskProfiles::GetInstance();
Bart Van Assche4c99e962022-02-03 19:50:16 +0000110 const IProfileAttribute* attr = tp.GetAttribute(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800111
112 if (attr == nullptr) {
113 return false;
114 }
115
116 if (path) {
117 *path = StringPrintf("%s/%s", attr->controller()->path(), attr->file_name().c_str());
118 }
119
120 return true;
121}
122
123bool CgroupGetAttributePathForTask(const std::string& attr_name, int tid, std::string* path) {
124 const TaskProfiles& tp = TaskProfiles::GetInstance();
Bart Van Assche4c99e962022-02-03 19:50:16 +0000125 const IProfileAttribute* attr = tp.GetAttribute(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800126
127 if (attr == nullptr) {
128 return false;
129 }
130
131 if (!attr->GetPathForTask(tid, path)) {
T.J. Mercier4d0d2852023-10-27 23:44:03 +0000132 LOG(ERROR) << "Failed to find cgroup for tid " << tid;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800133 return false;
134 }
135
136 return true;
137}
138
139bool UsePerAppMemcg() {
140 bool low_ram_device = GetBoolProperty("ro.config.low_ram", false);
141 return GetBoolProperty("ro.config.per_app_memcg", low_ram_device);
142}
143
Peter Collingbourned7157c22018-10-30 15:49:33 -0700144static bool isMemoryCgroupSupported() {
Suren Baghdasaryanfa7a05f2019-05-08 17:59:55 -0700145 static bool memcg_supported = CgroupMap::GetInstance().FindController("memory").IsUsable();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800146
Peter Collingbourned7157c22018-10-30 15:49:33 -0700147 return memcg_supported;
Martijn Coenenb82bab62016-01-20 16:39:16 -0800148}
149
Riddle Hsua6abd822019-06-18 15:53:53 -0600150void DropTaskProfilesResourceCaching() {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800151 TaskProfiles::GetInstance().DropResourceCaching(ProfileAction::RCT_TASK);
152 TaskProfiles::GetInstance().DropResourceCaching(ProfileAction::RCT_PROCESS);
Riddle Hsua6abd822019-06-18 15:53:53 -0600153}
154
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800155bool SetProcessProfiles(uid_t uid, pid_t pid, const std::vector<std::string>& profiles) {
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700156 return TaskProfiles::GetInstance().SetProcessProfiles(
157 uid, pid, std::span<const std::string>(profiles), false);
158}
159
160bool SetProcessProfiles(uid_t uid, pid_t pid, std::initializer_list<std::string_view> profiles) {
161 return TaskProfiles::GetInstance().SetProcessProfiles(
162 uid, pid, std::span<const std::string_view>(profiles), false);
163}
164
165bool SetProcessProfiles(uid_t uid, pid_t pid, std::span<const std::string_view> profiles) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800166 return TaskProfiles::GetInstance().SetProcessProfiles(uid, pid, profiles, false);
167}
168
169bool SetProcessProfilesCached(uid_t uid, pid_t pid, const std::vector<std::string>& profiles) {
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700170 return TaskProfiles::GetInstance().SetProcessProfiles(
171 uid, pid, std::span<const std::string>(profiles), true);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800172}
173
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800174bool SetTaskProfiles(int tid, const std::vector<std::string>& profiles, bool use_fd_cache) {
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700175 return TaskProfiles::GetInstance().SetTaskProfiles(tid, std::span<const std::string>(profiles),
176 use_fd_cache);
177}
178
179bool SetTaskProfiles(int tid, std::initializer_list<std::string_view> profiles, bool use_fd_cache) {
180 return TaskProfiles::GetInstance().SetTaskProfiles(
181 tid, std::span<const std::string_view>(profiles), use_fd_cache);
182}
183
184bool SetTaskProfiles(int tid, std::span<const std::string_view> profiles, bool use_fd_cache) {
Rick Yiu0b211fa2019-09-16 19:07:17 +0800185 return TaskProfiles::GetInstance().SetTaskProfiles(tid, profiles, use_fd_cache);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800186}
187
Jiyong Park8bf59402022-04-01 12:24:22 +0900188// C wrapper for SetProcessProfiles.
189// No need to have this in the header file because this function is specifically for crosvm. Crosvm
190// which is written in Rust has its own declaration of this foreign function and doesn't rely on the
191// header. See
192// https://chromium-review.googlesource.com/c/chromiumos/platform/crosvm/+/3574427/5/src/linux/android.rs#12
193extern "C" bool android_set_process_profiles(uid_t uid, pid_t pid, size_t num_profiles,
194 const char* profiles[]) {
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700195 std::vector<std::string_view> profiles_;
Jiyong Parkcc9932b2022-04-20 17:11:42 +0900196 profiles_.reserve(num_profiles);
Jiyong Park8bf59402022-04-01 12:24:22 +0900197 for (size_t i = 0; i < num_profiles; i++) {
198 profiles_.emplace_back(profiles[i]);
199 }
Bart Van Asschef32c4ec2022-08-02 13:18:12 -0700200 return SetProcessProfiles(uid, pid, std::span<const std::string_view>(profiles_));
Jiyong Park8bf59402022-04-01 12:24:22 +0900201}
202
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000203bool SetUserProfiles(uid_t uid, const std::vector<std::string>& profiles) {
204 return TaskProfiles::GetInstance().SetUserProfiles(uid, std::span<const std::string>(profiles),
205 false);
206}
207
Peter Collingbourned7157c22018-10-30 15:49:33 -0700208static std::string ConvertUidToPath(const char* cgroup, uid_t uid) {
T.J. Mercieraa6158b2023-07-26 22:12:44 +0000209 return StringPrintf("%s/uid_%u", cgroup, uid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700210}
211
Peter Collingbourned7157c22018-10-30 15:49:33 -0700212static std::string ConvertUidPidToPath(const char* cgroup, uid_t uid, int pid) {
T.J. Mercieraa6158b2023-07-26 22:12:44 +0000213 return StringPrintf("%s/uid_%u/pid_%d", cgroup, uid, pid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700214}
215
T.J. Merciera99e7d82023-10-27 17:29:01 +0000216static int RemoveCgroup(const char* cgroup, uid_t uid, int pid, unsigned int retries) {
Marco Ballesio4dac8162021-02-10 16:35:44 -0800217 int ret = 0;
Peter Collingbourned7157c22018-10-30 15:49:33 -0700218 auto uid_pid_path = ConvertUidPidToPath(cgroup, uid, pid);
Marco Ballesio4dac8162021-02-10 16:35:44 -0800219
Marco Ballesio4dac8162021-02-10 16:35:44 -0800220 while (retries--) {
221 ret = rmdir(uid_pid_path.c_str());
Kelvin Zhang459edb02023-11-13 13:35:44 -0800222 // If we get an error 2 'No such file or directory' , that means the
223 // cgroup is already removed, treat it as success and return 0 for
224 // idempotency.
225 if (ret < 0 && errno == ENOENT) {
226 ret = 0;
227 }
T.J. Mercierb02f9442023-10-06 23:11:09 +0000228 if (!ret || errno != EBUSY || !retries) break;
Marco Ballesio4dac8162021-02-10 16:35:44 -0800229 std::this_thread::sleep_for(5ms);
230 }
231
T.J. Mercier9c8c7482023-07-12 18:18:42 +0000232 if (!ret && uid >= AID_ISOLATED_START && uid <= AID_ISOLATED_END) {
233 // Isolated UIDs are unlikely to be reused soon after removal,
234 // so free up the kernel resources for the UID level cgroup.
235 const auto uid_path = ConvertUidToPath(cgroup, uid);
236 ret = rmdir(uid_path.c_str());
Kelvin Zhang459edb02023-11-13 13:35:44 -0800237 if (ret < 0 && errno == ENOENT) {
238 ret = 0;
239 }
T.J. Mercier9c8c7482023-07-12 18:18:42 +0000240 }
241
Colin Crosscf8d1c22014-06-03 13:24:21 -0700242 return ret;
243}
244
T.J. Merciera99e7d82023-10-27 17:29:01 +0000245static bool RemoveUidCgroups(const std::string& uid_path, bool empty_only) {
Tom Cherry574a0812018-02-23 13:04:40 -0800246 std::unique_ptr<DIR, decltype(&closedir)> uid(opendir(uid_path.c_str()), closedir);
Wei Wang858f3e52019-02-21 11:25:16 -0800247 bool empty = true;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700248 if (uid != NULL) {
Elliott Hughes9f206932016-09-28 13:29:54 -0700249 dirent* dir;
250 while ((dir = readdir(uid.get())) != nullptr) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700251 if (dir->d_type != DT_DIR) {
252 continue;
253 }
254
Tom Cherry574a0812018-02-23 13:04:40 -0800255 if (!StartsWith(dir->d_name, "pid_")) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700256 continue;
257 }
258
Tom Cherry574a0812018-02-23 13:04:40 -0800259 auto path = StringPrintf("%s/%s", uid_path.c_str(), dir->d_name);
Suren Baghdasaryan4345f3f2022-04-28 13:24:28 -0700260 if (empty_only) {
261 struct stat st;
262 auto procs_file = StringPrintf("%s/%s", path.c_str(),
263 PROCESSGROUP_CGROUP_PROCS_FILE);
264 if (stat(procs_file.c_str(), &st) == -1) {
265 PLOG(ERROR) << "Failed to get stats for " << procs_file;
266 continue;
267 }
268 if (st.st_size > 0) {
269 // skip non-empty groups
270 LOG(VERBOSE) << "Skipping non-empty group " << path;
271 empty = false;
272 continue;
273 }
274 }
Tom Cherry20514c42017-04-21 13:48:49 -0700275 LOG(VERBOSE) << "Removing " << path;
Wei Wang858f3e52019-02-21 11:25:16 -0800276 if (rmdir(path.c_str()) == -1) {
277 if (errno != EBUSY) {
278 PLOG(WARNING) << "Failed to remove " << path;
279 }
280 empty = false;
281 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700282 }
283 }
Wei Wang858f3e52019-02-21 11:25:16 -0800284 return empty;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700285}
286
T.J. Mercier9431b632023-11-06 14:56:29 +0000287static void removeAllProcessGroupsInternal(bool empty_only) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800288 std::vector<std::string> cgroups;
Bart Van Assche4c957122022-02-04 18:19:45 +0000289 std::string path, memcg_apps_path;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800290
T.J. Merciera99e7d82023-10-27 17:29:01 +0000291 if (CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &path)) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800292 cgroups.push_back(path);
293 }
Bart Van Assche4c957122022-02-04 18:19:45 +0000294 if (CgroupGetMemcgAppsPath(&memcg_apps_path) && memcg_apps_path != path) {
295 cgroups.push_back(memcg_apps_path);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800296 }
297
298 for (std::string cgroup_root_path : cgroups) {
299 std::unique_ptr<DIR, decltype(&closedir)> root(opendir(cgroup_root_path.c_str()), closedir);
Peter Collingbourned7157c22018-10-30 15:49:33 -0700300 if (root == NULL) {
Bart Van Assche6e814b02022-02-03 19:24:42 +0000301 PLOG(ERROR) << __func__ << " failed to open " << cgroup_root_path;
Peter Collingbourned7157c22018-10-30 15:49:33 -0700302 } else {
303 dirent* dir;
304 while ((dir = readdir(root.get())) != nullptr) {
305 if (dir->d_type != DT_DIR) {
306 continue;
307 }
Tom Cherry574a0812018-02-23 13:04:40 -0800308
Peter Collingbourned7157c22018-10-30 15:49:33 -0700309 if (!StartsWith(dir->d_name, "uid_")) {
310 continue;
311 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700312
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800313 auto path = StringPrintf("%s/%s", cgroup_root_path.c_str(), dir->d_name);
T.J. Merciera99e7d82023-10-27 17:29:01 +0000314 if (!RemoveUidCgroups(path, empty_only)) {
Wei Wang858f3e52019-02-21 11:25:16 -0800315 LOG(VERBOSE) << "Skip removing " << path;
316 continue;
317 }
Peter Collingbourned7157c22018-10-30 15:49:33 -0700318 LOG(VERBOSE) << "Removing " << path;
Wei Wang858f3e52019-02-21 11:25:16 -0800319 if (rmdir(path.c_str()) == -1 && errno != EBUSY) {
320 PLOG(WARNING) << "Failed to remove " << path;
321 }
Peter Collingbourned7157c22018-10-30 15:49:33 -0700322 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700323 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700324 }
325}
326
Suren Baghdasaryan4345f3f2022-04-28 13:24:28 -0700327void removeAllProcessGroups() {
328 LOG(VERBOSE) << "removeAllProcessGroups()";
329 removeAllProcessGroupsInternal(false);
330}
331
332void removeAllEmptyProcessGroups() {
333 LOG(VERBOSE) << "removeAllEmptyProcessGroups()";
334 removeAllProcessGroupsInternal(true);
335}
336
Marco Ballesio4dac8162021-02-10 16:35:44 -0800337/**
338 * Process groups are primarily created by the Zygote, meaning that uid/pid groups are created by
339 * the user root. Ownership for the newly created cgroup and all of its files must thus be
340 * transferred for the user/group passed as uid/gid before system_server can properly access them.
341 */
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800342static bool MkdirAndChown(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
Suren Baghdasaryan29c9e262021-07-07 10:59:59 -0700343 if (mkdir(path.c_str(), mode) == -1) {
344 if (errno == EEXIST) {
345 // Directory already exists and permissions have been set at the time it was created
346 return true;
347 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800348 return false;
349 }
350
Marco Ballesio4dac8162021-02-10 16:35:44 -0800351 auto dir = std::unique_ptr<DIR, decltype(&closedir)>(opendir(path.c_str()), closedir);
352
353 if (dir == NULL) {
354 PLOG(ERROR) << "opendir failed for " << path;
355 goto err;
356 }
357
358 struct dirent* dir_entry;
359 while ((dir_entry = readdir(dir.get()))) {
360 if (!strcmp("..", dir_entry->d_name)) {
361 continue;
362 }
363
364 std::string file_path = path + "/" + dir_entry->d_name;
365
366 if (lchown(file_path.c_str(), uid, gid) < 0) {
367 PLOG(ERROR) << "lchown failed for " << file_path;
368 goto err;
369 }
370
371 if (fchmodat(AT_FDCWD, file_path.c_str(), mode, AT_SYMLINK_NOFOLLOW) != 0) {
372 PLOG(ERROR) << "fchmodat failed for " << file_path;
373 goto err;
374 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800375 }
376
377 return true;
Marco Ballesio4dac8162021-02-10 16:35:44 -0800378err:
379 int saved_errno = errno;
380 rmdir(path.c_str());
381 errno = saved_errno;
382
383 return false;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800384}
385
Tom Cherry20514c42017-04-21 13:48:49 -0700386// Returns number of processes killed on success
387// Returns 0 if there are no processes in the process cgroup left to kill
Tom Cherry574a0812018-02-23 13:04:40 -0800388// Returns -1 on error
Peter Collingbourned7157c22018-10-30 15:49:33 -0700389static int DoKillProcessGroupOnce(const char* cgroup, uid_t uid, int initialPid, int signal) {
Tom Cherry70a5ed42017-06-05 19:20:17 -0700390 // We separate all of the pids in the cgroup into those pids that are also the leaders of
391 // process groups (stored in the pgids set) and those that are not (stored in the pids set).
392 std::set<pid_t> pgids;
393 pgids.emplace(initialPid);
394 std::set<pid_t> pids;
Suren Baghdasaryan4f7cc8c2023-03-02 14:12:49 -0800395 int processes = 0;
Tom Cherry70a5ed42017-06-05 19:20:17 -0700396
Inseob Kima049a992022-11-17 23:42:12 +0900397 std::unique_ptr<FILE, decltype(&fclose)> fd(nullptr, fclose);
398
399 if (CgroupsAvailable()) {
400 auto path = ConvertUidPidToPath(cgroup, uid, initialPid) + PROCESSGROUP_CGROUP_PROCS_FILE;
401 fd.reset(fopen(path.c_str(), "re"));
402 if (!fd) {
403 if (errno == ENOENT) {
404 // This happens when process is already dead
405 return 0;
406 }
407 PLOG(WARNING) << __func__ << " failed to open process cgroup uid " << uid << " pid "
408 << initialPid;
409 return -1;
410 }
411 pid_t pid;
412 bool file_is_empty = true;
413 while (fscanf(fd.get(), "%d\n", &pid) == 1 && pid >= 0) {
Suren Baghdasaryan4f7cc8c2023-03-02 14:12:49 -0800414 processes++;
Inseob Kima049a992022-11-17 23:42:12 +0900415 file_is_empty = false;
416 if (pid == 0) {
417 // Should never happen... but if it does, trying to kill this
418 // will boomerang right back and kill us! Let's not let that happen.
419 LOG(WARNING)
420 << "Yikes, we've been told to kill pid 0! How about we don't do that?";
421 continue;
422 }
423 pid_t pgid = getpgid(pid);
424 if (pgid == -1) PLOG(ERROR) << "getpgid(" << pid << ") failed";
425 if (pgid == pid) {
426 pgids.emplace(pid);
427 } else {
428 pids.emplace(pid);
429 }
430 }
Jing Ji304c0f12023-02-27 21:58:19 -0800431 if (!file_is_empty) {
432 // Erase all pids that will be killed when we kill the process groups.
433 for (auto it = pids.begin(); it != pids.end();) {
434 pid_t pgid = getpgid(*it);
435 if (pgids.count(pgid) == 1) {
436 it = pids.erase(it);
437 } else {
438 ++it;
439 }
Inseob Kima049a992022-11-17 23:42:12 +0900440 }
441 }
442 }
443
Tom Cherry70a5ed42017-06-05 19:20:17 -0700444 // Kill all process groups.
445 for (const auto pgid : pgids) {
446 LOG(VERBOSE) << "Killing process group " << -pgid << " in uid " << uid
447 << " as part of process cgroup " << initialPid;
448
Suren Baghdasaryan4f7cc8c2023-03-02 14:12:49 -0800449 if (kill(-pgid, signal) == -1 && errno != ESRCH) {
Tom Cherry70a5ed42017-06-05 19:20:17 -0700450 PLOG(WARNING) << "kill(" << -pgid << ", " << signal << ") failed";
451 }
452 }
453
454 // Kill remaining pids.
455 for (const auto pid : pids) {
Tom Cherry20514c42017-04-21 13:48:49 -0700456 LOG(VERBOSE) << "Killing pid " << pid << " in uid " << uid << " as part of process cgroup "
457 << initialPid;
Tom Cherry70a5ed42017-06-05 19:20:17 -0700458
Suren Baghdasaryan4f7cc8c2023-03-02 14:12:49 -0800459 if (kill(pid, signal) == -1 && errno != ESRCH) {
Elliott Hughes171df0a2016-08-02 13:30:30 -0700460 PLOG(WARNING) << "kill(" << pid << ", " << signal << ") failed";
Colin Crosscf8d1c22014-06-03 13:24:21 -0700461 }
462 }
463
Inseob Kima049a992022-11-17 23:42:12 +0900464 return (!fd || feof(fd.get())) ? processes : -1;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700465}
466
T.J. Mercier599d9792023-10-26 20:46:21 +0000467static int KillProcessGroup(uid_t uid, int initialPid, int signal, int retries) {
Bart Van Assche5a3c3f72023-03-22 13:21:03 -0700468 CHECK_GE(uid, 0);
469 CHECK_GT(initialPid, 0);
470
Marco Ballesio4dac8162021-02-10 16:35:44 -0800471 std::string hierarchy_root_path;
Inseob Kima049a992022-11-17 23:42:12 +0900472 if (CgroupsAvailable()) {
T.J. Merciera99e7d82023-10-27 17:29:01 +0000473 CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &hierarchy_root_path);
Inseob Kima049a992022-11-17 23:42:12 +0900474 }
Marco Ballesio4dac8162021-02-10 16:35:44 -0800475 const char* cgroup = hierarchy_root_path.c_str();
Peter Collingbourned7157c22018-10-30 15:49:33 -0700476
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000477 std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
Colin Crosscf8d1c22014-06-03 13:24:21 -0700478
Tom Cherry20514c42017-04-21 13:48:49 -0700479 int retry = retries;
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000480 int processes;
Peter Collingbourned7157c22018-10-30 15:49:33 -0700481 while ((processes = DoKillProcessGroupOnce(cgroup, uid, initialPid, signal)) > 0) {
Tom Cherry20514c42017-04-21 13:48:49 -0700482 LOG(VERBOSE) << "Killed " << processes << " processes for processgroup " << initialPid;
Inseob Kim110cd772022-12-14 11:12:48 +0900483 if (!CgroupsAvailable()) {
484 // makes no sense to retry, because there are no cgroup_procs file
485 processes = 0; // no remaining processes
486 break;
487 }
Yusuke Satod5039302015-06-16 13:51:14 -0700488 if (retry > 0) {
Elliott Hughes290a2282016-11-14 17:08:47 -0800489 std::this_thread::sleep_for(5ms);
Yusuke Satod5039302015-06-16 13:51:14 -0700490 --retry;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700491 } else {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700492 break;
493 }
494 }
495
Tom Cherry20514c42017-04-21 13:48:49 -0700496 if (processes < 0) {
497 PLOG(ERROR) << "Error encountered killing process cgroup uid " << uid << " pid "
498 << initialPid;
499 return -1;
500 }
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000501
Tom Cherry20514c42017-04-21 13:48:49 -0700502 std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
Elliott Hughes171df0a2016-08-02 13:30:30 -0700503 auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
Tom Cherry20514c42017-04-21 13:48:49 -0700504
505 // We only calculate the number of 'processes' when killing the processes.
506 // In the retries == 0 case, we only kill the processes once and therefore
507 // will not have waited then recalculated how many processes are remaining
508 // after the first signals have been sent.
509 // Logging anything regarding the number of 'processes' here does not make sense.
Dianne Hackborn2c5e7e12014-10-13 17:45:22 -0700510
Colin Crosscf8d1c22014-06-03 13:24:21 -0700511 if (processes == 0) {
Tom Cherry20514c42017-04-21 13:48:49 -0700512 if (retries > 0) {
513 LOG(INFO) << "Successfully killed process cgroup uid " << uid << " pid " << initialPid
514 << " in " << static_cast<int>(ms) << "ms";
515 }
Marco Ballesio4dac8162021-02-10 16:35:44 -0800516
Inseob Kima049a992022-11-17 23:42:12 +0900517 if (!CgroupsAvailable()) {
518 // nothing to do here, if cgroups isn't available
519 return 0;
520 }
521
Suren Baghdasaryanfd933782022-05-26 17:40:25 -0700522 // 400 retries correspond to 2 secs max timeout
T.J. Merciera99e7d82023-10-27 17:29:01 +0000523 int err = RemoveCgroup(cgroup, uid, initialPid, 400);
Marco Ballesio4dac8162021-02-10 16:35:44 -0800524
525 if (isMemoryCgroupSupported() && UsePerAppMemcg()) {
Bart Van Assche4c957122022-02-04 18:19:45 +0000526 std::string memcg_apps_path;
527 if (CgroupGetMemcgAppsPath(&memcg_apps_path) &&
T.J. Merciera99e7d82023-10-27 17:29:01 +0000528 RemoveCgroup(memcg_apps_path.c_str(), uid, initialPid, 400) < 0) {
Bart Van Assche4c957122022-02-04 18:19:45 +0000529 return -1;
530 }
Marco Ballesio4dac8162021-02-10 16:35:44 -0800531 }
532
533 return err;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700534 } else {
Tom Cherry20514c42017-04-21 13:48:49 -0700535 if (retries > 0) {
536 LOG(ERROR) << "Failed to kill process cgroup uid " << uid << " pid " << initialPid
537 << " in " << static_cast<int>(ms) << "ms, " << processes
538 << " processes remain";
539 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700540 return -1;
541 }
542}
543
T.J. Mercier599d9792023-10-26 20:46:21 +0000544int killProcessGroup(uid_t uid, int initialPid, int signal) {
545 return KillProcessGroup(uid, initialPid, signal, 40 /*retries*/);
Keun-young Parkfac4b632017-03-28 17:25:24 -0700546}
547
T.J. Mercier599d9792023-10-26 20:46:21 +0000548int killProcessGroupOnce(uid_t uid, int initialPid, int signal) {
549 return KillProcessGroup(uid, initialPid, signal, 0 /*retries*/);
Keun-young Parkfac4b632017-03-28 17:25:24 -0700550}
551
T.J. Mercier22006bf2023-04-13 21:48:55 +0000552int sendSignalToProcessGroup(uid_t uid, int initialPid, int signal) {
553 std::string hierarchy_root_path;
554 if (CgroupsAvailable()) {
T.J. Merciera99e7d82023-10-27 17:29:01 +0000555 CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &hierarchy_root_path);
T.J. Mercier22006bf2023-04-13 21:48:55 +0000556 }
557 const char* cgroup = hierarchy_root_path.c_str();
558 return DoKillProcessGroupOnce(cgroup, uid, initialPid, signal);
559}
560
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700561static int createProcessGroupInternal(uid_t uid, int initialPid, std::string cgroup,
562 bool activate_controllers) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800563 auto uid_path = ConvertUidToPath(cgroup.c_str(), uid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700564
Marco Ballesio9e628a62021-02-11 14:44:53 -0800565 struct stat cgroup_stat;
566 mode_t cgroup_mode = 0750;
Bart Van Assche8eb7a6e2022-03-29 23:47:08 +0000567 uid_t cgroup_uid = AID_SYSTEM;
Bart Van Assche32a9b1c2022-03-10 21:42:40 +0000568 gid_t cgroup_gid = AID_SYSTEM;
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700569 int ret = 0;
Marco Ballesio9e628a62021-02-11 14:44:53 -0800570
Bart Van Assche55a9b1e2022-03-23 10:13:18 -0700571 if (stat(cgroup.c_str(), &cgroup_stat) < 0) {
Marco Ballesio9e628a62021-02-11 14:44:53 -0800572 PLOG(ERROR) << "Failed to get stats for " << cgroup;
573 } else {
574 cgroup_mode = cgroup_stat.st_mode;
Bart Van Assche8eb7a6e2022-03-29 23:47:08 +0000575 cgroup_uid = cgroup_stat.st_uid;
Marco Ballesio9e628a62021-02-11 14:44:53 -0800576 cgroup_gid = cgroup_stat.st_gid;
577 }
578
Bart Van Assche8eb7a6e2022-03-29 23:47:08 +0000579 if (!MkdirAndChown(uid_path, cgroup_mode, cgroup_uid, cgroup_gid)) {
Tom Cherry574a0812018-02-23 13:04:40 -0800580 PLOG(ERROR) << "Failed to make and chown " << uid_path;
Elliott Hughes171df0a2016-08-02 13:30:30 -0700581 return -errno;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700582 }
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700583 if (activate_controllers) {
584 ret = CgroupMap::GetInstance().ActivateControllers(uid_path);
585 if (ret) {
586 LOG(ERROR) << "Failed to activate controllers in " << uid_path;
587 return ret;
588 }
589 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700590
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800591 auto uid_pid_path = ConvertUidPidToPath(cgroup.c_str(), uid, initialPid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700592
Bart Van Assche8eb7a6e2022-03-29 23:47:08 +0000593 if (!MkdirAndChown(uid_pid_path, cgroup_mode, cgroup_uid, cgroup_gid)) {
Tom Cherry574a0812018-02-23 13:04:40 -0800594 PLOG(ERROR) << "Failed to make and chown " << uid_pid_path;
Elliott Hughes171df0a2016-08-02 13:30:30 -0700595 return -errno;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700596 }
597
Tom Cherry574a0812018-02-23 13:04:40 -0800598 auto uid_pid_procs_file = uid_pid_path + PROCESSGROUP_CGROUP_PROCS_FILE;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700599
Tom Cherry574a0812018-02-23 13:04:40 -0800600 if (!WriteStringToFile(std::to_string(initialPid), uid_pid_procs_file)) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700601 ret = -errno;
Tom Cherry574a0812018-02-23 13:04:40 -0800602 PLOG(ERROR) << "Failed to write '" << initialPid << "' to " << uid_pid_procs_file;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700603 }
604
Colin Crosscf8d1c22014-06-03 13:24:21 -0700605 return ret;
606}
Robert Benead4852262017-07-16 19:38:11 -0700607
Marco Ballesio4dac8162021-02-10 16:35:44 -0800608int createProcessGroup(uid_t uid, int initialPid, bool memControl) {
Bart Van Assche5a3c3f72023-03-22 13:21:03 -0700609 CHECK_GE(uid, 0);
610 CHECK_GT(initialPid, 0);
Marco Ballesio4dac8162021-02-10 16:35:44 -0800611
612 if (memControl && !UsePerAppMemcg()) {
T.J. Mercier4d0d2852023-10-27 23:44:03 +0000613 LOG(ERROR) << "service memory controls are used without per-process memory cgroup support";
Marco Ballesio4dac8162021-02-10 16:35:44 -0800614 return -EINVAL;
615 }
616
Bart Van Assche4c957122022-02-04 18:19:45 +0000617 if (std::string memcg_apps_path;
618 isMemoryCgroupSupported() && UsePerAppMemcg() && CgroupGetMemcgAppsPath(&memcg_apps_path)) {
619 // Note by bvanassche: passing 'false' as fourth argument below implies that the v1
620 // hierarchy is used. It is not clear to me whether the above conditions guarantee that the
621 // v1 hierarchy is used.
622 int ret = createProcessGroupInternal(uid, initialPid, memcg_apps_path, false);
Marco Ballesio4dac8162021-02-10 16:35:44 -0800623 if (ret != 0) {
624 return ret;
625 }
626 }
627
Bart Van Assche5a3c3f72023-03-22 13:21:03 -0700628 std::string cgroup;
T.J. Merciera99e7d82023-10-27 17:29:01 +0000629 CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &cgroup);
Suren Baghdasaryan25ad3f92021-07-30 13:42:39 -0700630 return createProcessGroupInternal(uid, initialPid, cgroup, true);
Marco Ballesio4dac8162021-02-10 16:35:44 -0800631}
632
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800633static bool SetProcessGroupValue(int tid, const std::string& attr_name, int64_t value) {
Peter Collingbourned7157c22018-10-30 15:49:33 -0700634 if (!isMemoryCgroupSupported()) {
T.J. Mercier4d0d2852023-10-27 23:44:03 +0000635 LOG(ERROR) << "Memcg is not mounted.";
Robert Benead4852262017-07-16 19:38:11 -0700636 return false;
637 }
638
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800639 std::string path;
640 if (!CgroupGetAttributePathForTask(attr_name, tid, &path)) {
T.J. Mercier4d0d2852023-10-27 23:44:03 +0000641 LOG(ERROR) << "Failed to find attribute '" << attr_name << "'";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800642 return false;
643 }
Robert Benead4852262017-07-16 19:38:11 -0700644
645 if (!WriteStringToFile(std::to_string(value), path)) {
646 PLOG(ERROR) << "Failed to write '" << value << "' to " << path;
647 return false;
648 }
649 return true;
650}
651
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800652bool setProcessGroupSwappiness(uid_t, int pid, int swappiness) {
653 return SetProcessGroupValue(pid, "MemSwappiness", swappiness);
Robert Benead4852262017-07-16 19:38:11 -0700654}
655
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800656bool setProcessGroupSoftLimit(uid_t, int pid, int64_t soft_limit_in_bytes) {
657 return SetProcessGroupValue(pid, "MemSoftLimit", soft_limit_in_bytes);
Robert Benead4852262017-07-16 19:38:11 -0700658}
659
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800660bool setProcessGroupLimit(uid_t, int pid, int64_t limit_in_bytes) {
661 return SetProcessGroupValue(pid, "MemLimit", limit_in_bytes);
Robert Benead4852262017-07-16 19:38:11 -0700662}
Marco Ballesio4e644c42021-02-24 16:30:50 -0800663
664bool getAttributePathForTask(const std::string& attr_name, int tid, std::string* path) {
665 return CgroupGetAttributePathForTask(attr_name, tid, path);
666}
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000667
668bool isProfileValidForProcess(const std::string& profile_name, int uid, int pid) {
669 const TaskProfile* tp = TaskProfiles::GetInstance().GetProfile(profile_name);
670
671 if (tp == nullptr) {
672 return false;
673 }
674
675 return tp->IsValidForProcess(uid, pid);
T.J. Merciera99e7d82023-10-27 17:29:01 +0000676}