blob: 9df8dd96f64d853c5d1d885b160d2d4479a69e16 [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 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>
Colin Crosscf8d1c22014-06-03 13:24:21 -070045#include <private/android_filesystem_config.h>
46
47#include <processgroup/processgroup.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
Peter Collingbourned7157c22018-10-30 15:49:33 -070056static const char kCpuacctCgroup[] = "/acct";
57static const char kMemoryCgroup[] = "/dev/memcg/apps";
Martijn Coenenb82bab62016-01-20 16:39:16 -080058
Martijn Coenenb82bab62016-01-20 16:39:16 -080059#define PROCESSGROUP_CGROUP_PROCS_FILE "/cgroup.procs"
Martijn Coenenb82bab62016-01-20 16:39:16 -080060
Peter Collingbourned7157c22018-10-30 15:49:33 -070061static bool isMemoryCgroupSupported() {
62 static bool memcg_supported = !access("/dev/memcg/memory.limit_in_bytes", F_OK);
63 return memcg_supported;
Martijn Coenenb82bab62016-01-20 16:39:16 -080064}
65
Peter Collingbourned7157c22018-10-30 15:49:33 -070066static std::string ConvertUidToPath(const char* cgroup, uid_t uid) {
67 return StringPrintf("%s/uid_%d", cgroup, uid);
Colin Crosscf8d1c22014-06-03 13:24:21 -070068}
69
Peter Collingbourned7157c22018-10-30 15:49:33 -070070static std::string ConvertUidPidToPath(const char* cgroup, uid_t uid, int pid) {
71 return StringPrintf("%s/uid_%d/pid_%d", cgroup, uid, pid);
Colin Crosscf8d1c22014-06-03 13:24:21 -070072}
73
Peter Collingbourned7157c22018-10-30 15:49:33 -070074static int RemoveProcessGroup(const char* cgroup, uid_t uid, int pid) {
Colin Crosscf8d1c22014-06-03 13:24:21 -070075 int ret;
Colin Crosscf8d1c22014-06-03 13:24:21 -070076
Peter Collingbourned7157c22018-10-30 15:49:33 -070077 auto uid_pid_path = ConvertUidPidToPath(cgroup, uid, pid);
Tom Cherry574a0812018-02-23 13:04:40 -080078 ret = rmdir(uid_pid_path.c_str());
Colin Crosscf8d1c22014-06-03 13:24:21 -070079
Peter Collingbourned7157c22018-10-30 15:49:33 -070080 auto uid_path = ConvertUidToPath(cgroup, uid);
Tom Cherry574a0812018-02-23 13:04:40 -080081 rmdir(uid_path.c_str());
Colin Crosscf8d1c22014-06-03 13:24:21 -070082
83 return ret;
84}
85
Tom Cherry574a0812018-02-23 13:04:40 -080086static void RemoveUidProcessGroups(const std::string& uid_path) {
87 std::unique_ptr<DIR, decltype(&closedir)> uid(opendir(uid_path.c_str()), closedir);
Colin Crosscf8d1c22014-06-03 13:24:21 -070088 if (uid != NULL) {
Elliott Hughes9f206932016-09-28 13:29:54 -070089 dirent* dir;
90 while ((dir = readdir(uid.get())) != nullptr) {
Colin Crosscf8d1c22014-06-03 13:24:21 -070091 if (dir->d_type != DT_DIR) {
92 continue;
93 }
94
Tom Cherry574a0812018-02-23 13:04:40 -080095 if (!StartsWith(dir->d_name, "pid_")) {
Colin Crosscf8d1c22014-06-03 13:24:21 -070096 continue;
97 }
98
Tom Cherry574a0812018-02-23 13:04:40 -080099 auto path = StringPrintf("%s/%s", uid_path.c_str(), dir->d_name);
Tom Cherry20514c42017-04-21 13:48:49 -0700100 LOG(VERBOSE) << "Removing " << path;
Tom Cherry574a0812018-02-23 13:04:40 -0800101 if (rmdir(path.c_str()) == -1) PLOG(WARNING) << "Failed to remove " << path;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700102 }
103 }
104}
105
106void removeAllProcessGroups()
107{
Elliott Hughes171df0a2016-08-02 13:30:30 -0700108 LOG(VERBOSE) << "removeAllProcessGroups()";
Peter Collingbourned7157c22018-10-30 15:49:33 -0700109 for (const char* cgroup_root_path : {kCpuacctCgroup, kMemoryCgroup}) {
110 std::unique_ptr<DIR, decltype(&closedir)> root(opendir(cgroup_root_path), closedir);
111 if (root == NULL) {
112 PLOG(ERROR) << "Failed to open " << cgroup_root_path;
113 } else {
114 dirent* dir;
115 while ((dir = readdir(root.get())) != nullptr) {
116 if (dir->d_type != DT_DIR) {
117 continue;
118 }
Tom Cherry574a0812018-02-23 13:04:40 -0800119
Peter Collingbourned7157c22018-10-30 15:49:33 -0700120 if (!StartsWith(dir->d_name, "uid_")) {
121 continue;
122 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700123
Peter Collingbourned7157c22018-10-30 15:49:33 -0700124 auto path = StringPrintf("%s/%s", cgroup_root_path, dir->d_name);
125 RemoveUidProcessGroups(path);
126 LOG(VERBOSE) << "Removing " << path;
127 if (rmdir(path.c_str()) == -1) PLOG(WARNING) << "Failed to remove " << path;
128 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700129 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700130 }
131}
132
Tom Cherry20514c42017-04-21 13:48:49 -0700133// Returns number of processes killed on success
134// Returns 0 if there are no processes in the process cgroup left to kill
Tom Cherry574a0812018-02-23 13:04:40 -0800135// Returns -1 on error
Peter Collingbourned7157c22018-10-30 15:49:33 -0700136static int DoKillProcessGroupOnce(const char* cgroup, uid_t uid, int initialPid, int signal) {
137 auto path = ConvertUidPidToPath(cgroup, uid, initialPid) + PROCESSGROUP_CGROUP_PROCS_FILE;
Tom Cherry574a0812018-02-23 13:04:40 -0800138 std::unique_ptr<FILE, decltype(&fclose)> fd(fopen(path.c_str(), "re"), fclose);
139 if (!fd) {
Tom Cherry20514c42017-04-21 13:48:49 -0700140 PLOG(WARNING) << "Failed to open process cgroup uid " << uid << " pid " << initialPid;
Tom Cherry574a0812018-02-23 13:04:40 -0800141 return -1;
Tom Cherry20514c42017-04-21 13:48:49 -0700142 }
143
Tom Cherry70a5ed42017-06-05 19:20:17 -0700144 // We separate all of the pids in the cgroup into those pids that are also the leaders of
145 // process groups (stored in the pgids set) and those that are not (stored in the pids set).
146 std::set<pid_t> pgids;
147 pgids.emplace(initialPid);
148 std::set<pid_t> pids;
149
Colin Crosscf8d1c22014-06-03 13:24:21 -0700150 pid_t pid;
Tom Cherry20514c42017-04-21 13:48:49 -0700151 int processes = 0;
Tom Cherry574a0812018-02-23 13:04:40 -0800152 while (fscanf(fd.get(), "%d\n", &pid) == 1 && pid >= 0) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700153 processes++;
Dianne Hackborn2c5e7e12014-10-13 17:45:22 -0700154 if (pid == 0) {
155 // Should never happen... but if it does, trying to kill this
156 // will boomerang right back and kill us! Let's not let that happen.
Elliott Hughes171df0a2016-08-02 13:30:30 -0700157 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 -0700158 continue;
159 }
Tom Cherry70a5ed42017-06-05 19:20:17 -0700160 pid_t pgid = getpgid(pid);
161 if (pgid == -1) PLOG(ERROR) << "getpgid(" << pid << ") failed";
162 if (pgid == pid) {
163 pgids.emplace(pid);
164 } else {
165 pids.emplace(pid);
166 }
167 }
168
169 // Erase all pids that will be killed when we kill the process groups.
170 for (auto it = pids.begin(); it != pids.end();) {
fengshaobo950f6f32018-09-13 14:57:07 +0800171 pid_t pgid = getpgid(*it);
Tom Cherry70a5ed42017-06-05 19:20:17 -0700172 if (pgids.count(pgid) == 1) {
173 it = pids.erase(it);
174 } else {
175 ++it;
176 }
177 }
178
179 // Kill all process groups.
180 for (const auto pgid : pgids) {
181 LOG(VERBOSE) << "Killing process group " << -pgid << " in uid " << uid
182 << " as part of process cgroup " << initialPid;
183
184 if (kill(-pgid, signal) == -1) {
185 PLOG(WARNING) << "kill(" << -pgid << ", " << signal << ") failed";
186 }
187 }
188
189 // Kill remaining pids.
190 for (const auto pid : pids) {
Tom Cherry20514c42017-04-21 13:48:49 -0700191 LOG(VERBOSE) << "Killing pid " << pid << " in uid " << uid << " as part of process cgroup "
192 << initialPid;
Tom Cherry70a5ed42017-06-05 19:20:17 -0700193
Elliott Hughes171df0a2016-08-02 13:30:30 -0700194 if (kill(pid, signal) == -1) {
195 PLOG(WARNING) << "kill(" << pid << ", " << signal << ") failed";
Colin Crosscf8d1c22014-06-03 13:24:21 -0700196 }
197 }
198
Tom Cherry574a0812018-02-23 13:04:40 -0800199 return feof(fd.get()) ? processes : -1;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700200}
201
Tom Cherry574a0812018-02-23 13:04:40 -0800202static int KillProcessGroup(uid_t uid, int initialPid, int signal, int retries) {
Peter Collingbourned7157c22018-10-30 15:49:33 -0700203 const char* cgroup =
204 (!access(ConvertUidPidToPath(kCpuacctCgroup, uid, initialPid).c_str(), F_OK))
205 ? kCpuacctCgroup
206 : kMemoryCgroup;
207
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000208 std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
Colin Crosscf8d1c22014-06-03 13:24:21 -0700209
Tom Cherry20514c42017-04-21 13:48:49 -0700210 int retry = retries;
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000211 int processes;
Peter Collingbourned7157c22018-10-30 15:49:33 -0700212 while ((processes = DoKillProcessGroupOnce(cgroup, uid, initialPid, signal)) > 0) {
Tom Cherry20514c42017-04-21 13:48:49 -0700213 LOG(VERBOSE) << "Killed " << processes << " processes for processgroup " << initialPid;
Yusuke Satod5039302015-06-16 13:51:14 -0700214 if (retry > 0) {
Elliott Hughes290a2282016-11-14 17:08:47 -0800215 std::this_thread::sleep_for(5ms);
Yusuke Satod5039302015-06-16 13:51:14 -0700216 --retry;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700217 } else {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700218 break;
219 }
220 }
221
Tom Cherry20514c42017-04-21 13:48:49 -0700222 if (processes < 0) {
223 PLOG(ERROR) << "Error encountered killing process cgroup uid " << uid << " pid "
224 << initialPid;
225 return -1;
226 }
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000227
Tom Cherry20514c42017-04-21 13:48:49 -0700228 std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
Elliott Hughes171df0a2016-08-02 13:30:30 -0700229 auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
Tom Cherry20514c42017-04-21 13:48:49 -0700230
231 // We only calculate the number of 'processes' when killing the processes.
232 // In the retries == 0 case, we only kill the processes once and therefore
233 // will not have waited then recalculated how many processes are remaining
234 // after the first signals have been sent.
235 // Logging anything regarding the number of 'processes' here does not make sense.
Dianne Hackborn2c5e7e12014-10-13 17:45:22 -0700236
Colin Crosscf8d1c22014-06-03 13:24:21 -0700237 if (processes == 0) {
Tom Cherry20514c42017-04-21 13:48:49 -0700238 if (retries > 0) {
239 LOG(INFO) << "Successfully killed process cgroup uid " << uid << " pid " << initialPid
240 << " in " << static_cast<int>(ms) << "ms";
241 }
Peter Collingbourned7157c22018-10-30 15:49:33 -0700242 return RemoveProcessGroup(cgroup, uid, initialPid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700243 } else {
Tom Cherry20514c42017-04-21 13:48:49 -0700244 if (retries > 0) {
245 LOG(ERROR) << "Failed to kill process cgroup uid " << uid << " pid " << initialPid
246 << " in " << static_cast<int>(ms) << "ms, " << processes
247 << " processes remain";
248 }
Colin Crosscf8d1c22014-06-03 13:24:21 -0700249 return -1;
250 }
251}
252
Keun-young Parkfac4b632017-03-28 17:25:24 -0700253int killProcessGroup(uid_t uid, int initialPid, int signal) {
Tom Cherry574a0812018-02-23 13:04:40 -0800254 return KillProcessGroup(uid, initialPid, signal, 40 /*retries*/);
Keun-young Parkfac4b632017-03-28 17:25:24 -0700255}
256
257int killProcessGroupOnce(uid_t uid, int initialPid, int signal) {
Tom Cherry574a0812018-02-23 13:04:40 -0800258 return KillProcessGroup(uid, initialPid, signal, 0 /*retries*/);
Keun-young Parkfac4b632017-03-28 17:25:24 -0700259}
260
Tom Cherry574a0812018-02-23 13:04:40 -0800261static bool MkdirAndChown(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
262 if (mkdir(path.c_str(), mode) == -1 && errno != EEXIST) {
Elliott Hughes171df0a2016-08-02 13:30:30 -0700263 return false;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700264 }
265
Tom Cherry574a0812018-02-23 13:04:40 -0800266 if (chown(path.c_str(), uid, gid) == -1) {
Elliott Hughes171df0a2016-08-02 13:30:30 -0700267 int saved_errno = errno;
Tom Cherry574a0812018-02-23 13:04:40 -0800268 rmdir(path.c_str());
Elliott Hughes171df0a2016-08-02 13:30:30 -0700269 errno = saved_errno;
270 return false;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700271 }
272
Elliott Hughes171df0a2016-08-02 13:30:30 -0700273 return true;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700274}
275
Peter Collingbourned7157c22018-10-30 15:49:33 -0700276static bool isPerAppMemcgEnabled() {
277 static bool per_app_memcg =
278 GetBoolProperty("ro.config.per_app_memcg", GetBoolProperty("ro.config.low_ram", false));
279 return per_app_memcg;
280}
281
282int createProcessGroup(uid_t uid, int initialPid, bool memControl)
Colin Crosscf8d1c22014-06-03 13:24:21 -0700283{
Peter Collingbourned7157c22018-10-30 15:49:33 -0700284 const char* cgroup;
285 if (isMemoryCgroupSupported() && (memControl || isPerAppMemcgEnabled())) {
286 cgroup = kMemoryCgroup;
287 } else {
288 cgroup = kCpuacctCgroup;
289 }
290
291 auto uid_path = ConvertUidToPath(cgroup, uid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700292
Tom Cherry574a0812018-02-23 13:04:40 -0800293 if (!MkdirAndChown(uid_path, 0750, AID_SYSTEM, AID_SYSTEM)) {
294 PLOG(ERROR) << "Failed to make and chown " << uid_path;
Elliott Hughes171df0a2016-08-02 13:30:30 -0700295 return -errno;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700296 }
297
Peter Collingbourned7157c22018-10-30 15:49:33 -0700298 auto uid_pid_path = ConvertUidPidToPath(cgroup, uid, initialPid);
Colin Crosscf8d1c22014-06-03 13:24:21 -0700299
Tom Cherry574a0812018-02-23 13:04:40 -0800300 if (!MkdirAndChown(uid_pid_path, 0750, AID_SYSTEM, AID_SYSTEM)) {
301 PLOG(ERROR) << "Failed to make and chown " << uid_pid_path;
Elliott Hughes171df0a2016-08-02 13:30:30 -0700302 return -errno;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700303 }
304
Tom Cherry574a0812018-02-23 13:04:40 -0800305 auto uid_pid_procs_file = uid_pid_path + PROCESSGROUP_CGROUP_PROCS_FILE;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700306
Elliott Hughes171df0a2016-08-02 13:30:30 -0700307 int ret = 0;
Tom Cherry574a0812018-02-23 13:04:40 -0800308 if (!WriteStringToFile(std::to_string(initialPid), uid_pid_procs_file)) {
Colin Crosscf8d1c22014-06-03 13:24:21 -0700309 ret = -errno;
Tom Cherry574a0812018-02-23 13:04:40 -0800310 PLOG(ERROR) << "Failed to write '" << initialPid << "' to " << uid_pid_procs_file;
Colin Crosscf8d1c22014-06-03 13:24:21 -0700311 }
312
Colin Crosscf8d1c22014-06-03 13:24:21 -0700313 return ret;
314}
Robert Benead4852262017-07-16 19:38:11 -0700315
Tom Cherry574a0812018-02-23 13:04:40 -0800316static bool SetProcessGroupValue(uid_t uid, int pid, const std::string& file_name, int64_t value) {
Peter Collingbourned7157c22018-10-30 15:49:33 -0700317 if (!isMemoryCgroupSupported()) {
Tom Cherry574a0812018-02-23 13:04:40 -0800318 PLOG(ERROR) << "Memcg is not mounted.";
Robert Benead4852262017-07-16 19:38:11 -0700319 return false;
320 }
321
Peter Collingbourned7157c22018-10-30 15:49:33 -0700322 auto path = ConvertUidPidToPath(kMemoryCgroup, uid, pid) + file_name;
Robert Benead4852262017-07-16 19:38:11 -0700323
324 if (!WriteStringToFile(std::to_string(value), path)) {
325 PLOG(ERROR) << "Failed to write '" << value << "' to " << path;
326 return false;
327 }
328 return true;
329}
330
331bool setProcessGroupSwappiness(uid_t uid, int pid, int swappiness) {
Tom Cherry574a0812018-02-23 13:04:40 -0800332 return SetProcessGroupValue(uid, pid, "/memory.swappiness", swappiness);
Robert Benead4852262017-07-16 19:38:11 -0700333}
334
335bool setProcessGroupSoftLimit(uid_t uid, int pid, int64_t soft_limit_in_bytes) {
Tom Cherry574a0812018-02-23 13:04:40 -0800336 return SetProcessGroupValue(uid, pid, "/memory.soft_limit_in_bytes", soft_limit_in_bytes);
Robert Benead4852262017-07-16 19:38:11 -0700337}
338
339bool setProcessGroupLimit(uid_t uid, int pid, int64_t limit_in_bytes) {
Tom Cherry574a0812018-02-23 13:04:40 -0800340 return SetProcessGroupValue(uid, pid, "/memory.limit_in_bytes", limit_in_bytes);
Robert Benead4852262017-07-16 19:38:11 -0700341}