blob: 58295fadbdebf82e97292042134d336a3df55aec [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>
28#include <string.h>
29#include <sys/stat.h>
30#include <sys/types.h>
Tom Cherry70a5ed42017-06-05 19:20:17 -070031#include <unistd.h>
Collin Mullinerf7e79b92016-06-01 21:03:55 +000032
33#include <chrono>
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 Baghdasaryancbb69022018-05-23 12:30:44 -070042#ifdef __ANDROID__
43#include <android-base/properties.h>
44#endif
Tom Cherry574a0812018-02-23 13:04:40 -080045#include <android-base/stringprintf.h>
46#include <android-base/strings.h>
Colin Crosscf8d1c22014-06-03 13:24:21 -070047#include <private/android_filesystem_config.h>
48
49#include <processgroup/processgroup.h>
Martijn Coenenb82bab62016-01-20 16:39:16 -080050
Suren Baghdasaryancbb69022018-05-23 12:30:44 -070051#ifdef __ANDROID__
52using android::base::GetBoolProperty;
53#endif
Tom Cherry574a0812018-02-23 13:04:40 -080054using android::base::StartsWith;
55using android::base::StringPrintf;
Robert Benead4852262017-07-16 19:38:11 -070056using android::base::WriteStringToFile;
57
Elliott Hughes290a2282016-11-14 17:08:47 -080058using namespace std::chrono_literals;
59
Martijn Coenenb82bab62016-01-20 16:39:16 -080060#define MEM_CGROUP_PATH "/dev/memcg/apps"
Martijn Coenen623b56a2016-02-08 11:42:25 +010061#define MEM_CGROUP_TASKS "/dev/memcg/apps/tasks"
Martijn Coenenb82bab62016-01-20 16:39:16 -080062#define ACCT_CGROUP_PATH "/acct"
63
Martijn Coenenb82bab62016-01-20 16:39:16 -080064#define PROCESSGROUP_CGROUP_PROCS_FILE "/cgroup.procs"
Martijn Coenenb82bab62016-01-20 16:39:16 -080065
66std::once_flag init_path_flag;
Colin Crosscf8d1c22014-06-03 13:24:21 -070067
Tom Cherry574a0812018-02-23 13:04:40 -080068static const std::string& GetCgroupRootPath() {
69 static std::string cgroup_root_path;
Martijn Coenenb82bab62016-01-20 16:39:16 -080070 std::call_once(init_path_flag, [&]() {
Suren Baghdasaryancbb69022018-05-23 12:30:44 -070071#ifdef __ANDROID__
72 // low-ram devices use per-app memcg by default, unlike high-end ones
73 bool low_ram_device = GetBoolProperty("ro.config.low_ram", false);
74 bool per_app_memcg =
75 GetBoolProperty("ro.config.per_app_memcg", low_ram_device);
76#else
77 // host does not support Android properties
78 bool per_app_memcg = false;
79#endif
80 if (per_app_memcg) {
81 // Check if mem cgroup is mounted, only then check for
82 // write-access to avoid SELinux denials
Tom Cherry574a0812018-02-23 13:04:40 -080083 cgroup_root_path =
Suren Baghdasaryancbb69022018-05-23 12:30:44 -070084 (access(MEM_CGROUP_TASKS, F_OK) || access(MEM_CGROUP_PATH, W_OK) ?
85 ACCT_CGROUP_PATH : MEM_CGROUP_PATH);
86 } else {
87 cgroup_root_path = ACCT_CGROUP_PATH;
88 }
89 });
Martijn Coenenb82bab62016-01-20 16:39:16 -080090 return cgroup_root_path;
91}
92
Tom Cherry574a0812018-02-23 13:04:40 -080093static std::string ConvertUidToPath(uid_t uid) {
94 return StringPrintf("%s/uid_%d", GetCgroupRootPath().c_str(), uid);
Colin Crosscf8d1c22014-06-03 13:24:21 -070095}
96
Tom Cherry574a0812018-02-23 13:04:40 -080097static std::string ConvertUidPidToPath(uid_t uid, int pid) {
98 return StringPrintf("%s/uid_%d/pid_%d", GetCgroupRootPath().c_str(), uid, pid);
Colin Crosscf8d1c22014-06-03 13:24:21 -070099}
100
Tom Cherry574a0812018-02-23 13:04:40 -0800101static int RemoveProcessGroup(uid_t uid, int pid) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700102 int ret;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700103
Tom Cherry574a0812018-02-23 13:04:40 -0800104 auto uid_pid_path = ConvertUidPidToPath(uid, pid);
105 ret = rmdir(uid_pid_path.c_str());
Colin Crosscf8d1c22014-06-03 13:24:21 -0700106
Tom Cherry574a0812018-02-23 13:04:40 -0800107 auto uid_path = ConvertUidToPath(uid);
108 rmdir(uid_path.c_str());
Colin Crosscf8d1c22014-06-03 13:24:21 -0700109
110 return ret;
111}
112
Tom Cherry574a0812018-02-23 13:04:40 -0800113static void RemoveUidProcessGroups(const std::string& uid_path) {
114 std::unique_ptr<DIR, decltype(&closedir)> uid(opendir(uid_path.c_str()), closedir);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700115 if (uid != NULL) {
Elliott Hughes9f206932016-09-28 13:29:54 -0700116 dirent* dir;
117 while ((dir = readdir(uid.get())) != nullptr) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700118 if (dir->d_type != DT_DIR) {
119 continue;
120 }
121
Tom Cherry574a0812018-02-23 13:04:40 -0800122 if (!StartsWith(dir->d_name, "pid_")) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700123 continue;
124 }
125
Tom Cherry574a0812018-02-23 13:04:40 -0800126 auto path = StringPrintf("%s/%s", uid_path.c_str(), dir->d_name);
Tom Cherry20514c42017-04-21 13:48:49 -0700127 LOG(VERBOSE) << "Removing " << path;
Tom Cherry574a0812018-02-23 13:04:40 -0800128 if (rmdir(path.c_str()) == -1) PLOG(WARNING) << "Failed to remove " << path;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700129 }
130 }
131}
132
133void removeAllProcessGroups()
134{
Elliott Hughes171df0a2016-08-02 13:30:30 -0700135 LOG(VERBOSE) << "removeAllProcessGroups()";
Tom Cherry574a0812018-02-23 13:04:40 -0800136 const auto& cgroup_root_path = GetCgroupRootPath();
137 std::unique_ptr<DIR, decltype(&closedir)> root(opendir(cgroup_root_path.c_str()), closedir);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700138 if (root == NULL) {
Tom Cherry20514c42017-04-21 13:48:49 -0700139 PLOG(ERROR) << "Failed to open " << cgroup_root_path;
Colin Crossc15dd042014-08-20 14:11:13 -0700140 } else {
Elliott Hughes9f206932016-09-28 13:29:54 -0700141 dirent* dir;
142 while ((dir = readdir(root.get())) != nullptr) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700143 if (dir->d_type != DT_DIR) {
144 continue;
145 }
Tom Cherry574a0812018-02-23 13:04:40 -0800146
147 if (!StartsWith(dir->d_name, "uid_")) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700148 continue;
149 }
150
Tom Cherry574a0812018-02-23 13:04:40 -0800151 auto path = StringPrintf("%s/%s", cgroup_root_path.c_str(), dir->d_name);
152 RemoveUidProcessGroups(path);
Tom Cherry20514c42017-04-21 13:48:49 -0700153 LOG(VERBOSE) << "Removing " << path;
Tom Cherry574a0812018-02-23 13:04:40 -0800154 if (rmdir(path.c_str()) == -1) PLOG(WARNING) << "Failed to remove " << path;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700155 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700156 }
157}
158
Tom Cherry20514c42017-04-21 13:48:49 -0700159// Returns number of processes killed on success
160// Returns 0 if there are no processes in the process cgroup left to kill
Tom Cherry574a0812018-02-23 13:04:40 -0800161// Returns -1 on error
162static int DoKillProcessGroupOnce(uid_t uid, int initialPid, int signal) {
163 auto path = ConvertUidPidToPath(uid, initialPid) + PROCESSGROUP_CGROUP_PROCS_FILE;
164 std::unique_ptr<FILE, decltype(&fclose)> fd(fopen(path.c_str(), "re"), fclose);
165 if (!fd) {
Tom Cherry20514c42017-04-21 13:48:49 -0700166 PLOG(WARNING) << "Failed to open process cgroup uid " << uid << " pid " << initialPid;
Tom Cherry574a0812018-02-23 13:04:40 -0800167 return -1;
Tom Cherry20514c42017-04-21 13:48:49 -0700168 }
169
Tom Cherry70a5ed42017-06-05 19:20:17 -0700170 // We separate all of the pids in the cgroup into those pids that are also the leaders of
171 // process groups (stored in the pgids set) and those that are not (stored in the pids set).
172 std::set<pid_t> pgids;
173 pgids.emplace(initialPid);
174 std::set<pid_t> pids;
175
Colin Crosscf8d1c22014-06-03 13:24:21 -0700176 pid_t pid;
Tom Cherry20514c42017-04-21 13:48:49 -0700177 int processes = 0;
Tom Cherry574a0812018-02-23 13:04:40 -0800178 while (fscanf(fd.get(), "%d\n", &pid) == 1 && pid >= 0) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700179 processes++;
Dianne Hackborn2c5e7e12014-10-13 17:45:22 -0700180 if (pid == 0) {
181 // Should never happen... but if it does, trying to kill this
182 // will boomerang right back and kill us! Let's not let that happen.
Elliott Hughes171df0a2016-08-02 13:30:30 -0700183 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 -0700184 continue;
185 }
Tom Cherry70a5ed42017-06-05 19:20:17 -0700186 pid_t pgid = getpgid(pid);
187 if (pgid == -1) PLOG(ERROR) << "getpgid(" << pid << ") failed";
188 if (pgid == pid) {
189 pgids.emplace(pid);
190 } else {
191 pids.emplace(pid);
192 }
193 }
194
195 // Erase all pids that will be killed when we kill the process groups.
196 for (auto it = pids.begin(); it != pids.end();) {
197 pid_t pgid = getpgid(pid);
198 if (pgids.count(pgid) == 1) {
199 it = pids.erase(it);
200 } else {
201 ++it;
202 }
203 }
204
205 // Kill all process groups.
206 for (const auto pgid : pgids) {
207 LOG(VERBOSE) << "Killing process group " << -pgid << " in uid " << uid
208 << " as part of process cgroup " << initialPid;
209
210 if (kill(-pgid, signal) == -1) {
211 PLOG(WARNING) << "kill(" << -pgid << ", " << signal << ") failed";
212 }
213 }
214
215 // Kill remaining pids.
216 for (const auto pid : pids) {
Tom Cherry20514c42017-04-21 13:48:49 -0700217 LOG(VERBOSE) << "Killing pid " << pid << " in uid " << uid << " as part of process cgroup "
218 << initialPid;
Tom Cherry70a5ed42017-06-05 19:20:17 -0700219
Elliott Hughes171df0a2016-08-02 13:30:30 -0700220 if (kill(pid, signal) == -1) {
221 PLOG(WARNING) << "kill(" << pid << ", " << signal << ") failed";
Colin Crosscf8d1c22014-06-03 13:24:21 -0700222 }
223 }
224
Tom Cherry574a0812018-02-23 13:04:40 -0800225 return feof(fd.get()) ? processes : -1;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700226}
227
Tom Cherry574a0812018-02-23 13:04:40 -0800228static int KillProcessGroup(uid_t uid, int initialPid, int signal, int retries) {
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000229 std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
Colin Crosscf8d1c22014-06-03 13:24:21 -0700230
Tom Cherry20514c42017-04-21 13:48:49 -0700231 int retry = retries;
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000232 int processes;
Tom Cherry574a0812018-02-23 13:04:40 -0800233 while ((processes = DoKillProcessGroupOnce(uid, initialPid, signal)) > 0) {
Tom Cherry20514c42017-04-21 13:48:49 -0700234 LOG(VERBOSE) << "Killed " << processes << " processes for processgroup " << initialPid;
Yusuke Satod5039302015-06-16 13:51:14 -0700235 if (retry > 0) {
Elliott Hughes290a2282016-11-14 17:08:47 -0800236 std::this_thread::sleep_for(5ms);
Yusuke Satod5039302015-06-16 13:51:14 -0700237 --retry;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700238 } else {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700239 break;
240 }
241 }
242
Tom Cherry20514c42017-04-21 13:48:49 -0700243 if (processes < 0) {
244 PLOG(ERROR) << "Error encountered killing process cgroup uid " << uid << " pid "
245 << initialPid;
246 return -1;
247 }
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000248
Tom Cherry20514c42017-04-21 13:48:49 -0700249 std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
Elliott Hughes171df0a2016-08-02 13:30:30 -0700250 auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
Tom Cherry20514c42017-04-21 13:48:49 -0700251
252 // We only calculate the number of 'processes' when killing the processes.
253 // In the retries == 0 case, we only kill the processes once and therefore
254 // will not have waited then recalculated how many processes are remaining
255 // after the first signals have been sent.
256 // Logging anything regarding the number of 'processes' here does not make sense.
Dianne Hackborn2c5e7e12014-10-13 17:45:22 -0700257
Colin Crosscf8d1c22014-06-03 13:24:21 -0700258 if (processes == 0) {
Tom Cherry20514c42017-04-21 13:48:49 -0700259 if (retries > 0) {
260 LOG(INFO) << "Successfully killed process cgroup uid " << uid << " pid " << initialPid
261 << " in " << static_cast<int>(ms) << "ms";
262 }
Tom Cherry574a0812018-02-23 13:04:40 -0800263 return RemoveProcessGroup(uid, initialPid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700264 } else {
Tom Cherry20514c42017-04-21 13:48:49 -0700265 if (retries > 0) {
266 LOG(ERROR) << "Failed to kill process cgroup uid " << uid << " pid " << initialPid
267 << " in " << static_cast<int>(ms) << "ms, " << processes
268 << " processes remain";
269 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700270 return -1;
271 }
272}
273
Keun-young Parkfac4b632017-03-28 17:25:24 -0700274int killProcessGroup(uid_t uid, int initialPid, int signal) {
Tom Cherry574a0812018-02-23 13:04:40 -0800275 return KillProcessGroup(uid, initialPid, signal, 40 /*retries*/);
Keun-young Parkfac4b632017-03-28 17:25:24 -0700276}
277
278int killProcessGroupOnce(uid_t uid, int initialPid, int signal) {
Tom Cherry574a0812018-02-23 13:04:40 -0800279 return KillProcessGroup(uid, initialPid, signal, 0 /*retries*/);
Keun-young Parkfac4b632017-03-28 17:25:24 -0700280}
281
Tom Cherry574a0812018-02-23 13:04:40 -0800282static bool MkdirAndChown(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
283 if (mkdir(path.c_str(), mode) == -1 && errno != EEXIST) {
Elliott Hughes171df0a2016-08-02 13:30:30 -0700284 return false;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700285 }
286
Tom Cherry574a0812018-02-23 13:04:40 -0800287 if (chown(path.c_str(), uid, gid) == -1) {
Elliott Hughes171df0a2016-08-02 13:30:30 -0700288 int saved_errno = errno;
Tom Cherry574a0812018-02-23 13:04:40 -0800289 rmdir(path.c_str());
Elliott Hughes171df0a2016-08-02 13:30:30 -0700290 errno = saved_errno;
291 return false;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700292 }
293
Elliott Hughes171df0a2016-08-02 13:30:30 -0700294 return true;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700295}
296
297int createProcessGroup(uid_t uid, int initialPid)
298{
Tom Cherry574a0812018-02-23 13:04:40 -0800299 auto uid_path = ConvertUidToPath(uid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700300
Tom Cherry574a0812018-02-23 13:04:40 -0800301 if (!MkdirAndChown(uid_path, 0750, AID_SYSTEM, AID_SYSTEM)) {
302 PLOG(ERROR) << "Failed to make and chown " << uid_path;
Elliott Hughes171df0a2016-08-02 13:30:30 -0700303 return -errno;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700304 }
305
Tom Cherry574a0812018-02-23 13:04:40 -0800306 auto uid_pid_path = ConvertUidPidToPath(uid, initialPid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700307
Tom Cherry574a0812018-02-23 13:04:40 -0800308 if (!MkdirAndChown(uid_pid_path, 0750, AID_SYSTEM, AID_SYSTEM)) {
309 PLOG(ERROR) << "Failed to make and chown " << uid_pid_path;
Elliott Hughes171df0a2016-08-02 13:30:30 -0700310 return -errno;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700311 }
312
Tom Cherry574a0812018-02-23 13:04:40 -0800313 auto uid_pid_procs_file = uid_pid_path + PROCESSGROUP_CGROUP_PROCS_FILE;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700314
Elliott Hughes171df0a2016-08-02 13:30:30 -0700315 int ret = 0;
Tom Cherry574a0812018-02-23 13:04:40 -0800316 if (!WriteStringToFile(std::to_string(initialPid), uid_pid_procs_file)) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700317 ret = -errno;
Tom Cherry574a0812018-02-23 13:04:40 -0800318 PLOG(ERROR) << "Failed to write '" << initialPid << "' to " << uid_pid_procs_file;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700319 }
320
Colin Crosscf8d1c22014-06-03 13:24:21 -0700321 return ret;
322}
Robert Benead4852262017-07-16 19:38:11 -0700323
Tom Cherry574a0812018-02-23 13:04:40 -0800324static bool SetProcessGroupValue(uid_t uid, int pid, const std::string& file_name, int64_t value) {
325 if (GetCgroupRootPath() != MEM_CGROUP_PATH) {
326 PLOG(ERROR) << "Memcg is not mounted.";
Robert Benead4852262017-07-16 19:38:11 -0700327 return false;
328 }
329
Tom Cherry574a0812018-02-23 13:04:40 -0800330 auto path = ConvertUidPidToPath(uid, pid) + file_name;
Robert Benead4852262017-07-16 19:38:11 -0700331
332 if (!WriteStringToFile(std::to_string(value), path)) {
333 PLOG(ERROR) << "Failed to write '" << value << "' to " << path;
334 return false;
335 }
336 return true;
337}
338
339bool setProcessGroupSwappiness(uid_t uid, int pid, int swappiness) {
Tom Cherry574a0812018-02-23 13:04:40 -0800340 return SetProcessGroupValue(uid, pid, "/memory.swappiness", swappiness);
Robert Benead4852262017-07-16 19:38:11 -0700341}
342
343bool setProcessGroupSoftLimit(uid_t uid, int pid, int64_t soft_limit_in_bytes) {
Tom Cherry574a0812018-02-23 13:04:40 -0800344 return SetProcessGroupValue(uid, pid, "/memory.soft_limit_in_bytes", soft_limit_in_bytes);
Robert Benead4852262017-07-16 19:38:11 -0700345}
346
347bool setProcessGroupLimit(uid_t uid, int pid, int64_t limit_in_bytes) {
Tom Cherry574a0812018-02-23 13:04:40 -0800348 return SetProcessGroupValue(uid, pid, "/memory.limit_in_bytes", limit_in_bytes);
Robert Benead4852262017-07-16 19:38:11 -0700349}