blob: 7a04100ac55c7c5fcf24b1b19f5ab5058ed3d0e5 [file] [log] [blame]
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -08001/*
2 * Copyright (C) 2019 The Android Open Source Project
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 <fcntl.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080021#include <task_profiles.h>
22#include <string>
23
24#include <android-base/file.h>
25#include <android-base/logging.h>
Suren Baghdasaryan35221b52020-11-20 17:08:51 -080026#include <android-base/properties.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080027#include <android-base/stringprintf.h>
Rick Yiubc1ad962020-10-26 20:32:52 +080028#include <android-base/strings.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080029#include <android-base/threads.h>
30
31#include <cutils/android_filesystem_config.h>
32
33#include <json/reader.h>
34#include <json/value.h>
35
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -080036// To avoid issues in sdk_mac build
37#if defined(__ANDROID__)
38#include <sys/prctl.h>
39#endif
40
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080041using android::base::GetThreadId;
Suren Baghdasaryan35221b52020-11-20 17:08:51 -080042using android::base::GetUintProperty;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080043using android::base::StringPrintf;
Rick Yiubc1ad962020-10-26 20:32:52 +080044using android::base::StringReplace;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080045using android::base::unique_fd;
46using android::base::WriteStringToFile;
47
Suren Baghdasaryan35221b52020-11-20 17:08:51 -080048static constexpr const char* TASK_PROFILE_DB_FILE = "/etc/task_profiles.json";
49static constexpr const char* TASK_PROFILE_DB_VENDOR_FILE = "/vendor/etc/task_profiles.json";
50
51static constexpr const char* TEMPLATE_TASK_PROFILE_API_FILE =
52 "/etc/task_profiles/task_profiles_%u.json";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080053
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -080054class FdCacheHelper {
55 public:
56 enum FdState {
57 FDS_INACCESSIBLE = -1,
58 FDS_APP_DEPENDENT = -2,
59 FDS_NOT_CACHED = -3,
60 };
61
62 static void Cache(const std::string& path, android::base::unique_fd& fd);
63 static void Drop(android::base::unique_fd& fd);
64 static void Init(const std::string& path, android::base::unique_fd& fd);
65 static bool IsCached(const android::base::unique_fd& fd) { return fd > FDS_INACCESSIBLE; }
66
67 private:
68 static bool IsAppDependentPath(const std::string& path);
69};
70
71void FdCacheHelper::Init(const std::string& path, android::base::unique_fd& fd) {
72 // file descriptors for app-dependent paths can't be cached
73 if (IsAppDependentPath(path)) {
74 // file descriptor is not cached
75 fd.reset(FDS_APP_DEPENDENT);
76 return;
77 }
78 // file descriptor can be cached later on request
79 fd.reset(FDS_NOT_CACHED);
80}
81
82void FdCacheHelper::Cache(const std::string& path, android::base::unique_fd& fd) {
83 if (fd != FDS_NOT_CACHED) {
84 return;
85 }
86
87 if (access(path.c_str(), W_OK) != 0) {
88 // file is not accessible
89 fd.reset(FDS_INACCESSIBLE);
90 return;
91 }
92
93 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_WRONLY | O_CLOEXEC)));
94 if (tmp_fd < 0) {
95 PLOG(ERROR) << "Failed to cache fd '" << path << "'";
96 fd.reset(FDS_INACCESSIBLE);
97 return;
98 }
99
100 fd = std::move(tmp_fd);
101}
102
103void FdCacheHelper::Drop(android::base::unique_fd& fd) {
104 if (fd == FDS_NOT_CACHED) {
105 return;
106 }
107
108 fd.reset(FDS_NOT_CACHED);
109}
110
111bool FdCacheHelper::IsAppDependentPath(const std::string& path) {
112 return path.find("<uid>", 0) != std::string::npos || path.find("<pid>", 0) != std::string::npos;
113}
114
Bart Van Assche4c99e962022-02-03 19:50:16 +0000115IProfileAttribute::~IProfileAttribute() = default;
116
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700117void ProfileAttribute::Reset(const CgroupController& controller, const std::string& file_name) {
118 controller_ = controller;
119 file_name_ = file_name;
120}
121
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800122bool ProfileAttribute::GetPathForTask(int tid, std::string* path) const {
123 std::string subgroup;
Yifan Hong53e0deb2019-03-22 17:01:08 -0700124 if (!controller()->GetTaskGroup(tid, &subgroup)) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800125 return false;
126 }
127
128 if (path == nullptr) {
129 return true;
130 }
131
Bart Van Asschebc077ff2022-02-17 01:26:44 +0000132 const std::string& file_name =
133 controller()->version() == 2 && !file_v2_name_.empty() ? file_v2_name_ : file_name_;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800134 if (subgroup.empty()) {
Bart Van Asschebc077ff2022-02-17 01:26:44 +0000135 *path = StringPrintf("%s/%s", controller()->path(), file_name.c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800136 } else {
Bart Van Asschebc077ff2022-02-17 01:26:44 +0000137 *path = StringPrintf("%s/%s/%s", controller()->path(), subgroup.c_str(), file_name.c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800138 }
139 return true;
140}
141
142bool SetClampsAction::ExecuteForProcess(uid_t, pid_t) const {
143 // TODO: add support when kernel supports util_clamp
144 LOG(WARNING) << "SetClampsAction::ExecuteForProcess is not supported";
145 return false;
146}
147
148bool SetClampsAction::ExecuteForTask(int) const {
149 // TODO: add support when kernel supports util_clamp
150 LOG(WARNING) << "SetClampsAction::ExecuteForTask is not supported";
151 return false;
152}
153
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -0800154// To avoid issues in sdk_mac build
155#if defined(__ANDROID__)
156
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800157bool SetTimerSlackAction::IsTimerSlackSupported(int tid) {
158 auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
159
160 return (access(file.c_str(), W_OK) == 0);
161}
162
163bool SetTimerSlackAction::ExecuteForTask(int tid) const {
164 static bool sys_supports_timerslack = IsTimerSlackSupported(tid);
165
166 // v4.6+ kernels support the /proc/<tid>/timerslack_ns interface.
167 // TODO: once we've backported this, log if the open(2) fails.
168 if (sys_supports_timerslack) {
169 auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
170 if (!WriteStringToFile(std::to_string(slack_), file)) {
Suren Baghdasaryan2bc52282019-02-12 17:30:26 -0800171 if (errno == ENOENT) {
172 // This happens when process is already dead
173 return true;
174 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800175 PLOG(ERROR) << "set_timerslack_ns write failed";
176 }
177 }
178
179 // TODO: Remove when /proc/<tid>/timerslack_ns interface is backported.
180 if (tid == 0 || tid == GetThreadId()) {
181 if (prctl(PR_SET_TIMERSLACK, slack_) == -1) {
182 PLOG(ERROR) << "set_timerslack_ns prctl failed";
183 }
184 }
185
186 return true;
187}
188
Bart Van Assche20d59bd2022-01-24 19:45:59 +0000189#else
190
191bool SetTimerSlackAction::ExecuteForTask(int) const {
192 return true;
193};
194
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -0800195#endif
196
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800197bool SetAttributeAction::ExecuteForProcess(uid_t, pid_t pid) const {
198 return ExecuteForTask(pid);
199}
200
201bool SetAttributeAction::ExecuteForTask(int tid) const {
202 std::string path;
203
204 if (!attribute_->GetPathForTask(tid, &path)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800205 LOG(ERROR) << "Failed to find cgroup for tid " << tid;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800206 return false;
207 }
208
209 if (!WriteStringToFile(value_, path)) {
Bart Van Assche9b5a2322022-03-22 16:15:00 -0700210 if (access(path.c_str(), F_OK) < 0) {
Bart Van Assche59af6802022-01-24 21:08:57 +0000211 if (optional_) {
212 return true;
213 } else {
214 LOG(ERROR) << "No such cgroup attribute: " << path;
215 return false;
216 }
217 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800218 PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
219 return false;
220 }
221
222 return true;
223}
224
Rick Yiud4c53512021-11-21 15:57:36 +0800225SetCgroupAction::SetCgroupAction(const CgroupController& c, const std::string& p)
226 : controller_(c), path_(p) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800227 FdCacheHelper::Init(controller_.GetTasksFilePath(path_), fd_[ProfileAction::RCT_TASK]);
228 // uid and pid don't matter because IsAppDependentPath ensures the path doesn't use them
229 FdCacheHelper::Init(controller_.GetProcsFilePath(path_, 0, 0), fd_[ProfileAction::RCT_PROCESS]);
Rick Yiud4c53512021-11-21 15:57:36 +0800230}
231
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700232bool SetCgroupAction::AddTidToCgroup(int tid, int fd, const char* controller_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800233 if (tid <= 0) {
234 return true;
235 }
236
237 std::string value = std::to_string(tid);
238
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700239 if (TEMP_FAILURE_RETRY(write(fd, value.c_str(), value.length())) == value.length()) {
240 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800241 }
242
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700243 // If the thread is in the process of exiting, don't flag an error
244 if (errno == ESRCH) {
245 return true;
246 }
247
248 // ENOSPC is returned when cpuset cgroup that we are joining has no online cpus
249 if (errno == ENOSPC && !strcmp(controller_name, "cpuset")) {
250 // This is an abnormal case happening only in testing, so report it only once
251 static bool empty_cpuset_reported = false;
252
253 if (empty_cpuset_reported) {
254 return true;
255 }
256
257 LOG(ERROR) << "Failed to add task '" << value
258 << "' into cpuset because all cpus in that cpuset are offline";
259 empty_cpuset_reported = true;
260 } else {
261 PLOG(ERROR) << "AddTidToCgroup failed to write '" << value << "'; fd=" << fd;
262 }
263
264 return false;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800265}
266
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800267ProfileAction::CacheUseResult SetCgroupAction::UseCachedFd(ResourceCacheType cache_type,
268 int id) const {
269 std::lock_guard<std::mutex> lock(fd_mutex_);
270 if (FdCacheHelper::IsCached(fd_[cache_type])) {
271 // fd is cached, reuse it
272 if (!AddTidToCgroup(id, fd_[cache_type], controller()->name())) {
273 LOG(ERROR) << "Failed to add task into cgroup";
274 return ProfileAction::FAIL;
275 }
276 return ProfileAction::SUCCESS;
277 }
278
279 if (fd_[cache_type] == FdCacheHelper::FDS_INACCESSIBLE) {
280 // no permissions to access the file, ignore
281 return ProfileAction::SUCCESS;
282 }
283
284 if (cache_type == ResourceCacheType::RCT_TASK &&
285 fd_[cache_type] == FdCacheHelper::FDS_APP_DEPENDENT) {
286 // application-dependent path can't be used with tid
287 PLOG(ERROR) << "Application profile can't be applied to a thread";
288 return ProfileAction::FAIL;
289 }
290
291 return ProfileAction::UNUSED;
292}
293
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800294bool SetCgroupAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800295 CacheUseResult result = UseCachedFd(ProfileAction::RCT_PROCESS, pid);
296 if (result != ProfileAction::UNUSED) {
297 return result == ProfileAction::SUCCESS;
298 }
299
300 // fd was not cached or cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700301 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800302 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(procs_path.c_str(), O_WRONLY | O_CLOEXEC)));
303 if (tmp_fd < 0) {
Elliott Hughes08b4d322019-03-14 20:06:36 -0700304 PLOG(WARNING) << "Failed to open " << procs_path;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800305 return false;
306 }
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700307 if (!AddTidToCgroup(pid, tmp_fd, controller()->name())) {
Wei Wangd71d3012019-03-07 11:59:12 -0800308 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800309 return false;
310 }
311
312 return true;
313}
314
315bool SetCgroupAction::ExecuteForTask(int tid) const {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800316 CacheUseResult result = UseCachedFd(ProfileAction::RCT_TASK, tid);
317 if (result != ProfileAction::UNUSED) {
318 return result == ProfileAction::SUCCESS;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800319 }
320
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800321 // fd was not cached or cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700322 std::string tasks_path = controller()->GetTasksFilePath(path_);
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800323 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
324 if (tmp_fd < 0) {
Rick Yiud4c53512021-11-21 15:57:36 +0800325 PLOG(WARNING) << "Failed to open " << tasks_path;
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800326 return false;
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800327 }
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700328 if (!AddTidToCgroup(tid, tmp_fd, controller()->name())) {
Wei Wangd71d3012019-03-07 11:59:12 -0800329 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800330 return false;
331 }
332
333 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800334}
335
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800336void SetCgroupAction::EnableResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800337 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800338 // Return early to prevent unnecessary calls to controller_.Get{Tasks|Procs}FilePath() which
339 // include regex evaluations
340 if (fd_[cache_type] != FdCacheHelper::FDS_NOT_CACHED) {
341 return;
342 }
343 switch (cache_type) {
344 case (ProfileAction::RCT_TASK):
345 FdCacheHelper::Cache(controller_.GetTasksFilePath(path_), fd_[cache_type]);
346 break;
347 case (ProfileAction::RCT_PROCESS):
348 // uid and pid don't matter because IsAppDependentPath ensures the path doesn't use them
349 FdCacheHelper::Cache(controller_.GetProcsFilePath(path_, 0, 0), fd_[cache_type]);
350 break;
351 default:
352 LOG(ERROR) << "Invalid cache type is specified!";
353 break;
354 }
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800355}
356
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800357void SetCgroupAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800358 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800359 FdCacheHelper::Drop(fd_[cache_type]);
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800360}
361
Rick Yiu9221b1e2022-02-10 16:44:43 +0800362WriteFileAction::WriteFileAction(const std::string& task_path, const std::string& proc_path,
363 const std::string& value, bool logfailures)
364 : task_path_(task_path), proc_path_(proc_path), value_(value), logfailures_(logfailures) {
365 FdCacheHelper::Init(task_path_, fd_[ProfileAction::RCT_TASK]);
366 if (!proc_path_.empty()) FdCacheHelper::Init(proc_path_, fd_[ProfileAction::RCT_PROCESS]);
Rick Yiud4c53512021-11-21 15:57:36 +0800367}
Rick Yiubc1ad962020-10-26 20:32:52 +0800368
Rick Yiu9221b1e2022-02-10 16:44:43 +0800369bool WriteFileAction::WriteValueToFile(const std::string& value_, ResourceCacheType cache_type,
370 int uid, int pid, bool logfailures) const {
371 std::string value(value_);
372
373 value = StringReplace(value, "<uid>", std::to_string(uid), true);
374 value = StringReplace(value, "<pid>", std::to_string(pid), true);
375
376 CacheUseResult result = UseCachedFd(cache_type, value);
377
378 if (result != ProfileAction::UNUSED) {
379 return result == ProfileAction::SUCCESS;
380 }
381
382 std::string path;
383 if (cache_type == ProfileAction::RCT_TASK || proc_path_.empty()) {
384 path = task_path_;
385 } else {
386 path = proc_path_;
387 }
388
Rick Yiud4c53512021-11-21 15:57:36 +0800389 // Use WriteStringToFd instead of WriteStringToFile because the latter will open file with
390 // O_TRUNC which causes kernfs_mutex contention
391 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_WRONLY | O_CLOEXEC)));
Rick Yiubc1ad962020-10-26 20:32:52 +0800392
Rick Yiud4c53512021-11-21 15:57:36 +0800393 if (tmp_fd < 0) {
394 if (logfailures) PLOG(WARNING) << "Failed to open " << path;
395 return false;
396 }
397
398 if (!WriteStringToFd(value, tmp_fd)) {
399 if (logfailures) PLOG(ERROR) << "Failed to write '" << value << "' to " << path;
Rick Yiubc1ad962020-10-26 20:32:52 +0800400 return false;
401 }
402
403 return true;
404}
405
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800406ProfileAction::CacheUseResult WriteFileAction::UseCachedFd(ResourceCacheType cache_type,
407 const std::string& value) const {
Rick Yiud4c53512021-11-21 15:57:36 +0800408 std::lock_guard<std::mutex> lock(fd_mutex_);
Rick Yiu9221b1e2022-02-10 16:44:43 +0800409 if (FdCacheHelper::IsCached(fd_[cache_type])) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800410 // fd is cached, reuse it
Rick Yiu9221b1e2022-02-10 16:44:43 +0800411 bool ret = WriteStringToFd(value, fd_[cache_type]);
412
413 if (!ret && logfailures_) {
414 if (cache_type == ProfileAction::RCT_TASK || proc_path_.empty()) {
415 PLOG(ERROR) << "Failed to write '" << value << "' to " << task_path_;
416 } else {
417 PLOG(ERROR) << "Failed to write '" << value << "' to " << proc_path_;
418 }
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800419 }
Rick Yiu9221b1e2022-02-10 16:44:43 +0800420 return ret ? ProfileAction::SUCCESS : ProfileAction::FAIL;
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800421 }
422
Rick Yiu9221b1e2022-02-10 16:44:43 +0800423 if (fd_[cache_type] == FdCacheHelper::FDS_INACCESSIBLE) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800424 // no permissions to access the file, ignore
425 return ProfileAction::SUCCESS;
426 }
427
Rick Yiu9221b1e2022-02-10 16:44:43 +0800428 if (cache_type == ResourceCacheType::RCT_TASK &&
429 fd_[cache_type] == FdCacheHelper::FDS_APP_DEPENDENT) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800430 // application-dependent path can't be used with tid
431 PLOG(ERROR) << "Application profile can't be applied to a thread";
432 return ProfileAction::FAIL;
433 }
434 return ProfileAction::UNUSED;
435}
436
437bool WriteFileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800438 if (!proc_path_.empty()) {
439 return WriteValueToFile(value_, ProfileAction::RCT_PROCESS, uid, pid, logfailures_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800440 }
441
Rick Yiu9221b1e2022-02-10 16:44:43 +0800442 DIR* d;
443 struct dirent* de;
444 char proc_path[255];
445 int t_pid;
Rick Yiud4c53512021-11-21 15:57:36 +0800446
Rick Yiu9221b1e2022-02-10 16:44:43 +0800447 sprintf(proc_path, "/proc/%d/task", pid);
448 if (!(d = opendir(proc_path))) {
449 return false;
450 }
451
452 while ((de = readdir(d))) {
453 if (de->d_name[0] == '.') {
454 continue;
455 }
456
457 t_pid = atoi(de->d_name);
458
459 if (!t_pid) {
460 continue;
461 }
462
463 WriteValueToFile(value_, ProfileAction::RCT_TASK, uid, t_pid, logfailures_);
464 }
465
466 closedir(d);
467
468 return true;
Rick Yiud4c53512021-11-21 15:57:36 +0800469}
470
Rick Yiubc1ad962020-10-26 20:32:52 +0800471bool WriteFileAction::ExecuteForTask(int tid) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800472 return WriteValueToFile(value_, ProfileAction::RCT_TASK, getuid(), tid, logfailures_);
473}
Rick Yiubc1ad962020-10-26 20:32:52 +0800474
Rick Yiu9221b1e2022-02-10 16:44:43 +0800475void WriteFileAction::EnableResourceCaching(ResourceCacheType cache_type) {
476 std::lock_guard<std::mutex> lock(fd_mutex_);
477 if (fd_[cache_type] != FdCacheHelper::FDS_NOT_CACHED) {
478 return;
Rick Yiubc1ad962020-10-26 20:32:52 +0800479 }
Rick Yiu9221b1e2022-02-10 16:44:43 +0800480 switch (cache_type) {
481 case (ProfileAction::RCT_TASK):
482 FdCacheHelper::Cache(task_path_, fd_[cache_type]);
483 break;
484 case (ProfileAction::RCT_PROCESS):
485 if (!proc_path_.empty()) FdCacheHelper::Cache(proc_path_, fd_[cache_type]);
486 break;
487 default:
488 LOG(ERROR) << "Invalid cache type is specified!";
489 break;
490 }
Rick Yiubc1ad962020-10-26 20:32:52 +0800491}
492
Rick Yiu9221b1e2022-02-10 16:44:43 +0800493void WriteFileAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800494 std::lock_guard<std::mutex> lock(fd_mutex_);
Rick Yiu9221b1e2022-02-10 16:44:43 +0800495 FdCacheHelper::Drop(fd_[cache_type]);
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800496}
497
Rick Yiu0b211fa2019-09-16 19:07:17 +0800498bool ApplyProfileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
499 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800500 profile->ExecuteForProcess(uid, pid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800501 }
502 return true;
503}
504
505bool ApplyProfileAction::ExecuteForTask(int tid) const {
506 for (const auto& profile : profiles_) {
Wei Wang8722e4d2021-05-14 12:34:54 -0700507 profile->ExecuteForTask(tid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800508 }
509 return true;
510}
511
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800512void ApplyProfileAction::EnableResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800513 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800514 profile->EnableResourceCaching(cache_type);
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800515 }
516}
517
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800518void ApplyProfileAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800519 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800520 profile->DropResourceCaching(cache_type);
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800521 }
522}
523
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800524void TaskProfile::MoveTo(TaskProfile* profile) {
525 profile->elements_ = std::move(elements_);
526 profile->res_cached_ = res_cached_;
527}
528
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800529bool TaskProfile::ExecuteForProcess(uid_t uid, pid_t pid) const {
530 for (const auto& element : elements_) {
531 if (!element->ExecuteForProcess(uid, pid)) {
Bart Van Asschef096bd22022-01-24 19:59:13 +0000532 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800533 return false;
534 }
535 }
536 return true;
537}
538
539bool TaskProfile::ExecuteForTask(int tid) const {
540 if (tid == 0) {
541 tid = GetThreadId();
542 }
543 for (const auto& element : elements_) {
544 if (!element->ExecuteForTask(tid)) {
Bart Van Asschef096bd22022-01-24 19:59:13 +0000545 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800546 return false;
547 }
548 }
549 return true;
550}
551
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800552void TaskProfile::EnableResourceCaching(ProfileAction::ResourceCacheType cache_type) {
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800553 if (res_cached_) {
554 return;
555 }
556
557 for (auto& element : elements_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800558 element->EnableResourceCaching(cache_type);
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800559 }
560
561 res_cached_ = true;
562}
563
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800564void TaskProfile::DropResourceCaching(ProfileAction::ResourceCacheType cache_type) {
Riddle Hsua6abd822019-06-18 15:53:53 -0600565 if (!res_cached_) {
566 return;
567 }
568
569 for (auto& element : elements_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800570 element->DropResourceCaching(cache_type);
Riddle Hsua6abd822019-06-18 15:53:53 -0600571 }
572
573 res_cached_ = false;
574}
575
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800576void TaskProfiles::DropResourceCaching(ProfileAction::ResourceCacheType cache_type) const {
Riddle Hsua6abd822019-06-18 15:53:53 -0600577 for (auto& iter : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800578 iter.second->DropResourceCaching(cache_type);
Riddle Hsua6abd822019-06-18 15:53:53 -0600579 }
580}
581
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800582TaskProfiles& TaskProfiles::GetInstance() {
Peter Collingbournedba6d442019-03-20 21:09:46 -0700583 // Deliberately leak this object to avoid a race between destruction on
584 // process exit and concurrent access from another thread.
585 static auto* instance = new TaskProfiles;
586 return *instance;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800587}
588
589TaskProfiles::TaskProfiles() {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800590 // load system task profiles
591 if (!Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_FILE)) {
592 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_FILE << " for [" << getpid() << "] failed";
593 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800594
595 // load API-level specific system task profiles if available
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800596 unsigned int api_level = GetUintProperty<unsigned int>("ro.product.first_api_level", 0);
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800597 if (api_level > 0) {
598 std::string api_profiles_path =
599 android::base::StringPrintf(TEMPLATE_TASK_PROFILE_API_FILE, api_level);
600 if (!access(api_profiles_path.c_str(), F_OK) || errno != ENOENT) {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800601 if (!Load(CgroupMap::GetInstance(), api_profiles_path)) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800602 LOG(ERROR) << "Loading " << api_profiles_path << " for [" << getpid() << "] failed";
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800603 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800604 }
605 }
606
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800607 // load vendor task profiles if the file exists
608 if (!access(TASK_PROFILE_DB_VENDOR_FILE, F_OK) &&
609 !Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_VENDOR_FILE)) {
610 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_VENDOR_FILE << " for [" << getpid()
611 << "] failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800612 }
613}
614
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800615bool TaskProfiles::Load(const CgroupMap& cg_map, const std::string& file_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800616 std::string json_doc;
617
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800618 if (!android::base::ReadFileToString(file_name, &json_doc)) {
619 LOG(ERROR) << "Failed to read task profiles from " << file_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800620 return false;
621 }
622
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800623 Json::CharReaderBuilder builder;
624 std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800625 Json::Value root;
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800626 std::string errorMessage;
627 if (!reader->parse(&*json_doc.begin(), &*json_doc.end(), &root, &errorMessage)) {
628 LOG(ERROR) << "Failed to parse task profiles: " << errorMessage;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800629 return false;
630 }
631
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800632 const Json::Value& attr = root["Attributes"];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800633 for (Json::Value::ArrayIndex i = 0; i < attr.size(); ++i) {
634 std::string name = attr[i]["Name"].asString();
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800635 std::string controller_name = attr[i]["Controller"].asString();
636 std::string file_attr = attr[i]["File"].asString();
Bart Van Asschebc077ff2022-02-17 01:26:44 +0000637 std::string file_v2_attr = attr[i]["FileV2"].asString();
638
639 if (!file_v2_attr.empty() && file_attr.empty()) {
640 LOG(ERROR) << "Attribute " << name << " has FileV2 but no File property";
641 return false;
642 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800643
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700644 auto controller = cg_map.FindController(controller_name);
645 if (controller.HasValue()) {
646 auto iter = attributes_.find(name);
647 if (iter == attributes_.end()) {
Bart Van Asschebc077ff2022-02-17 01:26:44 +0000648 attributes_[name] =
649 std::make_unique<ProfileAttribute>(controller, file_attr, file_v2_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800650 } else {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700651 iter->second->Reset(controller, file_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800652 }
653 } else {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700654 LOG(WARNING) << "Controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800655 }
656 }
657
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800658 const Json::Value& profiles_val = root["Profiles"];
659 for (Json::Value::ArrayIndex i = 0; i < profiles_val.size(); ++i) {
660 const Json::Value& profile_val = profiles_val[i];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800661
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800662 std::string profile_name = profile_val["Name"].asString();
663 const Json::Value& actions = profile_val["Actions"];
Bart Van Asschef096bd22022-01-24 19:59:13 +0000664 auto profile = std::make_shared<TaskProfile>(profile_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800665
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800666 for (Json::Value::ArrayIndex act_idx = 0; act_idx < actions.size(); ++act_idx) {
667 const Json::Value& action_val = actions[act_idx];
668 std::string action_name = action_val["Name"].asString();
669 const Json::Value& params_val = action_val["Params"];
670 if (action_name == "JoinCgroup") {
671 std::string controller_name = params_val["Controller"].asString();
672 std::string path = params_val["Path"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800673
Yifan Hong53e0deb2019-03-22 17:01:08 -0700674 auto controller = cg_map.FindController(controller_name);
675 if (controller.HasValue()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800676 profile->Add(std::make_unique<SetCgroupAction>(controller, path));
677 } else {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800678 LOG(WARNING) << "JoinCgroup: controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800679 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800680 } else if (action_name == "SetTimerSlack") {
681 std::string slack_value = params_val["Slack"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800682 char* end;
683 unsigned long slack;
684
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800685 slack = strtoul(slack_value.c_str(), &end, 10);
686 if (end > slack_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800687 profile->Add(std::make_unique<SetTimerSlackAction>(slack));
688 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800689 LOG(WARNING) << "SetTimerSlack: invalid parameter: " << slack_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800690 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800691 } else if (action_name == "SetAttribute") {
692 std::string attr_name = params_val["Name"].asString();
693 std::string attr_value = params_val["Value"].asString();
Bart Van Assche59af6802022-01-24 21:08:57 +0000694 bool optional = strcmp(params_val["Optional"].asString().c_str(), "true") == 0;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800695
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800696 auto iter = attributes_.find(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800697 if (iter != attributes_.end()) {
Bart Van Assche59af6802022-01-24 21:08:57 +0000698 profile->Add(std::make_unique<SetAttributeAction>(iter->second.get(),
699 attr_value, optional));
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800700 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800701 LOG(WARNING) << "SetAttribute: unknown attribute: " << attr_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800702 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800703 } else if (action_name == "SetClamps") {
704 std::string boost_value = params_val["Boost"].asString();
705 std::string clamp_value = params_val["Clamp"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800706 char* end;
707 unsigned long boost;
708
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800709 boost = strtoul(boost_value.c_str(), &end, 10);
710 if (end > boost_value.c_str()) {
711 unsigned long clamp = strtoul(clamp_value.c_str(), &end, 10);
712 if (end > clamp_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800713 profile->Add(std::make_unique<SetClampsAction>(boost, clamp));
714 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800715 LOG(WARNING) << "SetClamps: invalid parameter " << clamp_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800716 }
717 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800718 LOG(WARNING) << "SetClamps: invalid parameter: " << boost_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800719 }
Rick Yiubc1ad962020-10-26 20:32:52 +0800720 } else if (action_name == "WriteFile") {
721 std::string attr_filepath = params_val["FilePath"].asString();
Rick Yiu9221b1e2022-02-10 16:44:43 +0800722 std::string attr_procfilepath = params_val["ProcFilePath"].asString();
Rick Yiubc1ad962020-10-26 20:32:52 +0800723 std::string attr_value = params_val["Value"].asString();
Rick Yiu9221b1e2022-02-10 16:44:43 +0800724 // FilePath and Value are mandatory
Rick Yiubc1ad962020-10-26 20:32:52 +0800725 if (!attr_filepath.empty() && !attr_value.empty()) {
Rick Yiu49fce952021-04-08 22:10:06 +0800726 std::string attr_logfailures = params_val["LogFailures"].asString();
727 bool logfailures = attr_logfailures.empty() || attr_logfailures == "true";
Rick Yiu9221b1e2022-02-10 16:44:43 +0800728 profile->Add(std::make_unique<WriteFileAction>(attr_filepath, attr_procfilepath,
729 attr_value, logfailures));
Rick Yiubc1ad962020-10-26 20:32:52 +0800730 } else if (attr_filepath.empty()) {
731 LOG(WARNING) << "WriteFile: invalid parameter: "
732 << "empty filepath";
733 } else if (attr_value.empty()) {
734 LOG(WARNING) << "WriteFile: invalid parameter: "
735 << "empty value";
736 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800737 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800738 LOG(WARNING) << "Unknown profile action: " << action_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800739 }
740 }
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800741 auto iter = profiles_.find(profile_name);
742 if (iter == profiles_.end()) {
743 profiles_[profile_name] = profile;
744 } else {
745 // Move the content rather that replace the profile because old profile might be
746 // referenced from an aggregate profile if vendor overrides task profiles
747 profile->MoveTo(iter->second.get());
748 profile.reset();
749 }
Rick Yiu0b211fa2019-09-16 19:07:17 +0800750 }
751
752 const Json::Value& aggregateprofiles_val = root["AggregateProfiles"];
753 for (Json::Value::ArrayIndex i = 0; i < aggregateprofiles_val.size(); ++i) {
754 const Json::Value& aggregateprofile_val = aggregateprofiles_val[i];
755
756 std::string aggregateprofile_name = aggregateprofile_val["Name"].asString();
757 const Json::Value& aggregateprofiles = aggregateprofile_val["Profiles"];
758 std::vector<std::shared_ptr<TaskProfile>> profiles;
759 bool ret = true;
760
761 for (Json::Value::ArrayIndex pf_idx = 0; pf_idx < aggregateprofiles.size(); ++pf_idx) {
762 std::string profile_name = aggregateprofiles[pf_idx].asString();
763
764 if (profile_name == aggregateprofile_name) {
765 LOG(WARNING) << "AggregateProfiles: recursive profile name: " << profile_name;
766 ret = false;
767 break;
768 } else if (profiles_.find(profile_name) == profiles_.end()) {
769 LOG(WARNING) << "AggregateProfiles: undefined profile name: " << profile_name;
770 ret = false;
771 break;
772 } else {
773 profiles.push_back(profiles_[profile_name]);
774 }
775 }
776 if (ret) {
Bart Van Asschef096bd22022-01-24 19:59:13 +0000777 auto profile = std::make_shared<TaskProfile>(aggregateprofile_name);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800778 profile->Add(std::make_unique<ApplyProfileAction>(profiles));
779 profiles_[aggregateprofile_name] = profile;
780 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800781 }
782
783 return true;
784}
785
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800786TaskProfile* TaskProfiles::GetProfile(const std::string& name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800787 auto iter = profiles_.find(name);
788
789 if (iter != profiles_.end()) {
790 return iter->second.get();
791 }
792 return nullptr;
793}
794
Bart Van Assche4c99e962022-02-03 19:50:16 +0000795const IProfileAttribute* TaskProfiles::GetAttribute(const std::string& name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800796 auto iter = attributes_.find(name);
797
798 if (iter != attributes_.end()) {
799 return iter->second.get();
800 }
801 return nullptr;
802}
Rick Yiu0b211fa2019-09-16 19:07:17 +0800803
804bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800805 const std::vector<std::string>& profiles, bool use_fd_cache) {
Rick Yiu0b211fa2019-09-16 19:07:17 +0800806 for (const auto& name : profiles) {
807 TaskProfile* profile = GetProfile(name);
808 if (profile != nullptr) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800809 if (use_fd_cache) {
810 profile->EnableResourceCaching(ProfileAction::RCT_PROCESS);
811 }
Rick Yiu0b211fa2019-09-16 19:07:17 +0800812 if (!profile->ExecuteForProcess(uid, pid)) {
813 PLOG(WARNING) << "Failed to apply " << name << " process profile";
814 }
815 } else {
816 PLOG(WARNING) << "Failed to find " << name << "process profile";
817 }
818 }
819 return true;
820}
821
822bool TaskProfiles::SetTaskProfiles(int tid, const std::vector<std::string>& profiles,
823 bool use_fd_cache) {
824 for (const auto& name : profiles) {
825 TaskProfile* profile = GetProfile(name);
826 if (profile != nullptr) {
827 if (use_fd_cache) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800828 profile->EnableResourceCaching(ProfileAction::RCT_TASK);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800829 }
830 if (!profile->ExecuteForTask(tid)) {
831 PLOG(WARNING) << "Failed to apply " << name << " task profile";
832 }
833 } else {
834 PLOG(WARNING) << "Failed to find " << name << "task profile";
835 }
836 }
837 return true;
838}