blob: 3834f9194beba4a344aca8aaf4473fb2b218ae9a [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 Baghdasaryan81b9f0b2020-07-01 12:34:17 -070054void ProfileAttribute::Reset(const CgroupController& controller, const std::string& file_name) {
55 controller_ = controller;
56 file_name_ = file_name;
57}
58
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080059bool ProfileAttribute::GetPathForTask(int tid, std::string* path) const {
60 std::string subgroup;
Yifan Hong53e0deb2019-03-22 17:01:08 -070061 if (!controller()->GetTaskGroup(tid, &subgroup)) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080062 return false;
63 }
64
65 if (path == nullptr) {
66 return true;
67 }
68
69 if (subgroup.empty()) {
Yifan Hong53e0deb2019-03-22 17:01:08 -070070 *path = StringPrintf("%s/%s", controller()->path(), file_name_.c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080071 } else {
Yifan Hong53e0deb2019-03-22 17:01:08 -070072 *path = StringPrintf("%s/%s/%s", controller()->path(), subgroup.c_str(),
73 file_name_.c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080074 }
75 return true;
76}
77
78bool SetClampsAction::ExecuteForProcess(uid_t, pid_t) const {
79 // TODO: add support when kernel supports util_clamp
80 LOG(WARNING) << "SetClampsAction::ExecuteForProcess is not supported";
81 return false;
82}
83
84bool SetClampsAction::ExecuteForTask(int) const {
85 // TODO: add support when kernel supports util_clamp
86 LOG(WARNING) << "SetClampsAction::ExecuteForTask is not supported";
87 return false;
88}
89
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -080090// To avoid issues in sdk_mac build
91#if defined(__ANDROID__)
92
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080093bool SetTimerSlackAction::IsTimerSlackSupported(int tid) {
94 auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
95
96 return (access(file.c_str(), W_OK) == 0);
97}
98
99bool SetTimerSlackAction::ExecuteForTask(int tid) const {
100 static bool sys_supports_timerslack = IsTimerSlackSupported(tid);
101
102 // v4.6+ kernels support the /proc/<tid>/timerslack_ns interface.
103 // TODO: once we've backported this, log if the open(2) fails.
104 if (sys_supports_timerslack) {
105 auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
106 if (!WriteStringToFile(std::to_string(slack_), file)) {
Suren Baghdasaryan2bc52282019-02-12 17:30:26 -0800107 if (errno == ENOENT) {
108 // This happens when process is already dead
109 return true;
110 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800111 PLOG(ERROR) << "set_timerslack_ns write failed";
112 }
113 }
114
115 // TODO: Remove when /proc/<tid>/timerslack_ns interface is backported.
116 if (tid == 0 || tid == GetThreadId()) {
117 if (prctl(PR_SET_TIMERSLACK, slack_) == -1) {
118 PLOG(ERROR) << "set_timerslack_ns prctl failed";
119 }
120 }
121
122 return true;
123}
124
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -0800125#endif
126
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800127bool SetAttributeAction::ExecuteForProcess(uid_t, pid_t pid) const {
128 return ExecuteForTask(pid);
129}
130
131bool SetAttributeAction::ExecuteForTask(int tid) const {
132 std::string path;
133
134 if (!attribute_->GetPathForTask(tid, &path)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800135 LOG(ERROR) << "Failed to find cgroup for tid " << tid;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800136 return false;
137 }
138
139 if (!WriteStringToFile(value_, path)) {
140 PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
141 return false;
142 }
143
144 return true;
145}
146
Rick Yiud4c53512021-11-21 15:57:36 +0800147void CachedFdProfileAction::EnableResourceCaching() {
mtk1603653f79e62019-05-31 19:05:22 +0800148 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800149 if (fd_ != FDS_NOT_CACHED) {
150 return;
151 }
152
Rick Yiud4c53512021-11-21 15:57:36 +0800153 std::string tasks_path = GetPath();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800154
155 if (access(tasks_path.c_str(), W_OK) != 0) {
156 // file is not accessible
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800157 fd_.reset(FDS_INACCESSIBLE);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800158 return;
159 }
160
161 unique_fd fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
162 if (fd < 0) {
163 PLOG(ERROR) << "Failed to cache fd '" << tasks_path << "'";
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800164 fd_.reset(FDS_INACCESSIBLE);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800165 return;
166 }
167
168 fd_ = std::move(fd);
169}
170
Rick Yiud4c53512021-11-21 15:57:36 +0800171void CachedFdProfileAction::DropResourceCaching() {
Riddle Hsua6abd822019-06-18 15:53:53 -0600172 std::lock_guard<std::mutex> lock(fd_mutex_);
173 if (fd_ == FDS_NOT_CACHED) {
174 return;
175 }
176
177 fd_.reset(FDS_NOT_CACHED);
178}
179
Rick Yiud4c53512021-11-21 15:57:36 +0800180bool CachedFdProfileAction::IsAppDependentPath(const std::string& path) {
181 return path.find("<uid>", 0) != std::string::npos || path.find("<pid>", 0) != std::string::npos;
182}
183
184void CachedFdProfileAction::InitFd(const std::string& path) {
185 // file descriptors for app-dependent paths can't be cached
186 if (IsAppDependentPath(path)) {
187 // file descriptor is not cached
188 fd_.reset(FDS_APP_DEPENDENT);
189 return;
190 }
191 // file descriptor can be cached later on request
192 fd_.reset(FDS_NOT_CACHED);
193}
194
195SetCgroupAction::SetCgroupAction(const CgroupController& c, const std::string& p)
196 : controller_(c), path_(p) {
197 InitFd(controller_.GetTasksFilePath(path_));
198}
199
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700200bool SetCgroupAction::AddTidToCgroup(int tid, int fd, const char* controller_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800201 if (tid <= 0) {
202 return true;
203 }
204
205 std::string value = std::to_string(tid);
206
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700207 if (TEMP_FAILURE_RETRY(write(fd, value.c_str(), value.length())) == value.length()) {
208 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800209 }
210
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700211 // If the thread is in the process of exiting, don't flag an error
212 if (errno == ESRCH) {
213 return true;
214 }
215
216 // ENOSPC is returned when cpuset cgroup that we are joining has no online cpus
217 if (errno == ENOSPC && !strcmp(controller_name, "cpuset")) {
218 // This is an abnormal case happening only in testing, so report it only once
219 static bool empty_cpuset_reported = false;
220
221 if (empty_cpuset_reported) {
222 return true;
223 }
224
225 LOG(ERROR) << "Failed to add task '" << value
226 << "' into cpuset because all cpus in that cpuset are offline";
227 empty_cpuset_reported = true;
228 } else {
229 PLOG(ERROR) << "AddTidToCgroup failed to write '" << value << "'; fd=" << fd;
230 }
231
232 return false;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800233}
234
235bool SetCgroupAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Yifan Hong53e0deb2019-03-22 17:01:08 -0700236 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800237 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(procs_path.c_str(), O_WRONLY | O_CLOEXEC)));
238 if (tmp_fd < 0) {
Elliott Hughes08b4d322019-03-14 20:06:36 -0700239 PLOG(WARNING) << "Failed to open " << procs_path;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800240 return false;
241 }
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700242 if (!AddTidToCgroup(pid, tmp_fd, controller()->name())) {
Wei Wangd71d3012019-03-07 11:59:12 -0800243 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800244 return false;
245 }
246
247 return true;
248}
249
250bool SetCgroupAction::ExecuteForTask(int tid) const {
mtk1603653f79e62019-05-31 19:05:22 +0800251 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800252 if (IsFdValid()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800253 // fd is cached, reuse it
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700254 if (!AddTidToCgroup(tid, fd_, controller()->name())) {
Wei Wangd71d3012019-03-07 11:59:12 -0800255 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800256 return false;
257 }
258 return true;
259 }
260
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800261 if (fd_ == FDS_INACCESSIBLE) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800262 // no permissions to access the file, ignore
263 return true;
264 }
265
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800266 if (fd_ == FDS_APP_DEPENDENT) {
267 // application-dependent path can't be used with tid
268 PLOG(ERROR) << "Application profile can't be applied to a thread";
269 return false;
270 }
271
272 // fd was not cached because cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700273 std::string tasks_path = controller()->GetTasksFilePath(path_);
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800274 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
275 if (tmp_fd < 0) {
Rick Yiud4c53512021-11-21 15:57:36 +0800276 PLOG(WARNING) << "Failed to open " << tasks_path;
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800277 return false;
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800278 }
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700279 if (!AddTidToCgroup(tid, tmp_fd, controller()->name())) {
Wei Wangd71d3012019-03-07 11:59:12 -0800280 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800281 return false;
282 }
283
284 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800285}
286
Rick Yiud4c53512021-11-21 15:57:36 +0800287WriteFileAction::WriteFileAction(const std::string& path, const std::string& value,
288 bool logfailures)
289 : path_(path), value_(value), logfailures_(logfailures) {
290 InitFd(path_);
291}
Rick Yiubc1ad962020-10-26 20:32:52 +0800292
Rick Yiud4c53512021-11-21 15:57:36 +0800293bool WriteFileAction::WriteValueToFile(const std::string& value, const std::string& path,
294 bool logfailures) {
295 // Use WriteStringToFd instead of WriteStringToFile because the latter will open file with
296 // O_TRUNC which causes kernfs_mutex contention
297 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_WRONLY | O_CLOEXEC)));
Rick Yiubc1ad962020-10-26 20:32:52 +0800298
Rick Yiud4c53512021-11-21 15:57:36 +0800299 if (tmp_fd < 0) {
300 if (logfailures) PLOG(WARNING) << "Failed to open " << path;
301 return false;
302 }
303
304 if (!WriteStringToFd(value, tmp_fd)) {
305 if (logfailures) PLOG(ERROR) << "Failed to write '" << value << "' to " << path;
Rick Yiubc1ad962020-10-26 20:32:52 +0800306 return false;
307 }
308
309 return true;
310}
311
Rick Yiud4c53512021-11-21 15:57:36 +0800312bool WriteFileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
313 std::lock_guard<std::mutex> lock(fd_mutex_);
314 std::string value(value_);
315 std::string path(path_);
316
317 value = StringReplace(value, "<uid>", std::to_string(uid), true);
318 value = StringReplace(value, "<pid>", std::to_string(pid), true);
319 path = StringReplace(path, "<uid>", std::to_string(uid), true);
320 path = StringReplace(path, "<pid>", std::to_string(pid), true);
321
322 return WriteValueToFile(value, path, logfailures_);
323}
324
Rick Yiubc1ad962020-10-26 20:32:52 +0800325bool WriteFileAction::ExecuteForTask(int tid) const {
Rick Yiud4c53512021-11-21 15:57:36 +0800326 std::lock_guard<std::mutex> lock(fd_mutex_);
327 std::string value(value_);
Rick Yiubc1ad962020-10-26 20:32:52 +0800328 int uid = getuid();
329
Rick Yiubc1ad962020-10-26 20:32:52 +0800330 value = StringReplace(value, "<uid>", std::to_string(uid), true);
331 value = StringReplace(value, "<pid>", std::to_string(tid), true);
332
Rick Yiud4c53512021-11-21 15:57:36 +0800333 if (IsFdValid()) {
334 // fd is cached, reuse it
335 if (!WriteStringToFd(value, fd_)) {
336 if (logfailures_) PLOG(ERROR) << "Failed to write '" << value << "' to " << path_;
337 return false;
338 }
339 return true;
340 }
341
342 if (fd_ == FDS_INACCESSIBLE) {
343 // no permissions to access the file, ignore
344 return true;
345 }
346
347 if (fd_ == FDS_APP_DEPENDENT) {
348 // application-dependent path can't be used with tid
349 PLOG(ERROR) << "Application profile can't be applied to a thread";
Rick Yiubc1ad962020-10-26 20:32:52 +0800350 return false;
351 }
352
Rick Yiud4c53512021-11-21 15:57:36 +0800353 return WriteValueToFile(value, path_, logfailures_);
Rick Yiubc1ad962020-10-26 20:32:52 +0800354}
355
Rick Yiu0b211fa2019-09-16 19:07:17 +0800356bool ApplyProfileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
357 for (const auto& profile : profiles_) {
Rick Yiu0b211fa2019-09-16 19:07:17 +0800358 if (!profile->ExecuteForProcess(uid, pid)) {
359 PLOG(WARNING) << "ExecuteForProcess failed for aggregate profile";
360 }
361 }
362 return true;
363}
364
365bool ApplyProfileAction::ExecuteForTask(int tid) const {
366 for (const auto& profile : profiles_) {
Wei Wang8722e4d2021-05-14 12:34:54 -0700367 profile->ExecuteForTask(tid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800368 }
369 return true;
370}
371
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800372void ApplyProfileAction::EnableResourceCaching() {
373 for (const auto& profile : profiles_) {
374 profile->EnableResourceCaching();
375 }
376}
377
378void ApplyProfileAction::DropResourceCaching() {
379 for (const auto& profile : profiles_) {
380 profile->DropResourceCaching();
381 }
382}
383
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800384void TaskProfile::MoveTo(TaskProfile* profile) {
385 profile->elements_ = std::move(elements_);
386 profile->res_cached_ = res_cached_;
387}
388
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800389bool TaskProfile::ExecuteForProcess(uid_t uid, pid_t pid) const {
390 for (const auto& element : elements_) {
391 if (!element->ExecuteForProcess(uid, pid)) {
392 return false;
393 }
394 }
395 return true;
396}
397
398bool TaskProfile::ExecuteForTask(int tid) const {
399 if (tid == 0) {
400 tid = GetThreadId();
401 }
402 for (const auto& element : elements_) {
403 if (!element->ExecuteForTask(tid)) {
404 return false;
405 }
406 }
407 return true;
408}
409
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800410void TaskProfile::EnableResourceCaching() {
411 if (res_cached_) {
412 return;
413 }
414
415 for (auto& element : elements_) {
416 element->EnableResourceCaching();
417 }
418
419 res_cached_ = true;
420}
421
Riddle Hsua6abd822019-06-18 15:53:53 -0600422void TaskProfile::DropResourceCaching() {
423 if (!res_cached_) {
424 return;
425 }
426
427 for (auto& element : elements_) {
428 element->DropResourceCaching();
429 }
430
431 res_cached_ = false;
432}
433
434void TaskProfiles::DropResourceCaching() const {
435 for (auto& iter : profiles_) {
436 iter.second->DropResourceCaching();
437 }
438}
439
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800440TaskProfiles& TaskProfiles::GetInstance() {
Peter Collingbournedba6d442019-03-20 21:09:46 -0700441 // Deliberately leak this object to avoid a race between destruction on
442 // process exit and concurrent access from another thread.
443 static auto* instance = new TaskProfiles;
444 return *instance;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800445}
446
447TaskProfiles::TaskProfiles() {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800448 // load system task profiles
449 if (!Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_FILE)) {
450 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_FILE << " for [" << getpid() << "] failed";
451 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800452
453 // load API-level specific system task profiles if available
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800454 unsigned int api_level = GetUintProperty<unsigned int>("ro.product.first_api_level", 0);
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800455 if (api_level > 0) {
456 std::string api_profiles_path =
457 android::base::StringPrintf(TEMPLATE_TASK_PROFILE_API_FILE, api_level);
458 if (!access(api_profiles_path.c_str(), F_OK) || errno != ENOENT) {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800459 if (!Load(CgroupMap::GetInstance(), api_profiles_path)) {
460 LOG(ERROR) << "Loading " << api_profiles_path << " for [" << getpid()
461 << "] failed";
462 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800463 }
464 }
465
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800466 // load vendor task profiles if the file exists
467 if (!access(TASK_PROFILE_DB_VENDOR_FILE, F_OK) &&
468 !Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_VENDOR_FILE)) {
469 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_VENDOR_FILE << " for [" << getpid()
470 << "] failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800471 }
472}
473
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800474bool TaskProfiles::Load(const CgroupMap& cg_map, const std::string& file_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800475 std::string json_doc;
476
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800477 if (!android::base::ReadFileToString(file_name, &json_doc)) {
478 LOG(ERROR) << "Failed to read task profiles from " << file_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800479 return false;
480 }
481
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800482 Json::CharReaderBuilder builder;
483 std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800484 Json::Value root;
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800485 std::string errorMessage;
486 if (!reader->parse(&*json_doc.begin(), &*json_doc.end(), &root, &errorMessage)) {
487 LOG(ERROR) << "Failed to parse task profiles: " << errorMessage;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800488 return false;
489 }
490
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800491 const Json::Value& attr = root["Attributes"];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800492 for (Json::Value::ArrayIndex i = 0; i < attr.size(); ++i) {
493 std::string name = attr[i]["Name"].asString();
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800494 std::string controller_name = attr[i]["Controller"].asString();
495 std::string file_attr = attr[i]["File"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800496
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700497 auto controller = cg_map.FindController(controller_name);
498 if (controller.HasValue()) {
499 auto iter = attributes_.find(name);
500 if (iter == attributes_.end()) {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800501 attributes_[name] = std::make_unique<ProfileAttribute>(controller, file_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800502 } else {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700503 iter->second->Reset(controller, file_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800504 }
505 } else {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700506 LOG(WARNING) << "Controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800507 }
508 }
509
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800510 const Json::Value& profiles_val = root["Profiles"];
511 for (Json::Value::ArrayIndex i = 0; i < profiles_val.size(); ++i) {
512 const Json::Value& profile_val = profiles_val[i];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800513
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800514 std::string profile_name = profile_val["Name"].asString();
515 const Json::Value& actions = profile_val["Actions"];
Rick Yiu0b211fa2019-09-16 19:07:17 +0800516 auto profile = std::make_shared<TaskProfile>();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800517
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800518 for (Json::Value::ArrayIndex act_idx = 0; act_idx < actions.size(); ++act_idx) {
519 const Json::Value& action_val = actions[act_idx];
520 std::string action_name = action_val["Name"].asString();
521 const Json::Value& params_val = action_val["Params"];
522 if (action_name == "JoinCgroup") {
523 std::string controller_name = params_val["Controller"].asString();
524 std::string path = params_val["Path"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800525
Yifan Hong53e0deb2019-03-22 17:01:08 -0700526 auto controller = cg_map.FindController(controller_name);
527 if (controller.HasValue()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800528 profile->Add(std::make_unique<SetCgroupAction>(controller, path));
529 } else {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800530 LOG(WARNING) << "JoinCgroup: controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800531 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800532 } else if (action_name == "SetTimerSlack") {
533 std::string slack_value = params_val["Slack"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800534 char* end;
535 unsigned long slack;
536
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800537 slack = strtoul(slack_value.c_str(), &end, 10);
538 if (end > slack_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800539 profile->Add(std::make_unique<SetTimerSlackAction>(slack));
540 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800541 LOG(WARNING) << "SetTimerSlack: invalid parameter: " << slack_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800542 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800543 } else if (action_name == "SetAttribute") {
544 std::string attr_name = params_val["Name"].asString();
545 std::string attr_value = params_val["Value"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800546
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800547 auto iter = attributes_.find(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800548 if (iter != attributes_.end()) {
549 profile->Add(
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800550 std::make_unique<SetAttributeAction>(iter->second.get(), attr_value));
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800551 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800552 LOG(WARNING) << "SetAttribute: unknown attribute: " << attr_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800553 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800554 } else if (action_name == "SetClamps") {
555 std::string boost_value = params_val["Boost"].asString();
556 std::string clamp_value = params_val["Clamp"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800557 char* end;
558 unsigned long boost;
559
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800560 boost = strtoul(boost_value.c_str(), &end, 10);
561 if (end > boost_value.c_str()) {
562 unsigned long clamp = strtoul(clamp_value.c_str(), &end, 10);
563 if (end > clamp_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800564 profile->Add(std::make_unique<SetClampsAction>(boost, clamp));
565 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800566 LOG(WARNING) << "SetClamps: invalid parameter " << clamp_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800567 }
568 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800569 LOG(WARNING) << "SetClamps: invalid parameter: " << boost_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800570 }
Rick Yiubc1ad962020-10-26 20:32:52 +0800571 } else if (action_name == "WriteFile") {
572 std::string attr_filepath = params_val["FilePath"].asString();
573 std::string attr_value = params_val["Value"].asString();
574 if (!attr_filepath.empty() && !attr_value.empty()) {
Rick Yiu49fce952021-04-08 22:10:06 +0800575 std::string attr_logfailures = params_val["LogFailures"].asString();
576 bool logfailures = attr_logfailures.empty() || attr_logfailures == "true";
Rick Yiud76053a2021-01-25 12:44:45 +0800577 profile->Add(std::make_unique<WriteFileAction>(attr_filepath, attr_value,
Rick Yiu49fce952021-04-08 22:10:06 +0800578 logfailures));
Rick Yiubc1ad962020-10-26 20:32:52 +0800579 } else if (attr_filepath.empty()) {
580 LOG(WARNING) << "WriteFile: invalid parameter: "
581 << "empty filepath";
582 } else if (attr_value.empty()) {
583 LOG(WARNING) << "WriteFile: invalid parameter: "
584 << "empty value";
585 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800586 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800587 LOG(WARNING) << "Unknown profile action: " << action_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800588 }
589 }
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800590 auto iter = profiles_.find(profile_name);
591 if (iter == profiles_.end()) {
592 profiles_[profile_name] = profile;
593 } else {
594 // Move the content rather that replace the profile because old profile might be
595 // referenced from an aggregate profile if vendor overrides task profiles
596 profile->MoveTo(iter->second.get());
597 profile.reset();
598 }
Rick Yiu0b211fa2019-09-16 19:07:17 +0800599 }
600
601 const Json::Value& aggregateprofiles_val = root["AggregateProfiles"];
602 for (Json::Value::ArrayIndex i = 0; i < aggregateprofiles_val.size(); ++i) {
603 const Json::Value& aggregateprofile_val = aggregateprofiles_val[i];
604
605 std::string aggregateprofile_name = aggregateprofile_val["Name"].asString();
606 const Json::Value& aggregateprofiles = aggregateprofile_val["Profiles"];
607 std::vector<std::shared_ptr<TaskProfile>> profiles;
608 bool ret = true;
609
610 for (Json::Value::ArrayIndex pf_idx = 0; pf_idx < aggregateprofiles.size(); ++pf_idx) {
611 std::string profile_name = aggregateprofiles[pf_idx].asString();
612
613 if (profile_name == aggregateprofile_name) {
614 LOG(WARNING) << "AggregateProfiles: recursive profile name: " << profile_name;
615 ret = false;
616 break;
617 } else if (profiles_.find(profile_name) == profiles_.end()) {
618 LOG(WARNING) << "AggregateProfiles: undefined profile name: " << profile_name;
619 ret = false;
620 break;
621 } else {
622 profiles.push_back(profiles_[profile_name]);
623 }
624 }
625 if (ret) {
626 auto profile = std::make_shared<TaskProfile>();
627 profile->Add(std::make_unique<ApplyProfileAction>(profiles));
628 profiles_[aggregateprofile_name] = profile;
629 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800630 }
631
632 return true;
633}
634
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800635TaskProfile* TaskProfiles::GetProfile(const std::string& name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800636 auto iter = profiles_.find(name);
637
638 if (iter != profiles_.end()) {
639 return iter->second.get();
640 }
641 return nullptr;
642}
643
644const ProfileAttribute* TaskProfiles::GetAttribute(const std::string& name) const {
645 auto iter = attributes_.find(name);
646
647 if (iter != attributes_.end()) {
648 return iter->second.get();
649 }
650 return nullptr;
651}
Rick Yiu0b211fa2019-09-16 19:07:17 +0800652
653bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800654 const std::vector<std::string>& profiles) {
Rick Yiu0b211fa2019-09-16 19:07:17 +0800655 for (const auto& name : profiles) {
656 TaskProfile* profile = GetProfile(name);
657 if (profile != nullptr) {
Rick Yiu0b211fa2019-09-16 19:07:17 +0800658 if (!profile->ExecuteForProcess(uid, pid)) {
659 PLOG(WARNING) << "Failed to apply " << name << " process profile";
660 }
661 } else {
662 PLOG(WARNING) << "Failed to find " << name << "process profile";
663 }
664 }
665 return true;
666}
667
668bool TaskProfiles::SetTaskProfiles(int tid, const std::vector<std::string>& profiles,
669 bool use_fd_cache) {
670 for (const auto& name : profiles) {
671 TaskProfile* profile = GetProfile(name);
672 if (profile != nullptr) {
673 if (use_fd_cache) {
674 profile->EnableResourceCaching();
675 }
676 if (!profile->ExecuteForTask(tid)) {
677 PLOG(WARNING) << "Failed to apply " << name << " task profile";
678 }
679 } else {
680 PLOG(WARNING) << "Failed to find " << name << "task profile";
681 }
682 }
683 return true;
684}