blob: a61700cec13b13fc8c4284910a1f49644383bd1a [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 Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800210 FdCacheHelper::Init(controller_.GetTasksFilePath(path_), fd_);
Rick Yiud4c53512021-11-21 15:57:36 +0800211}
212
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700213bool SetCgroupAction::AddTidToCgroup(int tid, int fd, const char* controller_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800214 if (tid <= 0) {
215 return true;
216 }
217
218 std::string value = std::to_string(tid);
219
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700220 if (TEMP_FAILURE_RETRY(write(fd, value.c_str(), value.length())) == value.length()) {
221 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800222 }
223
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700224 // If the thread is in the process of exiting, don't flag an error
225 if (errno == ESRCH) {
226 return true;
227 }
228
229 // ENOSPC is returned when cpuset cgroup that we are joining has no online cpus
230 if (errno == ENOSPC && !strcmp(controller_name, "cpuset")) {
231 // This is an abnormal case happening only in testing, so report it only once
232 static bool empty_cpuset_reported = false;
233
234 if (empty_cpuset_reported) {
235 return true;
236 }
237
238 LOG(ERROR) << "Failed to add task '" << value
239 << "' into cpuset because all cpus in that cpuset are offline";
240 empty_cpuset_reported = true;
241 } else {
242 PLOG(ERROR) << "AddTidToCgroup failed to write '" << value << "'; fd=" << fd;
243 }
244
245 return false;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800246}
247
248bool SetCgroupAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Yifan Hong53e0deb2019-03-22 17:01:08 -0700249 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800250 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(procs_path.c_str(), O_WRONLY | O_CLOEXEC)));
251 if (tmp_fd < 0) {
Elliott Hughes08b4d322019-03-14 20:06:36 -0700252 PLOG(WARNING) << "Failed to open " << procs_path;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800253 return false;
254 }
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700255 if (!AddTidToCgroup(pid, tmp_fd, controller()->name())) {
Wei Wangd71d3012019-03-07 11:59:12 -0800256 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800257 return false;
258 }
259
260 return true;
261}
262
263bool SetCgroupAction::ExecuteForTask(int tid) const {
mtk1603653f79e62019-05-31 19:05:22 +0800264 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800265 if (FdCacheHelper::IsCached(fd_)) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800266 // fd is cached, reuse it
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700267 if (!AddTidToCgroup(tid, fd_, controller()->name())) {
Wei Wangd71d3012019-03-07 11:59:12 -0800268 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800269 return false;
270 }
271 return true;
272 }
273
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800274 if (fd_ == FdCacheHelper::FDS_INACCESSIBLE) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800275 // no permissions to access the file, ignore
276 return true;
277 }
278
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800279 if (fd_ == FdCacheHelper::FDS_APP_DEPENDENT) {
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800280 // application-dependent path can't be used with tid
281 PLOG(ERROR) << "Application profile can't be applied to a thread";
282 return false;
283 }
284
285 // fd was not cached because cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700286 std::string tasks_path = controller()->GetTasksFilePath(path_);
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800287 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
288 if (tmp_fd < 0) {
Rick Yiud4c53512021-11-21 15:57:36 +0800289 PLOG(WARNING) << "Failed to open " << tasks_path;
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800290 return false;
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800291 }
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700292 if (!AddTidToCgroup(tid, tmp_fd, controller()->name())) {
Wei Wangd71d3012019-03-07 11:59:12 -0800293 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800294 return false;
295 }
296
297 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800298}
299
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800300void SetCgroupAction::EnableResourceCaching() {
301 std::lock_guard<std::mutex> lock(fd_mutex_);
302 FdCacheHelper::Cache(controller_.GetTasksFilePath(path_), fd_);
303}
304
305void SetCgroupAction::DropResourceCaching() {
306 std::lock_guard<std::mutex> lock(fd_mutex_);
307 FdCacheHelper::Drop(fd_);
308}
309
Rick Yiud4c53512021-11-21 15:57:36 +0800310WriteFileAction::WriteFileAction(const std::string& path, const std::string& value,
311 bool logfailures)
312 : path_(path), value_(value), logfailures_(logfailures) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800313 FdCacheHelper::Init(path_, fd_);
Rick Yiud4c53512021-11-21 15:57:36 +0800314}
Rick Yiubc1ad962020-10-26 20:32:52 +0800315
Rick Yiud4c53512021-11-21 15:57:36 +0800316bool WriteFileAction::WriteValueToFile(const std::string& value, const std::string& path,
317 bool logfailures) {
318 // Use WriteStringToFd instead of WriteStringToFile because the latter will open file with
319 // O_TRUNC which causes kernfs_mutex contention
320 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_WRONLY | O_CLOEXEC)));
Rick Yiubc1ad962020-10-26 20:32:52 +0800321
Rick Yiud4c53512021-11-21 15:57:36 +0800322 if (tmp_fd < 0) {
323 if (logfailures) PLOG(WARNING) << "Failed to open " << path;
324 return false;
325 }
326
327 if (!WriteStringToFd(value, tmp_fd)) {
328 if (logfailures) PLOG(ERROR) << "Failed to write '" << value << "' to " << path;
Rick Yiubc1ad962020-10-26 20:32:52 +0800329 return false;
330 }
331
332 return true;
333}
334
Rick Yiud4c53512021-11-21 15:57:36 +0800335bool WriteFileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
336 std::lock_guard<std::mutex> lock(fd_mutex_);
337 std::string value(value_);
338 std::string path(path_);
339
340 value = StringReplace(value, "<uid>", std::to_string(uid), true);
341 value = StringReplace(value, "<pid>", std::to_string(pid), true);
342 path = StringReplace(path, "<uid>", std::to_string(uid), true);
343 path = StringReplace(path, "<pid>", std::to_string(pid), true);
344
345 return WriteValueToFile(value, path, logfailures_);
346}
347
Rick Yiubc1ad962020-10-26 20:32:52 +0800348bool WriteFileAction::ExecuteForTask(int tid) const {
Rick Yiud4c53512021-11-21 15:57:36 +0800349 std::lock_guard<std::mutex> lock(fd_mutex_);
350 std::string value(value_);
Rick Yiubc1ad962020-10-26 20:32:52 +0800351 int uid = getuid();
352
Rick Yiubc1ad962020-10-26 20:32:52 +0800353 value = StringReplace(value, "<uid>", std::to_string(uid), true);
354 value = StringReplace(value, "<pid>", std::to_string(tid), true);
355
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800356 if (FdCacheHelper::IsCached(fd_)) {
Rick Yiud4c53512021-11-21 15:57:36 +0800357 // fd is cached, reuse it
358 if (!WriteStringToFd(value, fd_)) {
359 if (logfailures_) PLOG(ERROR) << "Failed to write '" << value << "' to " << path_;
360 return false;
361 }
362 return true;
363 }
364
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800365 if (fd_ == FdCacheHelper::FDS_INACCESSIBLE) {
Rick Yiud4c53512021-11-21 15:57:36 +0800366 // no permissions to access the file, ignore
367 return true;
368 }
369
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800370 if (fd_ == FdCacheHelper::FDS_APP_DEPENDENT) {
Rick Yiud4c53512021-11-21 15:57:36 +0800371 // application-dependent path can't be used with tid
372 PLOG(ERROR) << "Application profile can't be applied to a thread";
Rick Yiubc1ad962020-10-26 20:32:52 +0800373 return false;
374 }
375
Rick Yiud4c53512021-11-21 15:57:36 +0800376 return WriteValueToFile(value, path_, logfailures_);
Rick Yiubc1ad962020-10-26 20:32:52 +0800377}
378
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800379void WriteFileAction::EnableResourceCaching() {
380 std::lock_guard<std::mutex> lock(fd_mutex_);
381 FdCacheHelper::Cache(path_, fd_);
382}
383
384void WriteFileAction::DropResourceCaching() {
385 std::lock_guard<std::mutex> lock(fd_mutex_);
386 FdCacheHelper::Drop(fd_);
387}
388
Rick Yiu0b211fa2019-09-16 19:07:17 +0800389bool ApplyProfileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
390 for (const auto& profile : profiles_) {
Rick Yiu0b211fa2019-09-16 19:07:17 +0800391 if (!profile->ExecuteForProcess(uid, pid)) {
392 PLOG(WARNING) << "ExecuteForProcess failed for aggregate profile";
393 }
394 }
395 return true;
396}
397
398bool ApplyProfileAction::ExecuteForTask(int tid) const {
399 for (const auto& profile : profiles_) {
Wei Wang8722e4d2021-05-14 12:34:54 -0700400 profile->ExecuteForTask(tid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800401 }
402 return true;
403}
404
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800405void ApplyProfileAction::EnableResourceCaching() {
406 for (const auto& profile : profiles_) {
407 profile->EnableResourceCaching();
408 }
409}
410
411void ApplyProfileAction::DropResourceCaching() {
412 for (const auto& profile : profiles_) {
413 profile->DropResourceCaching();
414 }
415}
416
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800417void TaskProfile::MoveTo(TaskProfile* profile) {
418 profile->elements_ = std::move(elements_);
419 profile->res_cached_ = res_cached_;
420}
421
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800422bool TaskProfile::ExecuteForProcess(uid_t uid, pid_t pid) const {
423 for (const auto& element : elements_) {
424 if (!element->ExecuteForProcess(uid, pid)) {
425 return false;
426 }
427 }
428 return true;
429}
430
431bool TaskProfile::ExecuteForTask(int tid) const {
432 if (tid == 0) {
433 tid = GetThreadId();
434 }
435 for (const auto& element : elements_) {
436 if (!element->ExecuteForTask(tid)) {
437 return false;
438 }
439 }
440 return true;
441}
442
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800443void TaskProfile::EnableResourceCaching() {
444 if (res_cached_) {
445 return;
446 }
447
448 for (auto& element : elements_) {
449 element->EnableResourceCaching();
450 }
451
452 res_cached_ = true;
453}
454
Riddle Hsua6abd822019-06-18 15:53:53 -0600455void TaskProfile::DropResourceCaching() {
456 if (!res_cached_) {
457 return;
458 }
459
460 for (auto& element : elements_) {
461 element->DropResourceCaching();
462 }
463
464 res_cached_ = false;
465}
466
467void TaskProfiles::DropResourceCaching() const {
468 for (auto& iter : profiles_) {
469 iter.second->DropResourceCaching();
470 }
471}
472
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800473TaskProfiles& TaskProfiles::GetInstance() {
Peter Collingbournedba6d442019-03-20 21:09:46 -0700474 // Deliberately leak this object to avoid a race between destruction on
475 // process exit and concurrent access from another thread.
476 static auto* instance = new TaskProfiles;
477 return *instance;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800478}
479
480TaskProfiles::TaskProfiles() {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800481 // load system task profiles
482 if (!Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_FILE)) {
483 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_FILE << " for [" << getpid() << "] failed";
484 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800485
486 // load API-level specific system task profiles if available
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800487 unsigned int api_level = GetUintProperty<unsigned int>("ro.product.first_api_level", 0);
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800488 if (api_level > 0) {
489 std::string api_profiles_path =
490 android::base::StringPrintf(TEMPLATE_TASK_PROFILE_API_FILE, api_level);
491 if (!access(api_profiles_path.c_str(), F_OK) || errno != ENOENT) {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800492 if (!Load(CgroupMap::GetInstance(), api_profiles_path)) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800493 LOG(ERROR) << "Loading " << api_profiles_path << " for [" << getpid() << "] failed";
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800494 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800495 }
496 }
497
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800498 // load vendor task profiles if the file exists
499 if (!access(TASK_PROFILE_DB_VENDOR_FILE, F_OK) &&
500 !Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_VENDOR_FILE)) {
501 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_VENDOR_FILE << " for [" << getpid()
502 << "] failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800503 }
504}
505
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800506bool TaskProfiles::Load(const CgroupMap& cg_map, const std::string& file_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800507 std::string json_doc;
508
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800509 if (!android::base::ReadFileToString(file_name, &json_doc)) {
510 LOG(ERROR) << "Failed to read task profiles from " << file_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800511 return false;
512 }
513
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800514 Json::CharReaderBuilder builder;
515 std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800516 Json::Value root;
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800517 std::string errorMessage;
518 if (!reader->parse(&*json_doc.begin(), &*json_doc.end(), &root, &errorMessage)) {
519 LOG(ERROR) << "Failed to parse task profiles: " << errorMessage;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800520 return false;
521 }
522
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800523 const Json::Value& attr = root["Attributes"];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800524 for (Json::Value::ArrayIndex i = 0; i < attr.size(); ++i) {
525 std::string name = attr[i]["Name"].asString();
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800526 std::string controller_name = attr[i]["Controller"].asString();
527 std::string file_attr = attr[i]["File"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800528
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700529 auto controller = cg_map.FindController(controller_name);
530 if (controller.HasValue()) {
531 auto iter = attributes_.find(name);
532 if (iter == attributes_.end()) {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800533 attributes_[name] = std::make_unique<ProfileAttribute>(controller, file_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800534 } else {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700535 iter->second->Reset(controller, file_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800536 }
537 } else {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700538 LOG(WARNING) << "Controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800539 }
540 }
541
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800542 const Json::Value& profiles_val = root["Profiles"];
543 for (Json::Value::ArrayIndex i = 0; i < profiles_val.size(); ++i) {
544 const Json::Value& profile_val = profiles_val[i];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800545
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800546 std::string profile_name = profile_val["Name"].asString();
547 const Json::Value& actions = profile_val["Actions"];
Rick Yiu0b211fa2019-09-16 19:07:17 +0800548 auto profile = std::make_shared<TaskProfile>();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800549
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800550 for (Json::Value::ArrayIndex act_idx = 0; act_idx < actions.size(); ++act_idx) {
551 const Json::Value& action_val = actions[act_idx];
552 std::string action_name = action_val["Name"].asString();
553 const Json::Value& params_val = action_val["Params"];
554 if (action_name == "JoinCgroup") {
555 std::string controller_name = params_val["Controller"].asString();
556 std::string path = params_val["Path"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800557
Yifan Hong53e0deb2019-03-22 17:01:08 -0700558 auto controller = cg_map.FindController(controller_name);
559 if (controller.HasValue()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800560 profile->Add(std::make_unique<SetCgroupAction>(controller, path));
561 } else {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800562 LOG(WARNING) << "JoinCgroup: controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800563 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800564 } else if (action_name == "SetTimerSlack") {
565 std::string slack_value = params_val["Slack"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800566 char* end;
567 unsigned long slack;
568
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800569 slack = strtoul(slack_value.c_str(), &end, 10);
570 if (end > slack_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800571 profile->Add(std::make_unique<SetTimerSlackAction>(slack));
572 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800573 LOG(WARNING) << "SetTimerSlack: invalid parameter: " << slack_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800574 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800575 } else if (action_name == "SetAttribute") {
576 std::string attr_name = params_val["Name"].asString();
577 std::string attr_value = params_val["Value"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800578
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800579 auto iter = attributes_.find(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800580 if (iter != attributes_.end()) {
581 profile->Add(
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800582 std::make_unique<SetAttributeAction>(iter->second.get(), attr_value));
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800583 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800584 LOG(WARNING) << "SetAttribute: unknown attribute: " << attr_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800585 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800586 } else if (action_name == "SetClamps") {
587 std::string boost_value = params_val["Boost"].asString();
588 std::string clamp_value = params_val["Clamp"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800589 char* end;
590 unsigned long boost;
591
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800592 boost = strtoul(boost_value.c_str(), &end, 10);
593 if (end > boost_value.c_str()) {
594 unsigned long clamp = strtoul(clamp_value.c_str(), &end, 10);
595 if (end > clamp_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800596 profile->Add(std::make_unique<SetClampsAction>(boost, clamp));
597 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800598 LOG(WARNING) << "SetClamps: invalid parameter " << clamp_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800599 }
600 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800601 LOG(WARNING) << "SetClamps: invalid parameter: " << boost_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800602 }
Rick Yiubc1ad962020-10-26 20:32:52 +0800603 } else if (action_name == "WriteFile") {
604 std::string attr_filepath = params_val["FilePath"].asString();
605 std::string attr_value = params_val["Value"].asString();
606 if (!attr_filepath.empty() && !attr_value.empty()) {
Rick Yiu49fce952021-04-08 22:10:06 +0800607 std::string attr_logfailures = params_val["LogFailures"].asString();
608 bool logfailures = attr_logfailures.empty() || attr_logfailures == "true";
Rick Yiud76053a2021-01-25 12:44:45 +0800609 profile->Add(std::make_unique<WriteFileAction>(attr_filepath, attr_value,
Rick Yiu49fce952021-04-08 22:10:06 +0800610 logfailures));
Rick Yiubc1ad962020-10-26 20:32:52 +0800611 } else if (attr_filepath.empty()) {
612 LOG(WARNING) << "WriteFile: invalid parameter: "
613 << "empty filepath";
614 } else if (attr_value.empty()) {
615 LOG(WARNING) << "WriteFile: invalid parameter: "
616 << "empty value";
617 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800618 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800619 LOG(WARNING) << "Unknown profile action: " << action_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800620 }
621 }
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800622 auto iter = profiles_.find(profile_name);
623 if (iter == profiles_.end()) {
624 profiles_[profile_name] = profile;
625 } else {
626 // Move the content rather that replace the profile because old profile might be
627 // referenced from an aggregate profile if vendor overrides task profiles
628 profile->MoveTo(iter->second.get());
629 profile.reset();
630 }
Rick Yiu0b211fa2019-09-16 19:07:17 +0800631 }
632
633 const Json::Value& aggregateprofiles_val = root["AggregateProfiles"];
634 for (Json::Value::ArrayIndex i = 0; i < aggregateprofiles_val.size(); ++i) {
635 const Json::Value& aggregateprofile_val = aggregateprofiles_val[i];
636
637 std::string aggregateprofile_name = aggregateprofile_val["Name"].asString();
638 const Json::Value& aggregateprofiles = aggregateprofile_val["Profiles"];
639 std::vector<std::shared_ptr<TaskProfile>> profiles;
640 bool ret = true;
641
642 for (Json::Value::ArrayIndex pf_idx = 0; pf_idx < aggregateprofiles.size(); ++pf_idx) {
643 std::string profile_name = aggregateprofiles[pf_idx].asString();
644
645 if (profile_name == aggregateprofile_name) {
646 LOG(WARNING) << "AggregateProfiles: recursive profile name: " << profile_name;
647 ret = false;
648 break;
649 } else if (profiles_.find(profile_name) == profiles_.end()) {
650 LOG(WARNING) << "AggregateProfiles: undefined profile name: " << profile_name;
651 ret = false;
652 break;
653 } else {
654 profiles.push_back(profiles_[profile_name]);
655 }
656 }
657 if (ret) {
658 auto profile = std::make_shared<TaskProfile>();
659 profile->Add(std::make_unique<ApplyProfileAction>(profiles));
660 profiles_[aggregateprofile_name] = profile;
661 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800662 }
663
664 return true;
665}
666
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800667TaskProfile* TaskProfiles::GetProfile(const std::string& name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800668 auto iter = profiles_.find(name);
669
670 if (iter != profiles_.end()) {
671 return iter->second.get();
672 }
673 return nullptr;
674}
675
676const ProfileAttribute* TaskProfiles::GetAttribute(const std::string& name) const {
677 auto iter = attributes_.find(name);
678
679 if (iter != attributes_.end()) {
680 return iter->second.get();
681 }
682 return nullptr;
683}
Rick Yiu0b211fa2019-09-16 19:07:17 +0800684
685bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800686 const std::vector<std::string>& profiles) {
Rick Yiu0b211fa2019-09-16 19:07:17 +0800687 for (const auto& name : profiles) {
688 TaskProfile* profile = GetProfile(name);
689 if (profile != nullptr) {
Rick Yiu0b211fa2019-09-16 19:07:17 +0800690 if (!profile->ExecuteForProcess(uid, pid)) {
691 PLOG(WARNING) << "Failed to apply " << name << " process profile";
692 }
693 } else {
694 PLOG(WARNING) << "Failed to find " << name << "process profile";
695 }
696 }
697 return true;
698}
699
700bool TaskProfiles::SetTaskProfiles(int tid, const std::vector<std::string>& profiles,
701 bool use_fd_cache) {
702 for (const auto& name : profiles) {
703 TaskProfile* profile = GetProfile(name);
704 if (profile != nullptr) {
705 if (use_fd_cache) {
706 profile->EnableResourceCaching();
707 }
708 if (!profile->ExecuteForTask(tid)) {
709 PLOG(WARNING) << "Failed to apply " << name << " task profile";
710 }
711 } else {
712 PLOG(WARNING) << "Failed to find " << name << "task profile";
713 }
714 }
715 return true;
716}