blob: 27b4065daa4c163f6c652e3d667c629b27ef9d18 [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>
Colin Crosscf8d1c22014-06-03 13:24:21 -070025#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
28#include <sys/stat.h>
29#include <sys/types.h>
Collin Mullinerf7e79b92016-06-01 21:03:55 +000030
31#include <chrono>
James Hawkins588a2ca2016-02-18 14:52:46 -080032#include <memory>
Elliott Hughes8d532e42016-06-06 21:19:55 -070033#include <mutex>
Elliott Hughes290a2282016-11-14 17:08:47 -080034#include <thread>
Colin Crosscf8d1c22014-06-03 13:24:21 -070035
Elliott Hughes171df0a2016-08-02 13:30:30 -070036#include <android-base/logging.h>
Tom Cherry20514c42017-04-21 13:48:49 -070037#include <android-base/unique_fd.h>
Colin Crosscf8d1c22014-06-03 13:24:21 -070038#include <private/android_filesystem_config.h>
39
40#include <processgroup/processgroup.h>
Martijn Coenenb82bab62016-01-20 16:39:16 -080041
Elliott Hughes290a2282016-11-14 17:08:47 -080042using namespace std::chrono_literals;
43
Martijn Coenen5bb91ab2016-03-18 15:28:31 +010044// Uncomment line below use memory cgroups for keeping track of (forked) PIDs
45// #define USE_MEMCG 1
46
Martijn Coenenb82bab62016-01-20 16:39:16 -080047#define MEM_CGROUP_PATH "/dev/memcg/apps"
Martijn Coenen623b56a2016-02-08 11:42:25 +010048#define MEM_CGROUP_TASKS "/dev/memcg/apps/tasks"
Martijn Coenenb82bab62016-01-20 16:39:16 -080049#define ACCT_CGROUP_PATH "/acct"
50
51#define PROCESSGROUP_UID_PREFIX "uid_"
52#define PROCESSGROUP_PID_PREFIX "pid_"
53#define PROCESSGROUP_CGROUP_PROCS_FILE "/cgroup.procs"
54#define PROCESSGROUP_MAX_UID_LEN 11
55#define PROCESSGROUP_MAX_PID_LEN 11
56#define PROCESSGROUP_MAX_PATH_LEN \
57 ((sizeof(MEM_CGROUP_PATH) > sizeof(ACCT_CGROUP_PATH) ? \
58 sizeof(MEM_CGROUP_PATH) : sizeof(ACCT_CGROUP_PATH)) + \
59 sizeof(PROCESSGROUP_UID_PREFIX) + 1 + \
60 PROCESSGROUP_MAX_UID_LEN + \
61 sizeof(PROCESSGROUP_PID_PREFIX) + 1 + \
62 PROCESSGROUP_MAX_PID_LEN + \
63 sizeof(PROCESSGROUP_CGROUP_PROCS_FILE) + \
64 1)
65
66std::once_flag init_path_flag;
Colin Crosscf8d1c22014-06-03 13:24:21 -070067
Tom Cherry20514c42017-04-21 13:48:49 -070068class ProcessGroup {
69 public:
70 ProcessGroup() : buf_ptr_(buf_), buf_len_(0) {}
71
72 bool Open(uid_t uid, int pid);
73
74 // Return positive number and sets *pid = next pid in process cgroup on success
75 // Returns 0 if there are no pids left in the process cgroup
76 // Returns -errno if an error was encountered
77 int GetOneAppProcess(pid_t* pid);
78
79 private:
80 // Returns positive number of bytes filled on success
81 // Returns 0 if there was nothing to read
82 // Returns -errno if an error was encountered
83 int RefillBuffer();
84
85 android::base::unique_fd fd_;
86 char buf_[128];
87 char* buf_ptr_;
88 size_t buf_len_;
Colin Crosscf8d1c22014-06-03 13:24:21 -070089};
90
Martijn Coenenb82bab62016-01-20 16:39:16 -080091static const char* getCgroupRootPath() {
Martijn Coenen5bb91ab2016-03-18 15:28:31 +010092#ifdef USE_MEMCG
Martijn Coenenb82bab62016-01-20 16:39:16 -080093 static const char* cgroup_root_path = NULL;
94 std::call_once(init_path_flag, [&]() {
Martijn Coenen623b56a2016-02-08 11:42:25 +010095 // Check if mem cgroup is mounted, only then check for write-access to avoid
96 // SELinux denials
97 cgroup_root_path = access(MEM_CGROUP_TASKS, F_OK) || access(MEM_CGROUP_PATH, W_OK) ?
98 ACCT_CGROUP_PATH : MEM_CGROUP_PATH;
Martijn Coenenb82bab62016-01-20 16:39:16 -080099 });
100 return cgroup_root_path;
Martijn Coenen5bb91ab2016-03-18 15:28:31 +0100101#else
102 return ACCT_CGROUP_PATH;
103#endif
Martijn Coenenb82bab62016-01-20 16:39:16 -0800104}
105
Colin Crosscf8d1c22014-06-03 13:24:21 -0700106static int convertUidToPath(char *path, size_t size, uid_t uid)
107{
108 return snprintf(path, size, "%s/%s%d",
Martijn Coenenb82bab62016-01-20 16:39:16 -0800109 getCgroupRootPath(),
Colin Crosscf8d1c22014-06-03 13:24:21 -0700110 PROCESSGROUP_UID_PREFIX,
111 uid);
112}
113
114static int convertUidPidToPath(char *path, size_t size, uid_t uid, int pid)
115{
116 return snprintf(path, size, "%s/%s%d/%s%d",
Martijn Coenenb82bab62016-01-20 16:39:16 -0800117 getCgroupRootPath(),
Colin Crosscf8d1c22014-06-03 13:24:21 -0700118 PROCESSGROUP_UID_PREFIX,
119 uid,
120 PROCESSGROUP_PID_PREFIX,
121 pid);
122}
123
Tom Cherry20514c42017-04-21 13:48:49 -0700124bool ProcessGroup::Open(uid_t uid, int pid) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700125 char path[PROCESSGROUP_MAX_PATH_LEN] = {0};
126 convertUidPidToPath(path, sizeof(path), uid, pid);
127 strlcat(path, PROCESSGROUP_CGROUP_PROCS_FILE, sizeof(path));
128
129 int fd = open(path, O_RDONLY);
Tom Cherry20514c42017-04-21 13:48:49 -0700130 if (fd < 0) return false;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700131
Tom Cherry20514c42017-04-21 13:48:49 -0700132 fd_.reset(fd);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700133
Elliott Hughes171df0a2016-08-02 13:30:30 -0700134 LOG(VERBOSE) << "Initialized context for " << path;
Dianne Hackborn2c5e7e12014-10-13 17:45:22 -0700135
Tom Cherry20514c42017-04-21 13:48:49 -0700136 return true;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700137}
138
Tom Cherry20514c42017-04-21 13:48:49 -0700139int ProcessGroup::RefillBuffer() {
140 memmove(buf_, buf_ptr_, buf_len_);
141 buf_ptr_ = buf_;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700142
Tom Cherry20514c42017-04-21 13:48:49 -0700143 ssize_t ret = read(fd_, buf_ptr_ + buf_len_, sizeof(buf_) - buf_len_ - 1);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700144 if (ret < 0) {
145 return -errno;
146 } else if (ret == 0) {
147 return 0;
148 }
149
Tom Cherry20514c42017-04-21 13:48:49 -0700150 buf_len_ += ret;
151 buf_[buf_len_] = 0;
152 LOG(VERBOSE) << "Read " << ret << " to buffer: " << buf_;
Dianne Hackborn2c5e7e12014-10-13 17:45:22 -0700153
Tom Cherry20514c42017-04-21 13:48:49 -0700154 assert(buf_len_ <= sizeof(buf_));
Colin Crosscf8d1c22014-06-03 13:24:21 -0700155
156 return ret;
157}
158
Tom Cherry20514c42017-04-21 13:48:49 -0700159int ProcessGroup::GetOneAppProcess(pid_t* out_pid) {
160 *out_pid = 0;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700161
Tom Cherry20514c42017-04-21 13:48:49 -0700162 char* eptr;
163 while ((eptr = static_cast<char*>(memchr(buf_ptr_, '\n', buf_len_))) == nullptr) {
164 int ret = RefillBuffer();
165 if (ret <= 0) return ret;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700166 }
167
168 *eptr = '\0';
Tom Cherry20514c42017-04-21 13:48:49 -0700169 char* pid_eptr = nullptr;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700170 errno = 0;
Tom Cherry20514c42017-04-21 13:48:49 -0700171 long pid = strtol(buf_ptr_, &pid_eptr, 10);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700172 if (errno != 0) {
173 return -errno;
174 }
175 if (pid_eptr != eptr) {
Tom Cherry20514c42017-04-21 13:48:49 -0700176 errno = EINVAL;
177 return -errno;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700178 }
179
Tom Cherry20514c42017-04-21 13:48:49 -0700180 buf_len_ -= (eptr - buf_ptr_) + 1;
181 buf_ptr_ = eptr + 1;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700182
Tom Cherry20514c42017-04-21 13:48:49 -0700183 *out_pid = static_cast<pid_t>(pid);
184 return 1;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700185}
186
187static int removeProcessGroup(uid_t uid, int pid)
188{
189 int ret;
190 char path[PROCESSGROUP_MAX_PATH_LEN] = {0};
191
192 convertUidPidToPath(path, sizeof(path), uid, pid);
193 ret = rmdir(path);
194
195 convertUidToPath(path, sizeof(path), uid);
196 rmdir(path);
197
198 return ret;
199}
200
201static void removeUidProcessGroups(const char *uid_path)
202{
James Hawkins588a2ca2016-02-18 14:52:46 -0800203 std::unique_ptr<DIR, decltype(&closedir)> uid(opendir(uid_path), closedir);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700204 if (uid != NULL) {
Elliott Hughes9f206932016-09-28 13:29:54 -0700205 dirent* dir;
206 while ((dir = readdir(uid.get())) != nullptr) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700207 char path[PROCESSGROUP_MAX_PATH_LEN];
208
209 if (dir->d_type != DT_DIR) {
210 continue;
211 }
212
213 if (strncmp(dir->d_name, PROCESSGROUP_PID_PREFIX, strlen(PROCESSGROUP_PID_PREFIX))) {
214 continue;
215 }
216
217 snprintf(path, sizeof(path), "%s/%s", uid_path, dir->d_name);
Tom Cherry20514c42017-04-21 13:48:49 -0700218 LOG(VERBOSE) << "Removing " << path;
219 if (rmdir(path) == -1) PLOG(WARNING) << "Failed to remove " << path;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700220 }
221 }
222}
223
224void removeAllProcessGroups()
225{
Elliott Hughes171df0a2016-08-02 13:30:30 -0700226 LOG(VERBOSE) << "removeAllProcessGroups()";
Elliott Hughesb6e1d152016-08-03 13:29:04 -0700227 const char* cgroup_root_path = getCgroupRootPath();
James Hawkins22b6f7a2016-02-19 11:10:30 -0800228 std::unique_ptr<DIR, decltype(&closedir)> root(opendir(cgroup_root_path), closedir);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700229 if (root == NULL) {
Tom Cherry20514c42017-04-21 13:48:49 -0700230 PLOG(ERROR) << "Failed to open " << cgroup_root_path;
Colin Crossc15dd042014-08-20 14:11:13 -0700231 } else {
Elliott Hughes9f206932016-09-28 13:29:54 -0700232 dirent* dir;
233 while ((dir = readdir(root.get())) != nullptr) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700234 char path[PROCESSGROUP_MAX_PATH_LEN];
235
236 if (dir->d_type != DT_DIR) {
237 continue;
238 }
239 if (strncmp(dir->d_name, PROCESSGROUP_UID_PREFIX, strlen(PROCESSGROUP_UID_PREFIX))) {
240 continue;
241 }
242
Martijn Coenenb82bab62016-01-20 16:39:16 -0800243 snprintf(path, sizeof(path), "%s/%s", cgroup_root_path, dir->d_name);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700244 removeUidProcessGroups(path);
Tom Cherry20514c42017-04-21 13:48:49 -0700245 LOG(VERBOSE) << "Removing " << path;
246 if (rmdir(path) == -1) PLOG(WARNING) << "Failed to remove " << path;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700247 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700248 }
249}
250
Tom Cherry20514c42017-04-21 13:48:49 -0700251// Returns number of processes killed on success
252// Returns 0 if there are no processes in the process cgroup left to kill
253// Returns -errno on error
Keun-young Parkfac4b632017-03-28 17:25:24 -0700254static int doKillProcessGroupOnce(uid_t uid, int initialPid, int signal) {
Tom Cherry20514c42017-04-21 13:48:49 -0700255 ProcessGroup process_group;
256 if (!process_group.Open(uid, initialPid)) {
257 PLOG(WARNING) << "Failed to open process cgroup uid " << uid << " pid " << initialPid;
258 return -errno;
259 }
260
261 int ret;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700262 pid_t pid;
Tom Cherry20514c42017-04-21 13:48:49 -0700263 int processes = 0;
264 while ((ret = process_group.GetOneAppProcess(&pid)) > 0 && pid >= 0) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700265 processes++;
Dianne Hackborn2c5e7e12014-10-13 17:45:22 -0700266 if (pid == 0) {
267 // Should never happen... but if it does, trying to kill this
268 // will boomerang right back and kill us! Let's not let that happen.
Elliott Hughes171df0a2016-08-02 13:30:30 -0700269 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 -0700270 continue;
271 }
Tom Cherry20514c42017-04-21 13:48:49 -0700272 LOG(VERBOSE) << "Killing pid " << pid << " in uid " << uid << " as part of process cgroup "
273 << initialPid;
Elliott Hughes171df0a2016-08-02 13:30:30 -0700274 if (kill(pid, signal) == -1) {
275 PLOG(WARNING) << "kill(" << pid << ", " << signal << ") failed";
Colin Crosscf8d1c22014-06-03 13:24:21 -0700276 }
277 }
278
Tom Cherry20514c42017-04-21 13:48:49 -0700279 return ret >= 0 ? processes : ret;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700280}
281
Tom Cherry20514c42017-04-21 13:48:49 -0700282static int killProcessGroup(uid_t uid, int initialPid, int signal, int retries) {
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000283 std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
Colin Crosscf8d1c22014-06-03 13:24:21 -0700284
Tom Cherry20514c42017-04-21 13:48:49 -0700285 int retry = retries;
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000286 int processes;
Keun-young Parkfac4b632017-03-28 17:25:24 -0700287 while ((processes = doKillProcessGroupOnce(uid, initialPid, signal)) > 0) {
Tom Cherry20514c42017-04-21 13:48:49 -0700288 LOG(VERBOSE) << "Killed " << processes << " processes for processgroup " << initialPid;
Yusuke Satod5039302015-06-16 13:51:14 -0700289 if (retry > 0) {
Elliott Hughes290a2282016-11-14 17:08:47 -0800290 std::this_thread::sleep_for(5ms);
Yusuke Satod5039302015-06-16 13:51:14 -0700291 --retry;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700292 } else {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700293 break;
294 }
295 }
296
Tom Cherry20514c42017-04-21 13:48:49 -0700297 if (processes < 0) {
298 PLOG(ERROR) << "Error encountered killing process cgroup uid " << uid << " pid "
299 << initialPid;
300 return -1;
301 }
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000302
Tom Cherry20514c42017-04-21 13:48:49 -0700303 std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
Elliott Hughes171df0a2016-08-02 13:30:30 -0700304 auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
Tom Cherry20514c42017-04-21 13:48:49 -0700305
306 // We only calculate the number of 'processes' when killing the processes.
307 // In the retries == 0 case, we only kill the processes once and therefore
308 // will not have waited then recalculated how many processes are remaining
309 // after the first signals have been sent.
310 // Logging anything regarding the number of 'processes' here does not make sense.
Dianne Hackborn2c5e7e12014-10-13 17:45:22 -0700311
Colin Crosscf8d1c22014-06-03 13:24:21 -0700312 if (processes == 0) {
Tom Cherry20514c42017-04-21 13:48:49 -0700313 if (retries > 0) {
314 LOG(INFO) << "Successfully killed process cgroup uid " << uid << " pid " << initialPid
315 << " in " << static_cast<int>(ms) << "ms";
316 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700317 return removeProcessGroup(uid, initialPid);
318 } else {
Tom Cherry20514c42017-04-21 13:48:49 -0700319 if (retries > 0) {
320 LOG(ERROR) << "Failed to kill process cgroup uid " << uid << " pid " << initialPid
321 << " in " << static_cast<int>(ms) << "ms, " << processes
322 << " processes remain";
323 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700324 return -1;
325 }
326}
327
Keun-young Parkfac4b632017-03-28 17:25:24 -0700328int killProcessGroup(uid_t uid, int initialPid, int signal) {
Tom Cherry20514c42017-04-21 13:48:49 -0700329 return killProcessGroup(uid, initialPid, signal, 40 /*retries*/);
Keun-young Parkfac4b632017-03-28 17:25:24 -0700330}
331
332int killProcessGroupOnce(uid_t uid, int initialPid, int signal) {
Tom Cherry20514c42017-04-21 13:48:49 -0700333 return killProcessGroup(uid, initialPid, signal, 0 /*retries*/);
Keun-young Parkfac4b632017-03-28 17:25:24 -0700334}
335
Elliott Hughes171df0a2016-08-02 13:30:30 -0700336static bool mkdirAndChown(const char *path, mode_t mode, uid_t uid, gid_t gid)
Colin Crosscf8d1c22014-06-03 13:24:21 -0700337{
Elliott Hughes171df0a2016-08-02 13:30:30 -0700338 if (mkdir(path, mode) == -1 && errno != EEXIST) {
339 return false;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700340 }
341
Elliott Hughes171df0a2016-08-02 13:30:30 -0700342 if (chown(path, uid, gid) == -1) {
343 int saved_errno = errno;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700344 rmdir(path);
Elliott Hughes171df0a2016-08-02 13:30:30 -0700345 errno = saved_errno;
346 return false;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700347 }
348
Elliott Hughes171df0a2016-08-02 13:30:30 -0700349 return true;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700350}
351
352int createProcessGroup(uid_t uid, int initialPid)
353{
354 char path[PROCESSGROUP_MAX_PATH_LEN] = {0};
Colin Crosscf8d1c22014-06-03 13:24:21 -0700355
356 convertUidToPath(path, sizeof(path), uid);
357
Elliott Hughes171df0a2016-08-02 13:30:30 -0700358 if (!mkdirAndChown(path, 0750, AID_SYSTEM, AID_SYSTEM)) {
Tom Cherry20514c42017-04-21 13:48:49 -0700359 PLOG(ERROR) << "Failed to make and chown " << path;
Elliott Hughes171df0a2016-08-02 13:30:30 -0700360 return -errno;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700361 }
362
363 convertUidPidToPath(path, sizeof(path), uid, initialPid);
364
Elliott Hughes171df0a2016-08-02 13:30:30 -0700365 if (!mkdirAndChown(path, 0750, AID_SYSTEM, AID_SYSTEM)) {
Tom Cherry20514c42017-04-21 13:48:49 -0700366 PLOG(ERROR) << "Failed to make and chown " << path;
Elliott Hughes171df0a2016-08-02 13:30:30 -0700367 return -errno;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700368 }
369
370 strlcat(path, PROCESSGROUP_CGROUP_PROCS_FILE, sizeof(path));
371
372 int fd = open(path, O_WRONLY);
Elliott Hughes171df0a2016-08-02 13:30:30 -0700373 if (fd == -1) {
374 int ret = -errno;
Tom Cherry20514c42017-04-21 13:48:49 -0700375 PLOG(ERROR) << "Failed to open " << path;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700376 return ret;
377 }
378
379 char pid[PROCESSGROUP_MAX_PID_LEN + 1] = {0};
380 int len = snprintf(pid, sizeof(pid), "%d", initialPid);
381
Elliott Hughes171df0a2016-08-02 13:30:30 -0700382 int ret = 0;
383 if (write(fd, pid, len) < 0) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700384 ret = -errno;
Tom Cherry20514c42017-04-21 13:48:49 -0700385 PLOG(ERROR) << "Failed to write '" << pid << "' to " << path;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700386 }
387
388 close(fd);
389 return ret;
390}