blob: e935f99de947b30ed544e6036b955f6aa517b664 [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
147bool SetCgroupAction::IsAppDependentPath(const std::string& path) {
148 return path.find("<uid>", 0) != std::string::npos || path.find("<pid>", 0) != std::string::npos;
149}
150
Yifan Hong53e0deb2019-03-22 17:01:08 -0700151SetCgroupAction::SetCgroupAction(const CgroupController& c, const std::string& p)
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800152 : controller_(c), path_(p) {
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800153 // file descriptors for app-dependent paths can't be cached
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800154 if (IsAppDependentPath(path_)) {
155 // file descriptor is not cached
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800156 fd_.reset(FDS_APP_DEPENDENT);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800157 return;
158 }
159
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800160 // file descriptor can be cached later on request
161 fd_.reset(FDS_NOT_CACHED);
162}
163
164void SetCgroupAction::EnableResourceCaching() {
mtk1603653f79e62019-05-31 19:05:22 +0800165 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800166 if (fd_ != FDS_NOT_CACHED) {
167 return;
168 }
169
170 std::string tasks_path = controller_.GetTasksFilePath(path_);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800171
172 if (access(tasks_path.c_str(), W_OK) != 0) {
173 // file is not accessible
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800174 fd_.reset(FDS_INACCESSIBLE);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800175 return;
176 }
177
178 unique_fd fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
179 if (fd < 0) {
180 PLOG(ERROR) << "Failed to cache fd '" << tasks_path << "'";
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800181 fd_.reset(FDS_INACCESSIBLE);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800182 return;
183 }
184
185 fd_ = std::move(fd);
186}
187
Riddle Hsua6abd822019-06-18 15:53:53 -0600188void SetCgroupAction::DropResourceCaching() {
189 std::lock_guard<std::mutex> lock(fd_mutex_);
190 if (fd_ == FDS_NOT_CACHED) {
191 return;
192 }
193
194 fd_.reset(FDS_NOT_CACHED);
195}
196
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700197bool SetCgroupAction::AddTidToCgroup(int tid, int fd, const char* controller_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800198 if (tid <= 0) {
199 return true;
200 }
201
202 std::string value = std::to_string(tid);
203
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700204 if (TEMP_FAILURE_RETRY(write(fd, value.c_str(), value.length())) == value.length()) {
205 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800206 }
207
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700208 // If the thread is in the process of exiting, don't flag an error
209 if (errno == ESRCH) {
210 return true;
211 }
212
213 // ENOSPC is returned when cpuset cgroup that we are joining has no online cpus
214 if (errno == ENOSPC && !strcmp(controller_name, "cpuset")) {
215 // This is an abnormal case happening only in testing, so report it only once
216 static bool empty_cpuset_reported = false;
217
218 if (empty_cpuset_reported) {
219 return true;
220 }
221
222 LOG(ERROR) << "Failed to add task '" << value
223 << "' into cpuset because all cpus in that cpuset are offline";
224 empty_cpuset_reported = true;
225 } else {
226 PLOG(ERROR) << "AddTidToCgroup failed to write '" << value << "'; fd=" << fd;
227 }
228
229 return false;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800230}
231
232bool SetCgroupAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Yifan Hong53e0deb2019-03-22 17:01:08 -0700233 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800234 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(procs_path.c_str(), O_WRONLY | O_CLOEXEC)));
235 if (tmp_fd < 0) {
Elliott Hughes08b4d322019-03-14 20:06:36 -0700236 PLOG(WARNING) << "Failed to open " << procs_path;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800237 return false;
238 }
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700239 if (!AddTidToCgroup(pid, tmp_fd, controller()->name())) {
Wei Wangd71d3012019-03-07 11:59:12 -0800240 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800241 return false;
242 }
243
244 return true;
245}
246
247bool SetCgroupAction::ExecuteForTask(int tid) const {
mtk1603653f79e62019-05-31 19:05:22 +0800248 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800249 if (IsFdValid()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800250 // fd is cached, reuse it
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700251 if (!AddTidToCgroup(tid, fd_, controller()->name())) {
Wei Wangd71d3012019-03-07 11:59:12 -0800252 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800253 return false;
254 }
255 return true;
256 }
257
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800258 if (fd_ == FDS_INACCESSIBLE) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800259 // no permissions to access the file, ignore
260 return true;
261 }
262
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800263 if (fd_ == FDS_APP_DEPENDENT) {
264 // application-dependent path can't be used with tid
265 PLOG(ERROR) << "Application profile can't be applied to a thread";
266 return false;
267 }
268
269 // fd was not cached because cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700270 std::string tasks_path = controller()->GetTasksFilePath(path_);
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800271 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
272 if (tmp_fd < 0) {
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800273 PLOG(WARNING) << "Failed to open " << tasks_path << ": " << strerror(errno);
274 return false;
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800275 }
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700276 if (!AddTidToCgroup(tid, tmp_fd, controller()->name())) {
Wei Wangd71d3012019-03-07 11:59:12 -0800277 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800278 return false;
279 }
280
281 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800282}
283
Rick Yiubc1ad962020-10-26 20:32:52 +0800284bool WriteFileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
285 std::string filepath(filepath_), value(value_);
286
287 filepath = StringReplace(filepath, "<uid>", std::to_string(uid), true);
288 filepath = StringReplace(filepath, "<pid>", std::to_string(pid), true);
289 value = StringReplace(value, "<uid>", std::to_string(uid), true);
290 value = StringReplace(value, "<pid>", std::to_string(pid), true);
291
292 if (!WriteStringToFile(value, filepath)) {
Rick Yiud76053a2021-01-25 12:44:45 +0800293 if (logfailures_) PLOG(ERROR) << "Failed to write '" << value << "' to " << filepath;
Rick Yiubc1ad962020-10-26 20:32:52 +0800294 return false;
295 }
296
297 return true;
298}
299
300bool WriteFileAction::ExecuteForTask(int tid) const {
301 std::string filepath(filepath_), value(value_);
302 int uid = getuid();
303
304 filepath = StringReplace(filepath, "<uid>", std::to_string(uid), true);
305 filepath = StringReplace(filepath, "<pid>", std::to_string(tid), true);
306 value = StringReplace(value, "<uid>", std::to_string(uid), true);
307 value = StringReplace(value, "<pid>", std::to_string(tid), true);
308
309 if (!WriteStringToFile(value, filepath)) {
Rick Yiud76053a2021-01-25 12:44:45 +0800310 if (logfailures_) PLOG(ERROR) << "Failed to write '" << value << "' to " << filepath;
Rick Yiubc1ad962020-10-26 20:32:52 +0800311 return false;
312 }
313
314 return true;
315}
316
Rick Yiu0b211fa2019-09-16 19:07:17 +0800317bool ApplyProfileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
318 for (const auto& profile : profiles_) {
Rick Yiu0b211fa2019-09-16 19:07:17 +0800319 if (!profile->ExecuteForProcess(uid, pid)) {
320 PLOG(WARNING) << "ExecuteForProcess failed for aggregate profile";
321 }
322 }
323 return true;
324}
325
326bool ApplyProfileAction::ExecuteForTask(int tid) const {
327 for (const auto& profile : profiles_) {
Wei Wang8722e4d2021-05-14 12:34:54 -0700328 profile->ExecuteForTask(tid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800329 }
330 return true;
331}
332
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800333void ApplyProfileAction::EnableResourceCaching() {
334 for (const auto& profile : profiles_) {
335 profile->EnableResourceCaching();
336 }
337}
338
339void ApplyProfileAction::DropResourceCaching() {
340 for (const auto& profile : profiles_) {
341 profile->DropResourceCaching();
342 }
343}
344
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800345void TaskProfile::MoveTo(TaskProfile* profile) {
346 profile->elements_ = std::move(elements_);
347 profile->res_cached_ = res_cached_;
348}
349
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800350bool TaskProfile::ExecuteForProcess(uid_t uid, pid_t pid) const {
351 for (const auto& element : elements_) {
352 if (!element->ExecuteForProcess(uid, pid)) {
353 return false;
354 }
355 }
356 return true;
357}
358
359bool TaskProfile::ExecuteForTask(int tid) const {
360 if (tid == 0) {
361 tid = GetThreadId();
362 }
363 for (const auto& element : elements_) {
364 if (!element->ExecuteForTask(tid)) {
365 return false;
366 }
367 }
368 return true;
369}
370
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800371void TaskProfile::EnableResourceCaching() {
372 if (res_cached_) {
373 return;
374 }
375
376 for (auto& element : elements_) {
377 element->EnableResourceCaching();
378 }
379
380 res_cached_ = true;
381}
382
Riddle Hsua6abd822019-06-18 15:53:53 -0600383void TaskProfile::DropResourceCaching() {
384 if (!res_cached_) {
385 return;
386 }
387
388 for (auto& element : elements_) {
389 element->DropResourceCaching();
390 }
391
392 res_cached_ = false;
393}
394
395void TaskProfiles::DropResourceCaching() const {
396 for (auto& iter : profiles_) {
397 iter.second->DropResourceCaching();
398 }
399}
400
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800401TaskProfiles& TaskProfiles::GetInstance() {
Peter Collingbournedba6d442019-03-20 21:09:46 -0700402 // Deliberately leak this object to avoid a race between destruction on
403 // process exit and concurrent access from another thread.
404 static auto* instance = new TaskProfiles;
405 return *instance;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800406}
407
408TaskProfiles::TaskProfiles() {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800409 // load system task profiles
410 if (!Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_FILE)) {
411 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_FILE << " for [" << getpid() << "] failed";
412 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800413
414 // load API-level specific system task profiles if available
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800415 unsigned int api_level = GetUintProperty<unsigned int>("ro.product.first_api_level", 0);
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800416 if (api_level > 0) {
417 std::string api_profiles_path =
418 android::base::StringPrintf(TEMPLATE_TASK_PROFILE_API_FILE, api_level);
419 if (!access(api_profiles_path.c_str(), F_OK) || errno != ENOENT) {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800420 if (!Load(CgroupMap::GetInstance(), api_profiles_path)) {
421 LOG(ERROR) << "Loading " << api_profiles_path << " for [" << getpid()
422 << "] failed";
423 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800424 }
425 }
426
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800427 // load vendor task profiles if the file exists
428 if (!access(TASK_PROFILE_DB_VENDOR_FILE, F_OK) &&
429 !Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_VENDOR_FILE)) {
430 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_VENDOR_FILE << " for [" << getpid()
431 << "] failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800432 }
433}
434
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800435bool TaskProfiles::Load(const CgroupMap& cg_map, const std::string& file_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800436 std::string json_doc;
437
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800438 if (!android::base::ReadFileToString(file_name, &json_doc)) {
439 LOG(ERROR) << "Failed to read task profiles from " << file_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800440 return false;
441 }
442
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800443 Json::CharReaderBuilder builder;
444 std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800445 Json::Value root;
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800446 std::string errorMessage;
447 if (!reader->parse(&*json_doc.begin(), &*json_doc.end(), &root, &errorMessage)) {
448 LOG(ERROR) << "Failed to parse task profiles: " << errorMessage;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800449 return false;
450 }
451
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800452 const Json::Value& attr = root["Attributes"];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800453 for (Json::Value::ArrayIndex i = 0; i < attr.size(); ++i) {
454 std::string name = attr[i]["Name"].asString();
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800455 std::string controller_name = attr[i]["Controller"].asString();
456 std::string file_attr = attr[i]["File"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800457
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700458 auto controller = cg_map.FindController(controller_name);
459 if (controller.HasValue()) {
460 auto iter = attributes_.find(name);
461 if (iter == attributes_.end()) {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800462 attributes_[name] = std::make_unique<ProfileAttribute>(controller, file_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800463 } else {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700464 iter->second->Reset(controller, file_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800465 }
466 } else {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700467 LOG(WARNING) << "Controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800468 }
469 }
470
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800471 const Json::Value& profiles_val = root["Profiles"];
472 for (Json::Value::ArrayIndex i = 0; i < profiles_val.size(); ++i) {
473 const Json::Value& profile_val = profiles_val[i];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800474
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800475 std::string profile_name = profile_val["Name"].asString();
476 const Json::Value& actions = profile_val["Actions"];
Rick Yiu0b211fa2019-09-16 19:07:17 +0800477 auto profile = std::make_shared<TaskProfile>();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800478
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800479 for (Json::Value::ArrayIndex act_idx = 0; act_idx < actions.size(); ++act_idx) {
480 const Json::Value& action_val = actions[act_idx];
481 std::string action_name = action_val["Name"].asString();
482 const Json::Value& params_val = action_val["Params"];
483 if (action_name == "JoinCgroup") {
484 std::string controller_name = params_val["Controller"].asString();
485 std::string path = params_val["Path"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800486
Yifan Hong53e0deb2019-03-22 17:01:08 -0700487 auto controller = cg_map.FindController(controller_name);
488 if (controller.HasValue()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800489 profile->Add(std::make_unique<SetCgroupAction>(controller, path));
490 } else {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800491 LOG(WARNING) << "JoinCgroup: controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800492 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800493 } else if (action_name == "SetTimerSlack") {
494 std::string slack_value = params_val["Slack"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800495 char* end;
496 unsigned long slack;
497
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800498 slack = strtoul(slack_value.c_str(), &end, 10);
499 if (end > slack_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800500 profile->Add(std::make_unique<SetTimerSlackAction>(slack));
501 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800502 LOG(WARNING) << "SetTimerSlack: invalid parameter: " << slack_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800503 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800504 } else if (action_name == "SetAttribute") {
505 std::string attr_name = params_val["Name"].asString();
506 std::string attr_value = params_val["Value"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800507
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800508 auto iter = attributes_.find(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800509 if (iter != attributes_.end()) {
510 profile->Add(
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800511 std::make_unique<SetAttributeAction>(iter->second.get(), attr_value));
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800512 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800513 LOG(WARNING) << "SetAttribute: unknown attribute: " << attr_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800514 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800515 } else if (action_name == "SetClamps") {
516 std::string boost_value = params_val["Boost"].asString();
517 std::string clamp_value = params_val["Clamp"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800518 char* end;
519 unsigned long boost;
520
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800521 boost = strtoul(boost_value.c_str(), &end, 10);
522 if (end > boost_value.c_str()) {
523 unsigned long clamp = strtoul(clamp_value.c_str(), &end, 10);
524 if (end > clamp_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800525 profile->Add(std::make_unique<SetClampsAction>(boost, clamp));
526 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800527 LOG(WARNING) << "SetClamps: invalid parameter " << clamp_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800528 }
529 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800530 LOG(WARNING) << "SetClamps: invalid parameter: " << boost_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800531 }
Rick Yiubc1ad962020-10-26 20:32:52 +0800532 } else if (action_name == "WriteFile") {
533 std::string attr_filepath = params_val["FilePath"].asString();
534 std::string attr_value = params_val["Value"].asString();
535 if (!attr_filepath.empty() && !attr_value.empty()) {
Rick Yiu49fce952021-04-08 22:10:06 +0800536 std::string attr_logfailures = params_val["LogFailures"].asString();
537 bool logfailures = attr_logfailures.empty() || attr_logfailures == "true";
Rick Yiud76053a2021-01-25 12:44:45 +0800538 profile->Add(std::make_unique<WriteFileAction>(attr_filepath, attr_value,
Rick Yiu49fce952021-04-08 22:10:06 +0800539 logfailures));
Rick Yiubc1ad962020-10-26 20:32:52 +0800540 } else if (attr_filepath.empty()) {
541 LOG(WARNING) << "WriteFile: invalid parameter: "
542 << "empty filepath";
543 } else if (attr_value.empty()) {
544 LOG(WARNING) << "WriteFile: invalid parameter: "
545 << "empty value";
546 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800547 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800548 LOG(WARNING) << "Unknown profile action: " << action_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800549 }
550 }
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800551 auto iter = profiles_.find(profile_name);
552 if (iter == profiles_.end()) {
553 profiles_[profile_name] = profile;
554 } else {
555 // Move the content rather that replace the profile because old profile might be
556 // referenced from an aggregate profile if vendor overrides task profiles
557 profile->MoveTo(iter->second.get());
558 profile.reset();
559 }
Rick Yiu0b211fa2019-09-16 19:07:17 +0800560 }
561
562 const Json::Value& aggregateprofiles_val = root["AggregateProfiles"];
563 for (Json::Value::ArrayIndex i = 0; i < aggregateprofiles_val.size(); ++i) {
564 const Json::Value& aggregateprofile_val = aggregateprofiles_val[i];
565
566 std::string aggregateprofile_name = aggregateprofile_val["Name"].asString();
567 const Json::Value& aggregateprofiles = aggregateprofile_val["Profiles"];
568 std::vector<std::shared_ptr<TaskProfile>> profiles;
569 bool ret = true;
570
571 for (Json::Value::ArrayIndex pf_idx = 0; pf_idx < aggregateprofiles.size(); ++pf_idx) {
572 std::string profile_name = aggregateprofiles[pf_idx].asString();
573
574 if (profile_name == aggregateprofile_name) {
575 LOG(WARNING) << "AggregateProfiles: recursive profile name: " << profile_name;
576 ret = false;
577 break;
578 } else if (profiles_.find(profile_name) == profiles_.end()) {
579 LOG(WARNING) << "AggregateProfiles: undefined profile name: " << profile_name;
580 ret = false;
581 break;
582 } else {
583 profiles.push_back(profiles_[profile_name]);
584 }
585 }
586 if (ret) {
587 auto profile = std::make_shared<TaskProfile>();
588 profile->Add(std::make_unique<ApplyProfileAction>(profiles));
589 profiles_[aggregateprofile_name] = profile;
590 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800591 }
592
593 return true;
594}
595
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800596TaskProfile* TaskProfiles::GetProfile(const std::string& name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800597 auto iter = profiles_.find(name);
598
599 if (iter != profiles_.end()) {
600 return iter->second.get();
601 }
602 return nullptr;
603}
604
605const ProfileAttribute* TaskProfiles::GetAttribute(const std::string& name) const {
606 auto iter = attributes_.find(name);
607
608 if (iter != attributes_.end()) {
609 return iter->second.get();
610 }
611 return nullptr;
612}
Rick Yiu0b211fa2019-09-16 19:07:17 +0800613
614bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800615 const std::vector<std::string>& profiles) {
Rick Yiu0b211fa2019-09-16 19:07:17 +0800616 for (const auto& name : profiles) {
617 TaskProfile* profile = GetProfile(name);
618 if (profile != nullptr) {
Rick Yiu0b211fa2019-09-16 19:07:17 +0800619 if (!profile->ExecuteForProcess(uid, pid)) {
620 PLOG(WARNING) << "Failed to apply " << name << " process profile";
621 }
622 } else {
623 PLOG(WARNING) << "Failed to find " << name << "process profile";
624 }
625 }
626 return true;
627}
628
629bool TaskProfiles::SetTaskProfiles(int tid, const std::vector<std::string>& profiles,
630 bool use_fd_cache) {
631 for (const auto& name : profiles) {
632 TaskProfile* profile = GetProfile(name);
633 if (profile != nullptr) {
634 if (use_fd_cache) {
635 profile->EnableResourceCaching();
636 }
637 if (!profile->ExecuteForTask(tid)) {
638 PLOG(WARNING) << "Failed to apply " << name << " task profile";
639 }
640 } else {
641 PLOG(WARNING) << "Failed to find " << name << "task profile";
642 }
643 }
644 return true;
645}