blob: 74ba7f61ac8c39dc3ef47128d17d9edaba4fd421 [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
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700115void ProfileAttribute::Reset(const CgroupController& controller, const std::string& file_name) {
116 controller_ = controller;
117 file_name_ = file_name;
118}
119
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800120bool ProfileAttribute::GetPathForTask(int tid, std::string* path) const {
121 std::string subgroup;
Yifan Hong53e0deb2019-03-22 17:01:08 -0700122 if (!controller()->GetTaskGroup(tid, &subgroup)) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800123 return false;
124 }
125
126 if (path == nullptr) {
127 return true;
128 }
129
130 if (subgroup.empty()) {
Yifan Hong53e0deb2019-03-22 17:01:08 -0700131 *path = StringPrintf("%s/%s", controller()->path(), file_name_.c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800132 } else {
Yifan Hong53e0deb2019-03-22 17:01:08 -0700133 *path = StringPrintf("%s/%s/%s", controller()->path(), subgroup.c_str(),
134 file_name_.c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800135 }
136 return true;
137}
138
139bool SetClampsAction::ExecuteForProcess(uid_t, pid_t) const {
140 // TODO: add support when kernel supports util_clamp
141 LOG(WARNING) << "SetClampsAction::ExecuteForProcess is not supported";
142 return false;
143}
144
145bool SetClampsAction::ExecuteForTask(int) const {
146 // TODO: add support when kernel supports util_clamp
147 LOG(WARNING) << "SetClampsAction::ExecuteForTask is not supported";
148 return false;
149}
150
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -0800151// To avoid issues in sdk_mac build
152#if defined(__ANDROID__)
153
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800154bool SetTimerSlackAction::IsTimerSlackSupported(int tid) {
155 auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
156
157 return (access(file.c_str(), W_OK) == 0);
158}
159
160bool SetTimerSlackAction::ExecuteForTask(int tid) const {
161 static bool sys_supports_timerslack = IsTimerSlackSupported(tid);
162
163 // v4.6+ kernels support the /proc/<tid>/timerslack_ns interface.
164 // TODO: once we've backported this, log if the open(2) fails.
165 if (sys_supports_timerslack) {
166 auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
167 if (!WriteStringToFile(std::to_string(slack_), file)) {
Suren Baghdasaryan2bc52282019-02-12 17:30:26 -0800168 if (errno == ENOENT) {
169 // This happens when process is already dead
170 return true;
171 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800172 PLOG(ERROR) << "set_timerslack_ns write failed";
173 }
174 }
175
176 // TODO: Remove when /proc/<tid>/timerslack_ns interface is backported.
177 if (tid == 0 || tid == GetThreadId()) {
178 if (prctl(PR_SET_TIMERSLACK, slack_) == -1) {
179 PLOG(ERROR) << "set_timerslack_ns prctl failed";
180 }
181 }
182
183 return true;
184}
185
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -0800186#endif
187
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800188bool SetAttributeAction::ExecuteForProcess(uid_t, pid_t pid) const {
189 return ExecuteForTask(pid);
190}
191
192bool SetAttributeAction::ExecuteForTask(int tid) const {
193 std::string path;
194
195 if (!attribute_->GetPathForTask(tid, &path)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800196 LOG(ERROR) << "Failed to find cgroup for tid " << tid;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800197 return false;
198 }
199
200 if (!WriteStringToFile(value_, path)) {
201 PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
202 return false;
203 }
204
205 return true;
206}
207
Rick Yiud4c53512021-11-21 15:57:36 +0800208SetCgroupAction::SetCgroupAction(const CgroupController& c, const std::string& p)
209 : controller_(c), path_(p) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800210 FdCacheHelper::Init(controller_.GetTasksFilePath(path_), fd_[ProfileAction::RCT_TASK]);
211 // uid and pid don't matter because IsAppDependentPath ensures the path doesn't use them
212 FdCacheHelper::Init(controller_.GetProcsFilePath(path_, 0, 0), fd_[ProfileAction::RCT_PROCESS]);
Rick Yiud4c53512021-11-21 15:57:36 +0800213}
214
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700215bool SetCgroupAction::AddTidToCgroup(int tid, int fd, const char* controller_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800216 if (tid <= 0) {
217 return true;
218 }
219
220 std::string value = std::to_string(tid);
221
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700222 if (TEMP_FAILURE_RETRY(write(fd, value.c_str(), value.length())) == value.length()) {
223 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800224 }
225
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700226 // If the thread is in the process of exiting, don't flag an error
227 if (errno == ESRCH) {
228 return true;
229 }
230
231 // ENOSPC is returned when cpuset cgroup that we are joining has no online cpus
232 if (errno == ENOSPC && !strcmp(controller_name, "cpuset")) {
233 // This is an abnormal case happening only in testing, so report it only once
234 static bool empty_cpuset_reported = false;
235
236 if (empty_cpuset_reported) {
237 return true;
238 }
239
240 LOG(ERROR) << "Failed to add task '" << value
241 << "' into cpuset because all cpus in that cpuset are offline";
242 empty_cpuset_reported = true;
243 } else {
244 PLOG(ERROR) << "AddTidToCgroup failed to write '" << value << "'; fd=" << fd;
245 }
246
247 return false;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800248}
249
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800250ProfileAction::CacheUseResult SetCgroupAction::UseCachedFd(ResourceCacheType cache_type,
251 int id) const {
252 std::lock_guard<std::mutex> lock(fd_mutex_);
253 if (FdCacheHelper::IsCached(fd_[cache_type])) {
254 // fd is cached, reuse it
255 if (!AddTidToCgroup(id, fd_[cache_type], controller()->name())) {
256 LOG(ERROR) << "Failed to add task into cgroup";
257 return ProfileAction::FAIL;
258 }
259 return ProfileAction::SUCCESS;
260 }
261
262 if (fd_[cache_type] == FdCacheHelper::FDS_INACCESSIBLE) {
263 // no permissions to access the file, ignore
264 return ProfileAction::SUCCESS;
265 }
266
267 if (cache_type == ResourceCacheType::RCT_TASK &&
268 fd_[cache_type] == FdCacheHelper::FDS_APP_DEPENDENT) {
269 // application-dependent path can't be used with tid
270 PLOG(ERROR) << "Application profile can't be applied to a thread";
271 return ProfileAction::FAIL;
272 }
273
274 return ProfileAction::UNUSED;
275}
276
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800277bool SetCgroupAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800278 CacheUseResult result = UseCachedFd(ProfileAction::RCT_PROCESS, pid);
279 if (result != ProfileAction::UNUSED) {
280 return result == ProfileAction::SUCCESS;
281 }
282
283 // fd was not cached or cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700284 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800285 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(procs_path.c_str(), O_WRONLY | O_CLOEXEC)));
286 if (tmp_fd < 0) {
Elliott Hughes08b4d322019-03-14 20:06:36 -0700287 PLOG(WARNING) << "Failed to open " << procs_path;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800288 return false;
289 }
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700290 if (!AddTidToCgroup(pid, tmp_fd, controller()->name())) {
Wei Wangd71d3012019-03-07 11:59:12 -0800291 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800292 return false;
293 }
294
295 return true;
296}
297
298bool SetCgroupAction::ExecuteForTask(int tid) const {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800299 CacheUseResult result = UseCachedFd(ProfileAction::RCT_TASK, tid);
300 if (result != ProfileAction::UNUSED) {
301 return result == ProfileAction::SUCCESS;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800302 }
303
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800304 // fd was not cached or cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700305 std::string tasks_path = controller()->GetTasksFilePath(path_);
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800306 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
307 if (tmp_fd < 0) {
Rick Yiud4c53512021-11-21 15:57:36 +0800308 PLOG(WARNING) << "Failed to open " << tasks_path;
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800309 return false;
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800310 }
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700311 if (!AddTidToCgroup(tid, tmp_fd, controller()->name())) {
Wei Wangd71d3012019-03-07 11:59:12 -0800312 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800313 return false;
314 }
315
316 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800317}
318
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800319void SetCgroupAction::EnableResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800320 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800321 // Return early to prevent unnecessary calls to controller_.Get{Tasks|Procs}FilePath() which
322 // include regex evaluations
323 if (fd_[cache_type] != FdCacheHelper::FDS_NOT_CACHED) {
324 return;
325 }
326 switch (cache_type) {
327 case (ProfileAction::RCT_TASK):
328 FdCacheHelper::Cache(controller_.GetTasksFilePath(path_), fd_[cache_type]);
329 break;
330 case (ProfileAction::RCT_PROCESS):
331 // uid and pid don't matter because IsAppDependentPath ensures the path doesn't use them
332 FdCacheHelper::Cache(controller_.GetProcsFilePath(path_, 0, 0), fd_[cache_type]);
333 break;
334 default:
335 LOG(ERROR) << "Invalid cache type is specified!";
336 break;
337 }
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800338}
339
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800340void SetCgroupAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800341 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800342 FdCacheHelper::Drop(fd_[cache_type]);
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800343}
344
Rick Yiud4c53512021-11-21 15:57:36 +0800345WriteFileAction::WriteFileAction(const std::string& path, const std::string& value,
346 bool logfailures)
347 : path_(path), value_(value), logfailures_(logfailures) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800348 FdCacheHelper::Init(path_, fd_);
Rick Yiud4c53512021-11-21 15:57:36 +0800349}
Rick Yiubc1ad962020-10-26 20:32:52 +0800350
Rick Yiud4c53512021-11-21 15:57:36 +0800351bool WriteFileAction::WriteValueToFile(const std::string& value, const std::string& path,
352 bool logfailures) {
353 // Use WriteStringToFd instead of WriteStringToFile because the latter will open file with
354 // O_TRUNC which causes kernfs_mutex contention
355 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_WRONLY | O_CLOEXEC)));
Rick Yiubc1ad962020-10-26 20:32:52 +0800356
Rick Yiud4c53512021-11-21 15:57:36 +0800357 if (tmp_fd < 0) {
358 if (logfailures) PLOG(WARNING) << "Failed to open " << path;
359 return false;
360 }
361
362 if (!WriteStringToFd(value, tmp_fd)) {
363 if (logfailures) PLOG(ERROR) << "Failed to write '" << value << "' to " << path;
Rick Yiubc1ad962020-10-26 20:32:52 +0800364 return false;
365 }
366
367 return true;
368}
369
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800370ProfileAction::CacheUseResult WriteFileAction::UseCachedFd(ResourceCacheType cache_type,
371 const std::string& value) const {
Rick Yiud4c53512021-11-21 15:57:36 +0800372 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800373 if (FdCacheHelper::IsCached(fd_)) {
374 // fd is cached, reuse it
375 if (!WriteStringToFd(value, fd_)) {
376 if (logfailures_) PLOG(ERROR) << "Failed to write '" << value << "' to " << path_;
377 return ProfileAction::FAIL;
378 }
379 return ProfileAction::SUCCESS;
380 }
381
382 if (fd_ == FdCacheHelper::FDS_INACCESSIBLE) {
383 // no permissions to access the file, ignore
384 return ProfileAction::SUCCESS;
385 }
386
387 if (cache_type == ResourceCacheType::RCT_TASK && fd_ == FdCacheHelper::FDS_APP_DEPENDENT) {
388 // application-dependent path can't be used with tid
389 PLOG(ERROR) << "Application profile can't be applied to a thread";
390 return ProfileAction::FAIL;
391 }
392 return ProfileAction::UNUSED;
393}
394
395bool WriteFileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Rick Yiud4c53512021-11-21 15:57:36 +0800396 std::string value(value_);
Rick Yiud4c53512021-11-21 15:57:36 +0800397
398 value = StringReplace(value, "<uid>", std::to_string(uid), true);
399 value = StringReplace(value, "<pid>", std::to_string(pid), true);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800400
401 CacheUseResult result = UseCachedFd(ProfileAction::RCT_PROCESS, value);
402 if (result != ProfileAction::UNUSED) {
403 return result == ProfileAction::SUCCESS;
404 }
405
406 std::string path(path_);
Rick Yiud4c53512021-11-21 15:57:36 +0800407 path = StringReplace(path, "<uid>", std::to_string(uid), true);
408 path = StringReplace(path, "<pid>", std::to_string(pid), true);
409
410 return WriteValueToFile(value, path, logfailures_);
411}
412
Rick Yiubc1ad962020-10-26 20:32:52 +0800413bool WriteFileAction::ExecuteForTask(int tid) const {
Rick Yiud4c53512021-11-21 15:57:36 +0800414 std::string value(value_);
Rick Yiubc1ad962020-10-26 20:32:52 +0800415 int uid = getuid();
416
Rick Yiubc1ad962020-10-26 20:32:52 +0800417 value = StringReplace(value, "<uid>", std::to_string(uid), true);
418 value = StringReplace(value, "<pid>", std::to_string(tid), true);
419
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800420 CacheUseResult result = UseCachedFd(ProfileAction::RCT_TASK, value);
421 if (result != ProfileAction::UNUSED) {
422 return result == ProfileAction::SUCCESS;
Rick Yiubc1ad962020-10-26 20:32:52 +0800423 }
424
Rick Yiud4c53512021-11-21 15:57:36 +0800425 return WriteValueToFile(value, path_, logfailures_);
Rick Yiubc1ad962020-10-26 20:32:52 +0800426}
427
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800428void WriteFileAction::EnableResourceCaching(ResourceCacheType) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800429 std::lock_guard<std::mutex> lock(fd_mutex_);
430 FdCacheHelper::Cache(path_, fd_);
431}
432
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800433void WriteFileAction::DropResourceCaching(ResourceCacheType) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800434 std::lock_guard<std::mutex> lock(fd_mutex_);
435 FdCacheHelper::Drop(fd_);
436}
437
Rick Yiu0b211fa2019-09-16 19:07:17 +0800438bool ApplyProfileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
439 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800440 profile->ExecuteForProcess(uid, pid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800441 }
442 return true;
443}
444
445bool ApplyProfileAction::ExecuteForTask(int tid) const {
446 for (const auto& profile : profiles_) {
Wei Wang8722e4d2021-05-14 12:34:54 -0700447 profile->ExecuteForTask(tid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800448 }
449 return true;
450}
451
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800452void ApplyProfileAction::EnableResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800453 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800454 profile->EnableResourceCaching(cache_type);
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800455 }
456}
457
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800458void ApplyProfileAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800459 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800460 profile->DropResourceCaching(cache_type);
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800461 }
462}
463
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800464void TaskProfile::MoveTo(TaskProfile* profile) {
465 profile->elements_ = std::move(elements_);
466 profile->res_cached_ = res_cached_;
467}
468
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800469bool TaskProfile::ExecuteForProcess(uid_t uid, pid_t pid) const {
470 for (const auto& element : elements_) {
471 if (!element->ExecuteForProcess(uid, pid)) {
472 return false;
473 }
474 }
475 return true;
476}
477
478bool TaskProfile::ExecuteForTask(int tid) const {
479 if (tid == 0) {
480 tid = GetThreadId();
481 }
482 for (const auto& element : elements_) {
483 if (!element->ExecuteForTask(tid)) {
484 return false;
485 }
486 }
487 return true;
488}
489
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800490void TaskProfile::EnableResourceCaching(ProfileAction::ResourceCacheType cache_type) {
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800491 if (res_cached_) {
492 return;
493 }
494
495 for (auto& element : elements_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800496 element->EnableResourceCaching(cache_type);
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800497 }
498
499 res_cached_ = true;
500}
501
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800502void TaskProfile::DropResourceCaching(ProfileAction::ResourceCacheType cache_type) {
Riddle Hsua6abd822019-06-18 15:53:53 -0600503 if (!res_cached_) {
504 return;
505 }
506
507 for (auto& element : elements_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800508 element->DropResourceCaching(cache_type);
Riddle Hsua6abd822019-06-18 15:53:53 -0600509 }
510
511 res_cached_ = false;
512}
513
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800514void TaskProfiles::DropResourceCaching(ProfileAction::ResourceCacheType cache_type) const {
Riddle Hsua6abd822019-06-18 15:53:53 -0600515 for (auto& iter : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800516 iter.second->DropResourceCaching(cache_type);
Riddle Hsua6abd822019-06-18 15:53:53 -0600517 }
518}
519
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800520TaskProfiles& TaskProfiles::GetInstance() {
Peter Collingbournedba6d442019-03-20 21:09:46 -0700521 // Deliberately leak this object to avoid a race between destruction on
522 // process exit and concurrent access from another thread.
523 static auto* instance = new TaskProfiles;
524 return *instance;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800525}
526
527TaskProfiles::TaskProfiles() {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800528 // load system task profiles
529 if (!Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_FILE)) {
530 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_FILE << " for [" << getpid() << "] failed";
531 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800532
533 // load API-level specific system task profiles if available
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800534 unsigned int api_level = GetUintProperty<unsigned int>("ro.product.first_api_level", 0);
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800535 if (api_level > 0) {
536 std::string api_profiles_path =
537 android::base::StringPrintf(TEMPLATE_TASK_PROFILE_API_FILE, api_level);
538 if (!access(api_profiles_path.c_str(), F_OK) || errno != ENOENT) {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800539 if (!Load(CgroupMap::GetInstance(), api_profiles_path)) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800540 LOG(ERROR) << "Loading " << api_profiles_path << " for [" << getpid() << "] failed";
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800541 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800542 }
543 }
544
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800545 // load vendor task profiles if the file exists
546 if (!access(TASK_PROFILE_DB_VENDOR_FILE, F_OK) &&
547 !Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_VENDOR_FILE)) {
548 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_VENDOR_FILE << " for [" << getpid()
549 << "] failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800550 }
551}
552
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800553bool TaskProfiles::Load(const CgroupMap& cg_map, const std::string& file_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800554 std::string json_doc;
555
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800556 if (!android::base::ReadFileToString(file_name, &json_doc)) {
557 LOG(ERROR) << "Failed to read task profiles from " << file_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800558 return false;
559 }
560
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800561 Json::CharReaderBuilder builder;
562 std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800563 Json::Value root;
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800564 std::string errorMessage;
565 if (!reader->parse(&*json_doc.begin(), &*json_doc.end(), &root, &errorMessage)) {
566 LOG(ERROR) << "Failed to parse task profiles: " << errorMessage;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800567 return false;
568 }
569
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800570 const Json::Value& attr = root["Attributes"];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800571 for (Json::Value::ArrayIndex i = 0; i < attr.size(); ++i) {
572 std::string name = attr[i]["Name"].asString();
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800573 std::string controller_name = attr[i]["Controller"].asString();
574 std::string file_attr = attr[i]["File"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800575
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700576 auto controller = cg_map.FindController(controller_name);
577 if (controller.HasValue()) {
578 auto iter = attributes_.find(name);
579 if (iter == attributes_.end()) {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800580 attributes_[name] = std::make_unique<ProfileAttribute>(controller, file_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800581 } else {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700582 iter->second->Reset(controller, file_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800583 }
584 } else {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700585 LOG(WARNING) << "Controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800586 }
587 }
588
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800589 const Json::Value& profiles_val = root["Profiles"];
590 for (Json::Value::ArrayIndex i = 0; i < profiles_val.size(); ++i) {
591 const Json::Value& profile_val = profiles_val[i];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800592
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800593 std::string profile_name = profile_val["Name"].asString();
594 const Json::Value& actions = profile_val["Actions"];
Rick Yiu0b211fa2019-09-16 19:07:17 +0800595 auto profile = std::make_shared<TaskProfile>();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800596
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800597 for (Json::Value::ArrayIndex act_idx = 0; act_idx < actions.size(); ++act_idx) {
598 const Json::Value& action_val = actions[act_idx];
599 std::string action_name = action_val["Name"].asString();
600 const Json::Value& params_val = action_val["Params"];
601 if (action_name == "JoinCgroup") {
602 std::string controller_name = params_val["Controller"].asString();
603 std::string path = params_val["Path"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800604
Yifan Hong53e0deb2019-03-22 17:01:08 -0700605 auto controller = cg_map.FindController(controller_name);
606 if (controller.HasValue()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800607 profile->Add(std::make_unique<SetCgroupAction>(controller, path));
608 } else {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800609 LOG(WARNING) << "JoinCgroup: controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800610 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800611 } else if (action_name == "SetTimerSlack") {
612 std::string slack_value = params_val["Slack"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800613 char* end;
614 unsigned long slack;
615
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800616 slack = strtoul(slack_value.c_str(), &end, 10);
617 if (end > slack_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800618 profile->Add(std::make_unique<SetTimerSlackAction>(slack));
619 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800620 LOG(WARNING) << "SetTimerSlack: invalid parameter: " << slack_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800621 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800622 } else if (action_name == "SetAttribute") {
623 std::string attr_name = params_val["Name"].asString();
624 std::string attr_value = params_val["Value"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800625
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800626 auto iter = attributes_.find(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800627 if (iter != attributes_.end()) {
628 profile->Add(
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800629 std::make_unique<SetAttributeAction>(iter->second.get(), attr_value));
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800630 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800631 LOG(WARNING) << "SetAttribute: unknown attribute: " << attr_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800632 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800633 } else if (action_name == "SetClamps") {
634 std::string boost_value = params_val["Boost"].asString();
635 std::string clamp_value = params_val["Clamp"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800636 char* end;
637 unsigned long boost;
638
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800639 boost = strtoul(boost_value.c_str(), &end, 10);
640 if (end > boost_value.c_str()) {
641 unsigned long clamp = strtoul(clamp_value.c_str(), &end, 10);
642 if (end > clamp_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800643 profile->Add(std::make_unique<SetClampsAction>(boost, clamp));
644 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800645 LOG(WARNING) << "SetClamps: invalid parameter " << clamp_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800646 }
647 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800648 LOG(WARNING) << "SetClamps: invalid parameter: " << boost_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800649 }
Rick Yiubc1ad962020-10-26 20:32:52 +0800650 } else if (action_name == "WriteFile") {
651 std::string attr_filepath = params_val["FilePath"].asString();
652 std::string attr_value = params_val["Value"].asString();
653 if (!attr_filepath.empty() && !attr_value.empty()) {
Rick Yiu49fce952021-04-08 22:10:06 +0800654 std::string attr_logfailures = params_val["LogFailures"].asString();
655 bool logfailures = attr_logfailures.empty() || attr_logfailures == "true";
Rick Yiud76053a2021-01-25 12:44:45 +0800656 profile->Add(std::make_unique<WriteFileAction>(attr_filepath, attr_value,
Rick Yiu49fce952021-04-08 22:10:06 +0800657 logfailures));
Rick Yiubc1ad962020-10-26 20:32:52 +0800658 } else if (attr_filepath.empty()) {
659 LOG(WARNING) << "WriteFile: invalid parameter: "
660 << "empty filepath";
661 } else if (attr_value.empty()) {
662 LOG(WARNING) << "WriteFile: invalid parameter: "
663 << "empty value";
664 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800665 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800666 LOG(WARNING) << "Unknown profile action: " << action_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800667 }
668 }
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800669 auto iter = profiles_.find(profile_name);
670 if (iter == profiles_.end()) {
671 profiles_[profile_name] = profile;
672 } else {
673 // Move the content rather that replace the profile because old profile might be
674 // referenced from an aggregate profile if vendor overrides task profiles
675 profile->MoveTo(iter->second.get());
676 profile.reset();
677 }
Rick Yiu0b211fa2019-09-16 19:07:17 +0800678 }
679
680 const Json::Value& aggregateprofiles_val = root["AggregateProfiles"];
681 for (Json::Value::ArrayIndex i = 0; i < aggregateprofiles_val.size(); ++i) {
682 const Json::Value& aggregateprofile_val = aggregateprofiles_val[i];
683
684 std::string aggregateprofile_name = aggregateprofile_val["Name"].asString();
685 const Json::Value& aggregateprofiles = aggregateprofile_val["Profiles"];
686 std::vector<std::shared_ptr<TaskProfile>> profiles;
687 bool ret = true;
688
689 for (Json::Value::ArrayIndex pf_idx = 0; pf_idx < aggregateprofiles.size(); ++pf_idx) {
690 std::string profile_name = aggregateprofiles[pf_idx].asString();
691
692 if (profile_name == aggregateprofile_name) {
693 LOG(WARNING) << "AggregateProfiles: recursive profile name: " << profile_name;
694 ret = false;
695 break;
696 } else if (profiles_.find(profile_name) == profiles_.end()) {
697 LOG(WARNING) << "AggregateProfiles: undefined profile name: " << profile_name;
698 ret = false;
699 break;
700 } else {
701 profiles.push_back(profiles_[profile_name]);
702 }
703 }
704 if (ret) {
705 auto profile = std::make_shared<TaskProfile>();
706 profile->Add(std::make_unique<ApplyProfileAction>(profiles));
707 profiles_[aggregateprofile_name] = profile;
708 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800709 }
710
711 return true;
712}
713
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800714TaskProfile* TaskProfiles::GetProfile(const std::string& name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800715 auto iter = profiles_.find(name);
716
717 if (iter != profiles_.end()) {
718 return iter->second.get();
719 }
720 return nullptr;
721}
722
723const ProfileAttribute* TaskProfiles::GetAttribute(const std::string& name) const {
724 auto iter = attributes_.find(name);
725
726 if (iter != attributes_.end()) {
727 return iter->second.get();
728 }
729 return nullptr;
730}
Rick Yiu0b211fa2019-09-16 19:07:17 +0800731
732bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800733 const std::vector<std::string>& profiles, bool use_fd_cache) {
Rick Yiu0b211fa2019-09-16 19:07:17 +0800734 for (const auto& name : profiles) {
735 TaskProfile* profile = GetProfile(name);
736 if (profile != nullptr) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800737 if (use_fd_cache) {
738 profile->EnableResourceCaching(ProfileAction::RCT_PROCESS);
739 }
Rick Yiu0b211fa2019-09-16 19:07:17 +0800740 if (!profile->ExecuteForProcess(uid, pid)) {
741 PLOG(WARNING) << "Failed to apply " << name << " process profile";
742 }
743 } else {
744 PLOG(WARNING) << "Failed to find " << name << "process profile";
745 }
746 }
747 return true;
748}
749
750bool TaskProfiles::SetTaskProfiles(int tid, const std::vector<std::string>& profiles,
751 bool use_fd_cache) {
752 for (const auto& name : profiles) {
753 TaskProfile* profile = GetProfile(name);
754 if (profile != nullptr) {
755 if (use_fd_cache) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800756 profile->EnableResourceCaching(ProfileAction::RCT_TASK);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800757 }
758 if (!profile->ExecuteForTask(tid)) {
759 PLOG(WARNING) << "Failed to apply " << name << " task profile";
760 }
761 } else {
762 PLOG(WARNING) << "Failed to find " << name << "task profile";
763 }
764 }
765 return true;
766}