blob: f3594e345bd154b404699c8a225a0426aedf1781 [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
T.J. Mercier39846112024-10-09 22:40:26 +000020#include <task_profiles.h>
21
22#include <map>
Siarhei Vishniakou930f77b2024-10-15 13:21:19 -070023#include <optional>
T.J. Mercier39846112024-10-09 22:40:26 +000024#include <string>
25
T.J. Mercier54bfde02024-06-04 23:25:29 +000026#include <dirent.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080027#include <fcntl.h>
T.J. Mercier39846112024-10-09 22:40:26 +000028#include <sched.h>
29#include <sys/resource.h>
T.J. Mercier54bfde02024-06-04 23:25:29 +000030#include <unistd.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080031
32#include <android-base/file.h>
33#include <android-base/logging.h>
Suren Baghdasaryan35221b52020-11-20 17:08:51 -080034#include <android-base/properties.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080035#include <android-base/stringprintf.h>
Rick Yiubc1ad962020-10-26 20:32:52 +080036#include <android-base/strings.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080037#include <android-base/threads.h>
38
T.J. Mercier39846112024-10-09 22:40:26 +000039#include <build_flags.h>
40
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080041#include <cutils/android_filesystem_config.h>
42
43#include <json/reader.h>
44#include <json/value.h>
45
46using android::base::GetThreadId;
Suren Baghdasaryan35221b52020-11-20 17:08:51 -080047using android::base::GetUintProperty;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080048using android::base::StringPrintf;
Rick Yiubc1ad962020-10-26 20:32:52 +080049using android::base::StringReplace;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080050using android::base::unique_fd;
51using android::base::WriteStringToFile;
52
Suren Baghdasaryan35221b52020-11-20 17:08:51 -080053static constexpr const char* TASK_PROFILE_DB_FILE = "/etc/task_profiles.json";
54static constexpr const char* TASK_PROFILE_DB_VENDOR_FILE = "/vendor/etc/task_profiles.json";
55
56static constexpr const char* TEMPLATE_TASK_PROFILE_API_FILE =
57 "/etc/task_profiles/task_profiles_%u.json";
Siarhei Vishniakou930f77b2024-10-15 13:21:19 -070058namespace {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080059
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -080060class FdCacheHelper {
61 public:
62 enum FdState {
63 FDS_INACCESSIBLE = -1,
64 FDS_APP_DEPENDENT = -2,
65 FDS_NOT_CACHED = -3,
66 };
67
68 static void Cache(const std::string& path, android::base::unique_fd& fd);
Siarhei Vishniakou930f77b2024-10-15 13:21:19 -070069
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -080070 static void Drop(android::base::unique_fd& fd);
Siarhei Vishniakou930f77b2024-10-15 13:21:19 -070071
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -080072 static void Init(const std::string& path, android::base::unique_fd& fd);
Siarhei Vishniakou930f77b2024-10-15 13:21:19 -070073
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -080074 static bool IsCached(const android::base::unique_fd& fd) { return fd > FDS_INACCESSIBLE; }
75
76 private:
77 static bool IsAppDependentPath(const std::string& path);
78};
79
80void FdCacheHelper::Init(const std::string& path, android::base::unique_fd& fd) {
81 // file descriptors for app-dependent paths can't be cached
82 if (IsAppDependentPath(path)) {
83 // file descriptor is not cached
84 fd.reset(FDS_APP_DEPENDENT);
85 return;
86 }
87 // file descriptor can be cached later on request
88 fd.reset(FDS_NOT_CACHED);
89}
90
91void FdCacheHelper::Cache(const std::string& path, android::base::unique_fd& fd) {
92 if (fd != FDS_NOT_CACHED) {
93 return;
94 }
95
96 if (access(path.c_str(), W_OK) != 0) {
97 // file is not accessible
98 fd.reset(FDS_INACCESSIBLE);
99 return;
100 }
101
102 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_WRONLY | O_CLOEXEC)));
103 if (tmp_fd < 0) {
104 PLOG(ERROR) << "Failed to cache fd '" << path << "'";
105 fd.reset(FDS_INACCESSIBLE);
106 return;
107 }
108
109 fd = std::move(tmp_fd);
110}
111
112void FdCacheHelper::Drop(android::base::unique_fd& fd) {
113 if (fd == FDS_NOT_CACHED) {
114 return;
115 }
116
117 fd.reset(FDS_NOT_CACHED);
118}
119
120bool FdCacheHelper::IsAppDependentPath(const std::string& path) {
121 return path.find("<uid>", 0) != std::string::npos || path.find("<pid>", 0) != std::string::npos;
122}
123
Siarhei Vishniakou930f77b2024-10-15 13:21:19 -0700124std::optional<long> readLong(const std::string& str) {
125 char* end;
126 const long result = strtol(str.c_str(), &end, 10);
127 if (end > str.c_str()) {
128 return result;
129 }
130 return std::nullopt;
131}
132
133} // namespace
134
Bart Van Assche4c99e962022-02-03 19:50:16 +0000135IProfileAttribute::~IProfileAttribute() = default;
136
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700137const std::string& ProfileAttribute::file_name() const {
138 if (controller()->version() == 2 && !file_v2_name_.empty()) return file_v2_name_;
139 return file_name_;
140}
141
T.J. Mercierfcb86662024-08-01 20:52:30 +0000142void ProfileAttribute::Reset(const CgroupControllerWrapper& controller,
143 const std::string& file_name, const std::string& file_v2_name) {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700144 controller_ = controller;
145 file_name_ = file_name;
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700146 file_v2_name_ = file_v2_name;
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700147}
148
T.J. Mercier1cfa2c42024-04-08 21:14:32 +0000149static bool isSystemApp(uid_t uid) {
150 return uid < AID_APP_START;
151}
152
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000153std::string ConvertUidToPath(const char* root_cgroup_path, uid_t uid) {
T.J. Mercier1cfa2c42024-04-08 21:14:32 +0000154 if (android::libprocessgroup_flags::cgroup_v2_sys_app_isolation()) {
155 if (isSystemApp(uid))
156 return StringPrintf("%s/system/uid_%u", root_cgroup_path, uid);
157 else
158 return StringPrintf("%s/apps/uid_%u", root_cgroup_path, uid);
159 }
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000160 return StringPrintf("%s/uid_%u", root_cgroup_path, uid);
161}
162
163std::string ConvertUidPidToPath(const char* root_cgroup_path, uid_t uid, pid_t pid) {
164 const std::string uid_path = ConvertUidToPath(root_cgroup_path, uid);
165 return StringPrintf("%s/pid_%d", uid_path.c_str(), pid);
166}
167
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700168bool ProfileAttribute::GetPathForProcess(uid_t uid, pid_t pid, std::string* path) const {
169 if (controller()->version() == 2) {
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000170 const std::string cgroup_path = ConvertUidPidToPath(controller()->path(), uid, pid);
171 *path = cgroup_path + "/" + file_name();
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700172 return true;
173 }
174 return GetPathForTask(pid, path);
175}
176
T.J. Mercier1c007992024-01-25 16:29:54 +0000177bool ProfileAttribute::GetPathForTask(pid_t tid, std::string* path) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800178 std::string subgroup;
Yifan Hong53e0deb2019-03-22 17:01:08 -0700179 if (!controller()->GetTaskGroup(tid, &subgroup)) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800180 return false;
181 }
182
183 if (path == nullptr) {
184 return true;
185 }
186
187 if (subgroup.empty()) {
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700188 *path = StringPrintf("%s/%s", controller()->path(), file_name().c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800189 } else {
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700190 *path = StringPrintf("%s/%s/%s", controller()->path(), subgroup.c_str(),
191 file_name().c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800192 }
193 return true;
194}
195
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000196// NOTE: This function is for cgroup v2 only
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000197bool ProfileAttribute::GetPathForUID(uid_t uid, std::string* path) const {
198 if (path == nullptr) {
199 return true;
200 }
201
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000202 const std::string cgroup_path = ConvertUidToPath(controller()->path(), uid);
203 *path = cgroup_path + "/" + file_name();
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000204 return true;
205}
206
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -0800207// To avoid issues in sdk_mac build
208#if defined(__ANDROID__)
209
T.J. Mercier1c007992024-01-25 16:29:54 +0000210bool SetTimerSlackAction::ExecuteForTask(pid_t tid) const {
T.J. Mercier07500812024-10-09 17:41:32 +0000211 const auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
212 if (!WriteStringToFile(std::to_string(slack_), file)) {
213 if (errno == ENOENT) {
214 // This happens when process is already dead
215 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800216 }
T.J. Mercier07500812024-10-09 17:41:32 +0000217 PLOG(ERROR) << "set_timerslack_ns write failed";
218 return false;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800219 }
220
221 return true;
222}
223
Bart Van Assche20d59bd2022-01-24 19:45:59 +0000224#else
225
226bool SetTimerSlackAction::ExecuteForTask(int) const {
227 return true;
228};
229
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -0800230#endif
231
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700232bool SetAttributeAction::WriteValueToFile(const std::string& path) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800233 if (!WriteStringToFile(value_, path)) {
Bart Van Assche9b5a2322022-03-22 16:15:00 -0700234 if (access(path.c_str(), F_OK) < 0) {
Bart Van Assche59af6802022-01-24 21:08:57 +0000235 if (optional_) {
236 return true;
237 } else {
238 LOG(ERROR) << "No such cgroup attribute: " << path;
239 return false;
240 }
241 }
Bart Van Assche54136f82022-03-31 11:26:42 -0700242 // The PLOG() statement below uses the error code stored in `errno` by
243 // WriteStringToFile() because access() only overwrites `errno` if it fails
244 // and because this code is only reached if the access() function returns 0.
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800245 PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
246 return false;
247 }
248
249 return true;
250}
251
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700252bool SetAttributeAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
253 std::string path;
254
255 if (!attribute_->GetPathForProcess(uid, pid, &path)) {
256 LOG(ERROR) << "Failed to find cgroup for uid " << uid << " pid " << pid;
257 return false;
258 }
259
260 return WriteValueToFile(path);
261}
262
T.J. Mercier1c007992024-01-25 16:29:54 +0000263bool SetAttributeAction::ExecuteForTask(pid_t tid) const {
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700264 std::string path;
265
266 if (!attribute_->GetPathForTask(tid, &path)) {
267 LOG(ERROR) << "Failed to find cgroup for tid " << tid;
268 return false;
269 }
270
271 return WriteValueToFile(path);
272}
273
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000274bool SetAttributeAction::ExecuteForUID(uid_t uid) const {
275 std::string path;
276
277 if (!attribute_->GetPathForUID(uid, &path)) {
278 LOG(ERROR) << "Failed to find cgroup for uid " << uid;
279 return false;
280 }
281
282 if (!WriteStringToFile(value_, path)) {
283 if (access(path.c_str(), F_OK) < 0) {
284 if (optional_) {
285 return true;
286 } else {
287 LOG(ERROR) << "No such cgroup attribute: " << path;
288 return false;
289 }
290 }
291 PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
292 return false;
293 }
294 return true;
295}
296
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000297bool SetAttributeAction::IsValidForProcess(uid_t, pid_t pid) const {
298 return IsValidForTask(pid);
299}
300
T.J. Mercier1c007992024-01-25 16:29:54 +0000301bool SetAttributeAction::IsValidForTask(pid_t tid) const {
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000302 std::string path;
303
304 if (!attribute_->GetPathForTask(tid, &path)) {
305 return false;
306 }
307
308 if (!access(path.c_str(), W_OK)) {
309 // operation will succeed
310 return true;
311 }
312
313 if (!access(path.c_str(), F_OK)) {
314 // file exists but not writable
315 return false;
316 }
317
318 // file does not exist, ignore if optional
319 return optional_;
320}
321
T.J. Mercierfcb86662024-08-01 20:52:30 +0000322SetCgroupAction::SetCgroupAction(const CgroupControllerWrapper& c, const std::string& p)
Rick Yiud4c53512021-11-21 15:57:36 +0800323 : controller_(c), path_(p) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800324 FdCacheHelper::Init(controller_.GetTasksFilePath(path_), fd_[ProfileAction::RCT_TASK]);
325 // uid and pid don't matter because IsAppDependentPath ensures the path doesn't use them
326 FdCacheHelper::Init(controller_.GetProcsFilePath(path_, 0, 0), fd_[ProfileAction::RCT_PROCESS]);
Rick Yiud4c53512021-11-21 15:57:36 +0800327}
328
T.J. Mercier1c007992024-01-25 16:29:54 +0000329bool SetCgroupAction::AddTidToCgroup(pid_t tid, int fd, ResourceCacheType cache_type) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800330 if (tid <= 0) {
331 return true;
332 }
333
334 std::string value = std::to_string(tid);
335
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700336 if (TEMP_FAILURE_RETRY(write(fd, value.c_str(), value.length())) == value.length()) {
337 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800338 }
339
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700340 // If the thread is in the process of exiting, don't flag an error
341 if (errno == ESRCH) {
342 return true;
343 }
344
Bart Van Asschedf985342023-11-13 15:19:43 -0800345 const char* controller_name = controller()->name();
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700346 // ENOSPC is returned when cpuset cgroup that we are joining has no online cpus
347 if (errno == ENOSPC && !strcmp(controller_name, "cpuset")) {
348 // This is an abnormal case happening only in testing, so report it only once
349 static bool empty_cpuset_reported = false;
350
351 if (empty_cpuset_reported) {
352 return true;
353 }
354
355 LOG(ERROR) << "Failed to add task '" << value
356 << "' into cpuset because all cpus in that cpuset are offline";
357 empty_cpuset_reported = true;
358 } else {
Bart Van Asschedf985342023-11-13 15:19:43 -0800359 PLOG(ERROR) << "AddTidToCgroup failed to write '" << value << "'; path=" << path_ << "; "
360 << (cache_type == RCT_TASK ? "task" : "process");
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700361 }
362
363 return false;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800364}
365
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800366ProfileAction::CacheUseResult SetCgroupAction::UseCachedFd(ResourceCacheType cache_type,
367 int id) const {
368 std::lock_guard<std::mutex> lock(fd_mutex_);
369 if (FdCacheHelper::IsCached(fd_[cache_type])) {
370 // fd is cached, reuse it
Bart Van Asschedf985342023-11-13 15:19:43 -0800371 if (!AddTidToCgroup(id, fd_[cache_type], cache_type)) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800372 LOG(ERROR) << "Failed to add task into cgroup";
373 return ProfileAction::FAIL;
374 }
375 return ProfileAction::SUCCESS;
376 }
377
378 if (fd_[cache_type] == FdCacheHelper::FDS_INACCESSIBLE) {
379 // no permissions to access the file, ignore
380 return ProfileAction::SUCCESS;
381 }
382
383 if (cache_type == ResourceCacheType::RCT_TASK &&
384 fd_[cache_type] == FdCacheHelper::FDS_APP_DEPENDENT) {
385 // application-dependent path can't be used with tid
Bart Van Assche7a952612022-10-12 13:27:28 -0700386 LOG(ERROR) << Name() << ": application profile can't be applied to a thread";
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800387 return ProfileAction::FAIL;
388 }
389
390 return ProfileAction::UNUSED;
391}
392
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800393bool SetCgroupAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800394 CacheUseResult result = UseCachedFd(ProfileAction::RCT_PROCESS, pid);
395 if (result != ProfileAction::UNUSED) {
396 return result == ProfileAction::SUCCESS;
397 }
398
399 // fd was not cached or cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700400 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800401 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(procs_path.c_str(), O_WRONLY | O_CLOEXEC)));
402 if (tmp_fd < 0) {
Bart Van Assche7a952612022-10-12 13:27:28 -0700403 PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << procs_path;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800404 return false;
405 }
Bart Van Asschedf985342023-11-13 15:19:43 -0800406 if (!AddTidToCgroup(pid, tmp_fd, RCT_PROCESS)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800407 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800408 return false;
409 }
410
411 return true;
412}
413
T.J. Mercier1c007992024-01-25 16:29:54 +0000414bool SetCgroupAction::ExecuteForTask(pid_t tid) const {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800415 CacheUseResult result = UseCachedFd(ProfileAction::RCT_TASK, tid);
416 if (result != ProfileAction::UNUSED) {
417 return result == ProfileAction::SUCCESS;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800418 }
419
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800420 // fd was not cached or cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700421 std::string tasks_path = controller()->GetTasksFilePath(path_);
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800422 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
423 if (tmp_fd < 0) {
Bart Van Assche7a952612022-10-12 13:27:28 -0700424 PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << tasks_path;
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800425 return false;
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800426 }
Bart Van Asschedf985342023-11-13 15:19:43 -0800427 if (!AddTidToCgroup(tid, tmp_fd, RCT_TASK)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800428 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800429 return false;
430 }
431
432 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800433}
434
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800435void SetCgroupAction::EnableResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800436 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800437 // Return early to prevent unnecessary calls to controller_.Get{Tasks|Procs}FilePath() which
438 // include regex evaluations
439 if (fd_[cache_type] != FdCacheHelper::FDS_NOT_CACHED) {
440 return;
441 }
442 switch (cache_type) {
443 case (ProfileAction::RCT_TASK):
444 FdCacheHelper::Cache(controller_.GetTasksFilePath(path_), fd_[cache_type]);
445 break;
446 case (ProfileAction::RCT_PROCESS):
447 // uid and pid don't matter because IsAppDependentPath ensures the path doesn't use them
448 FdCacheHelper::Cache(controller_.GetProcsFilePath(path_, 0, 0), fd_[cache_type]);
449 break;
450 default:
451 LOG(ERROR) << "Invalid cache type is specified!";
452 break;
453 }
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800454}
455
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800456void SetCgroupAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800457 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800458 FdCacheHelper::Drop(fd_[cache_type]);
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800459}
460
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000461bool SetCgroupAction::IsValidForProcess(uid_t uid, pid_t pid) const {
462 std::lock_guard<std::mutex> lock(fd_mutex_);
463 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_PROCESS])) {
464 return true;
465 }
466
467 if (fd_[ProfileAction::RCT_PROCESS] == FdCacheHelper::FDS_INACCESSIBLE) {
468 return false;
469 }
470
471 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
472 return access(procs_path.c_str(), W_OK) == 0;
473}
474
475bool SetCgroupAction::IsValidForTask(int) const {
476 std::lock_guard<std::mutex> lock(fd_mutex_);
477 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_TASK])) {
478 return true;
479 }
480
481 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_INACCESSIBLE) {
482 return false;
483 }
484
485 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_APP_DEPENDENT) {
486 // application-dependent path can't be used with tid
487 return false;
488 }
489
490 std::string tasks_path = controller()->GetTasksFilePath(path_);
491 return access(tasks_path.c_str(), W_OK) == 0;
492}
493
Rick Yiu9221b1e2022-02-10 16:44:43 +0800494WriteFileAction::WriteFileAction(const std::string& task_path, const std::string& proc_path,
495 const std::string& value, bool logfailures)
496 : task_path_(task_path), proc_path_(proc_path), value_(value), logfailures_(logfailures) {
497 FdCacheHelper::Init(task_path_, fd_[ProfileAction::RCT_TASK]);
498 if (!proc_path_.empty()) FdCacheHelper::Init(proc_path_, fd_[ProfileAction::RCT_PROCESS]);
Rick Yiud4c53512021-11-21 15:57:36 +0800499}
Rick Yiubc1ad962020-10-26 20:32:52 +0800500
Rick Yiu9221b1e2022-02-10 16:44:43 +0800501bool WriteFileAction::WriteValueToFile(const std::string& value_, ResourceCacheType cache_type,
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000502 uid_t uid, pid_t pid, bool logfailures) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800503 std::string value(value_);
504
505 value = StringReplace(value, "<uid>", std::to_string(uid), true);
506 value = StringReplace(value, "<pid>", std::to_string(pid), true);
507
508 CacheUseResult result = UseCachedFd(cache_type, value);
509
510 if (result != ProfileAction::UNUSED) {
511 return result == ProfileAction::SUCCESS;
512 }
513
514 std::string path;
515 if (cache_type == ProfileAction::RCT_TASK || proc_path_.empty()) {
516 path = task_path_;
517 } else {
518 path = proc_path_;
519 }
520
Rick Yiud4c53512021-11-21 15:57:36 +0800521 // Use WriteStringToFd instead of WriteStringToFile because the latter will open file with
522 // O_TRUNC which causes kernfs_mutex contention
523 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_WRONLY | O_CLOEXEC)));
Rick Yiubc1ad962020-10-26 20:32:52 +0800524
Rick Yiud4c53512021-11-21 15:57:36 +0800525 if (tmp_fd < 0) {
Bart Van Assche7a952612022-10-12 13:27:28 -0700526 if (logfailures) PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << path;
Rick Yiud4c53512021-11-21 15:57:36 +0800527 return false;
528 }
529
530 if (!WriteStringToFd(value, tmp_fd)) {
531 if (logfailures) PLOG(ERROR) << "Failed to write '" << value << "' to " << path;
Rick Yiubc1ad962020-10-26 20:32:52 +0800532 return false;
533 }
534
535 return true;
536}
537
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800538ProfileAction::CacheUseResult WriteFileAction::UseCachedFd(ResourceCacheType cache_type,
539 const std::string& value) const {
Rick Yiud4c53512021-11-21 15:57:36 +0800540 std::lock_guard<std::mutex> lock(fd_mutex_);
Rick Yiu9221b1e2022-02-10 16:44:43 +0800541 if (FdCacheHelper::IsCached(fd_[cache_type])) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800542 // fd is cached, reuse it
Rick Yiu9221b1e2022-02-10 16:44:43 +0800543 bool ret = WriteStringToFd(value, fd_[cache_type]);
544
545 if (!ret && logfailures_) {
546 if (cache_type == ProfileAction::RCT_TASK || proc_path_.empty()) {
547 PLOG(ERROR) << "Failed to write '" << value << "' to " << task_path_;
548 } else {
549 PLOG(ERROR) << "Failed to write '" << value << "' to " << proc_path_;
550 }
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800551 }
Rick Yiu9221b1e2022-02-10 16:44:43 +0800552 return ret ? ProfileAction::SUCCESS : ProfileAction::FAIL;
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800553 }
554
Rick Yiu9221b1e2022-02-10 16:44:43 +0800555 if (fd_[cache_type] == FdCacheHelper::FDS_INACCESSIBLE) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800556 // no permissions to access the file, ignore
557 return ProfileAction::SUCCESS;
558 }
559
Rick Yiu9221b1e2022-02-10 16:44:43 +0800560 if (cache_type == ResourceCacheType::RCT_TASK &&
561 fd_[cache_type] == FdCacheHelper::FDS_APP_DEPENDENT) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800562 // application-dependent path can't be used with tid
Bart Van Assche7a952612022-10-12 13:27:28 -0700563 LOG(ERROR) << Name() << ": application profile can't be applied to a thread";
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800564 return ProfileAction::FAIL;
565 }
566 return ProfileAction::UNUSED;
567}
568
569bool WriteFileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800570 if (!proc_path_.empty()) {
571 return WriteValueToFile(value_, ProfileAction::RCT_PROCESS, uid, pid, logfailures_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800572 }
573
Rick Yiu9221b1e2022-02-10 16:44:43 +0800574 DIR* d;
575 struct dirent* de;
576 char proc_path[255];
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000577 pid_t t_pid;
Rick Yiud4c53512021-11-21 15:57:36 +0800578
Rick Yiu9221b1e2022-02-10 16:44:43 +0800579 sprintf(proc_path, "/proc/%d/task", pid);
580 if (!(d = opendir(proc_path))) {
581 return false;
582 }
583
584 while ((de = readdir(d))) {
585 if (de->d_name[0] == '.') {
586 continue;
587 }
588
589 t_pid = atoi(de->d_name);
590
591 if (!t_pid) {
592 continue;
593 }
594
595 WriteValueToFile(value_, ProfileAction::RCT_TASK, uid, t_pid, logfailures_);
596 }
597
598 closedir(d);
599
600 return true;
Rick Yiud4c53512021-11-21 15:57:36 +0800601}
602
T.J. Mercier1c007992024-01-25 16:29:54 +0000603bool WriteFileAction::ExecuteForTask(pid_t tid) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800604 return WriteValueToFile(value_, ProfileAction::RCT_TASK, getuid(), tid, logfailures_);
605}
Rick Yiubc1ad962020-10-26 20:32:52 +0800606
Rick Yiu9221b1e2022-02-10 16:44:43 +0800607void WriteFileAction::EnableResourceCaching(ResourceCacheType cache_type) {
608 std::lock_guard<std::mutex> lock(fd_mutex_);
609 if (fd_[cache_type] != FdCacheHelper::FDS_NOT_CACHED) {
610 return;
Rick Yiubc1ad962020-10-26 20:32:52 +0800611 }
Rick Yiu9221b1e2022-02-10 16:44:43 +0800612 switch (cache_type) {
613 case (ProfileAction::RCT_TASK):
614 FdCacheHelper::Cache(task_path_, fd_[cache_type]);
615 break;
616 case (ProfileAction::RCT_PROCESS):
617 if (!proc_path_.empty()) FdCacheHelper::Cache(proc_path_, fd_[cache_type]);
618 break;
619 default:
620 LOG(ERROR) << "Invalid cache type is specified!";
621 break;
622 }
Rick Yiubc1ad962020-10-26 20:32:52 +0800623}
624
Rick Yiu9221b1e2022-02-10 16:44:43 +0800625void WriteFileAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800626 std::lock_guard<std::mutex> lock(fd_mutex_);
Rick Yiu9221b1e2022-02-10 16:44:43 +0800627 FdCacheHelper::Drop(fd_[cache_type]);
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800628}
629
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000630bool WriteFileAction::IsValidForProcess(uid_t, pid_t) const {
631 std::lock_guard<std::mutex> lock(fd_mutex_);
632 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_PROCESS])) {
633 return true;
634 }
635
636 if (fd_[ProfileAction::RCT_PROCESS] == FdCacheHelper::FDS_INACCESSIBLE) {
637 return false;
638 }
639
640 return access(proc_path_.empty() ? task_path_.c_str() : proc_path_.c_str(), W_OK) == 0;
641}
642
643bool WriteFileAction::IsValidForTask(int) const {
644 std::lock_guard<std::mutex> lock(fd_mutex_);
645 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_TASK])) {
646 return true;
647 }
648
649 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_INACCESSIBLE) {
650 return false;
651 }
652
653 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_APP_DEPENDENT) {
654 // application-dependent path can't be used with tid
655 return false;
656 }
657
658 return access(task_path_.c_str(), W_OK) == 0;
659}
660
T.J. Mercier39846112024-10-09 22:40:26 +0000661bool SetSchedulerPolicyAction::isNormalPolicy(int policy) {
662 return policy == SCHED_OTHER || policy == SCHED_BATCH || policy == SCHED_IDLE;
663}
664
665bool SetSchedulerPolicyAction::toPriority(int policy, int virtual_priority, int& priority_out) {
666 constexpr int VIRTUAL_PRIORITY_MIN = 1;
667 constexpr int VIRTUAL_PRIORITY_MAX = 99;
668
669 if (virtual_priority < VIRTUAL_PRIORITY_MIN || virtual_priority > VIRTUAL_PRIORITY_MAX) {
670 LOG(WARNING) << "SetSchedulerPolicy: invalid priority (" << virtual_priority
671 << ") for policy (" << policy << ")";
672 return false;
673 }
674
675 const int min = sched_get_priority_min(policy);
676 if (min == -1) {
677 PLOG(ERROR) << "SetSchedulerPolicy: Cannot get min sched priority for policy " << policy;
678 return false;
679 }
680
681 const int max = sched_get_priority_max(policy);
682 if (max == -1) {
683 PLOG(ERROR) << "SetSchedulerPolicy: Cannot get max sched priority for policy " << policy;
684 return false;
685 }
686
687 priority_out = min + (virtual_priority - VIRTUAL_PRIORITY_MIN) * (max - min) /
688 (VIRTUAL_PRIORITY_MAX - VIRTUAL_PRIORITY_MIN);
689
690 return true;
691}
692
693bool SetSchedulerPolicyAction::ExecuteForTask(pid_t tid) const {
694 struct sched_param param = {};
695 param.sched_priority = isNormalPolicy(policy_) ? 0 : *priority_or_nice_;
696 if (sched_setscheduler(tid, policy_, &param) == -1) {
697 PLOG(WARNING) << "SetSchedulerPolicy: Failed to apply scheduler policy (" << policy_
698 << ") with priority (" << *priority_or_nice_ << ") to tid " << tid;
699 return false;
700 }
701
702 if (isNormalPolicy(policy_) && priority_or_nice_ &&
703 setpriority(PRIO_PROCESS, tid, *priority_or_nice_) == -1) {
704 PLOG(WARNING) << "SetSchedulerPolicy: Failed to apply nice (" << *priority_or_nice_
705 << ") to tid " << tid;
706 return false;
707 }
708
709 return true;
710}
711
Rick Yiu0b211fa2019-09-16 19:07:17 +0800712bool ApplyProfileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
713 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800714 profile->ExecuteForProcess(uid, pid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800715 }
716 return true;
717}
718
T.J. Mercier1c007992024-01-25 16:29:54 +0000719bool ApplyProfileAction::ExecuteForTask(pid_t tid) const {
Rick Yiu0b211fa2019-09-16 19:07:17 +0800720 for (const auto& profile : profiles_) {
Wei Wang8722e4d2021-05-14 12:34:54 -0700721 profile->ExecuteForTask(tid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800722 }
723 return true;
724}
725
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800726void ApplyProfileAction::EnableResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800727 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800728 profile->EnableResourceCaching(cache_type);
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800729 }
730}
731
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800732void ApplyProfileAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800733 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800734 profile->DropResourceCaching(cache_type);
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800735 }
736}
737
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000738bool ApplyProfileAction::IsValidForProcess(uid_t uid, pid_t pid) const {
739 for (const auto& profile : profiles_) {
740 if (!profile->IsValidForProcess(uid, pid)) {
741 return false;
742 }
743 }
744 return true;
745}
746
T.J. Mercier1c007992024-01-25 16:29:54 +0000747bool ApplyProfileAction::IsValidForTask(pid_t tid) const {
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000748 for (const auto& profile : profiles_) {
749 if (!profile->IsValidForTask(tid)) {
750 return false;
751 }
752 }
753 return true;
754}
755
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800756void TaskProfile::MoveTo(TaskProfile* profile) {
757 profile->elements_ = std::move(elements_);
758 profile->res_cached_ = res_cached_;
759}
760
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800761bool TaskProfile::ExecuteForProcess(uid_t uid, pid_t pid) const {
762 for (const auto& element : elements_) {
763 if (!element->ExecuteForProcess(uid, pid)) {
Bart Van Asschef096bd22022-01-24 19:59:13 +0000764 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800765 return false;
766 }
767 }
768 return true;
769}
770
T.J. Mercier1c007992024-01-25 16:29:54 +0000771bool TaskProfile::ExecuteForTask(pid_t tid) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800772 if (tid == 0) {
773 tid = GetThreadId();
774 }
775 for (const auto& element : elements_) {
776 if (!element->ExecuteForTask(tid)) {
Bart Van Asschef096bd22022-01-24 19:59:13 +0000777 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800778 return false;
779 }
780 }
781 return true;
782}
783
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000784bool TaskProfile::ExecuteForUID(uid_t uid) const {
785 for (const auto& element : elements_) {
786 if (!element->ExecuteForUID(uid)) {
787 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
788 return false;
789 }
790 }
791 return true;
792}
793
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800794void TaskProfile::EnableResourceCaching(ProfileAction::ResourceCacheType cache_type) {
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800795 if (res_cached_) {
796 return;
797 }
798
799 for (auto& element : elements_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800800 element->EnableResourceCaching(cache_type);
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800801 }
802
803 res_cached_ = true;
804}
805
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800806void TaskProfile::DropResourceCaching(ProfileAction::ResourceCacheType cache_type) {
Riddle Hsua6abd822019-06-18 15:53:53 -0600807 if (!res_cached_) {
808 return;
809 }
810
811 for (auto& element : elements_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800812 element->DropResourceCaching(cache_type);
Riddle Hsua6abd822019-06-18 15:53:53 -0600813 }
814
815 res_cached_ = false;
816}
817
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000818bool TaskProfile::IsValidForProcess(uid_t uid, pid_t pid) const {
819 for (const auto& element : elements_) {
820 if (!element->IsValidForProcess(uid, pid)) return false;
821 }
822 return true;
823}
824
T.J. Mercier1c007992024-01-25 16:29:54 +0000825bool TaskProfile::IsValidForTask(pid_t tid) const {
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000826 for (const auto& element : elements_) {
827 if (!element->IsValidForTask(tid)) return false;
828 }
829 return true;
830}
831
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800832void TaskProfiles::DropResourceCaching(ProfileAction::ResourceCacheType cache_type) const {
Riddle Hsua6abd822019-06-18 15:53:53 -0600833 for (auto& iter : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800834 iter.second->DropResourceCaching(cache_type);
Riddle Hsua6abd822019-06-18 15:53:53 -0600835 }
836}
837
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800838TaskProfiles& TaskProfiles::GetInstance() {
Peter Collingbournedba6d442019-03-20 21:09:46 -0700839 // Deliberately leak this object to avoid a race between destruction on
840 // process exit and concurrent access from another thread.
841 static auto* instance = new TaskProfiles;
842 return *instance;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800843}
844
845TaskProfiles::TaskProfiles() {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800846 // load system task profiles
847 if (!Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_FILE)) {
848 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_FILE << " for [" << getpid() << "] failed";
849 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800850
851 // load API-level specific system task profiles if available
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800852 unsigned int api_level = GetUintProperty<unsigned int>("ro.product.first_api_level", 0);
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800853 if (api_level > 0) {
854 std::string api_profiles_path =
855 android::base::StringPrintf(TEMPLATE_TASK_PROFILE_API_FILE, api_level);
856 if (!access(api_profiles_path.c_str(), F_OK) || errno != ENOENT) {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800857 if (!Load(CgroupMap::GetInstance(), api_profiles_path)) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800858 LOG(ERROR) << "Loading " << api_profiles_path << " for [" << getpid() << "] failed";
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800859 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800860 }
861 }
862
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800863 // load vendor task profiles if the file exists
864 if (!access(TASK_PROFILE_DB_VENDOR_FILE, F_OK) &&
865 !Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_VENDOR_FILE)) {
866 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_VENDOR_FILE << " for [" << getpid()
867 << "] failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800868 }
869}
870
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800871bool TaskProfiles::Load(const CgroupMap& cg_map, const std::string& file_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800872 std::string json_doc;
873
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800874 if (!android::base::ReadFileToString(file_name, &json_doc)) {
875 LOG(ERROR) << "Failed to read task profiles from " << file_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800876 return false;
877 }
878
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800879 Json::CharReaderBuilder builder;
880 std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800881 Json::Value root;
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800882 std::string errorMessage;
883 if (!reader->parse(&*json_doc.begin(), &*json_doc.end(), &root, &errorMessage)) {
884 LOG(ERROR) << "Failed to parse task profiles: " << errorMessage;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800885 return false;
886 }
887
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800888 const Json::Value& attr = root["Attributes"];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800889 for (Json::Value::ArrayIndex i = 0; i < attr.size(); ++i) {
890 std::string name = attr[i]["Name"].asString();
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800891 std::string controller_name = attr[i]["Controller"].asString();
892 std::string file_attr = attr[i]["File"].asString();
Bart Van Asschebc077ff2022-02-17 01:26:44 +0000893 std::string file_v2_attr = attr[i]["FileV2"].asString();
894
895 if (!file_v2_attr.empty() && file_attr.empty()) {
896 LOG(ERROR) << "Attribute " << name << " has FileV2 but no File property";
897 return false;
898 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800899
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700900 auto controller = cg_map.FindController(controller_name);
901 if (controller.HasValue()) {
902 auto iter = attributes_.find(name);
903 if (iter == attributes_.end()) {
Bart Van Asschebc077ff2022-02-17 01:26:44 +0000904 attributes_[name] =
905 std::make_unique<ProfileAttribute>(controller, file_attr, file_v2_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800906 } else {
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700907 iter->second->Reset(controller, file_attr, file_v2_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800908 }
909 } else {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700910 LOG(WARNING) << "Controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800911 }
912 }
913
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800914 const Json::Value& profiles_val = root["Profiles"];
915 for (Json::Value::ArrayIndex i = 0; i < profiles_val.size(); ++i) {
916 const Json::Value& profile_val = profiles_val[i];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800917
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800918 std::string profile_name = profile_val["Name"].asString();
919 const Json::Value& actions = profile_val["Actions"];
Bart Van Asschef096bd22022-01-24 19:59:13 +0000920 auto profile = std::make_shared<TaskProfile>(profile_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800921
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800922 for (Json::Value::ArrayIndex act_idx = 0; act_idx < actions.size(); ++act_idx) {
923 const Json::Value& action_val = actions[act_idx];
924 std::string action_name = action_val["Name"].asString();
925 const Json::Value& params_val = action_val["Params"];
926 if (action_name == "JoinCgroup") {
927 std::string controller_name = params_val["Controller"].asString();
928 std::string path = params_val["Path"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800929
Yifan Hong53e0deb2019-03-22 17:01:08 -0700930 auto controller = cg_map.FindController(controller_name);
931 if (controller.HasValue()) {
Bart Van Assche2953a922023-11-14 07:33:00 -0800932 if (controller.version() == 1) {
933 profile->Add(std::make_unique<SetCgroupAction>(controller, path));
934 } else {
935 LOG(WARNING) << "A JoinCgroup action in the " << profile_name
936 << " profile is used for controller " << controller_name
937 << " in the cgroup v2 hierarchy and will be ignored";
938 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800939 } else {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800940 LOG(WARNING) << "JoinCgroup: controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800941 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800942 } else if (action_name == "SetTimerSlack") {
Siarhei Vishniakou930f77b2024-10-15 13:21:19 -0700943 const std::string slack_string = params_val["Slack"].asString();
944 std::optional<long> slack = readLong(slack_string);
945 if (slack && *slack >= 0) {
946 profile->Add(std::make_unique<SetTimerSlackAction>(*slack));
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800947 } else {
Siarhei Vishniakou930f77b2024-10-15 13:21:19 -0700948 LOG(WARNING) << "SetTimerSlack: invalid parameter: " << slack_string;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800949 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800950 } else if (action_name == "SetAttribute") {
951 std::string attr_name = params_val["Name"].asString();
952 std::string attr_value = params_val["Value"].asString();
Bart Van Assche59af6802022-01-24 21:08:57 +0000953 bool optional = strcmp(params_val["Optional"].asString().c_str(), "true") == 0;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800954
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800955 auto iter = attributes_.find(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800956 if (iter != attributes_.end()) {
Bart Van Assche59af6802022-01-24 21:08:57 +0000957 profile->Add(std::make_unique<SetAttributeAction>(iter->second.get(),
958 attr_value, optional));
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800959 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800960 LOG(WARNING) << "SetAttribute: unknown attribute: " << attr_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800961 }
Rick Yiubc1ad962020-10-26 20:32:52 +0800962 } else if (action_name == "WriteFile") {
963 std::string attr_filepath = params_val["FilePath"].asString();
Rick Yiu9221b1e2022-02-10 16:44:43 +0800964 std::string attr_procfilepath = params_val["ProcFilePath"].asString();
Rick Yiubc1ad962020-10-26 20:32:52 +0800965 std::string attr_value = params_val["Value"].asString();
Rick Yiu9221b1e2022-02-10 16:44:43 +0800966 // FilePath and Value are mandatory
Rick Yiubc1ad962020-10-26 20:32:52 +0800967 if (!attr_filepath.empty() && !attr_value.empty()) {
Rick Yiu49fce952021-04-08 22:10:06 +0800968 std::string attr_logfailures = params_val["LogFailures"].asString();
969 bool logfailures = attr_logfailures.empty() || attr_logfailures == "true";
Rick Yiu9221b1e2022-02-10 16:44:43 +0800970 profile->Add(std::make_unique<WriteFileAction>(attr_filepath, attr_procfilepath,
971 attr_value, logfailures));
Rick Yiubc1ad962020-10-26 20:32:52 +0800972 } else if (attr_filepath.empty()) {
973 LOG(WARNING) << "WriteFile: invalid parameter: "
974 << "empty filepath";
975 } else if (attr_value.empty()) {
976 LOG(WARNING) << "WriteFile: invalid parameter: "
977 << "empty value";
978 }
T.J. Mercier39846112024-10-09 22:40:26 +0000979 } else if (action_name == "SetSchedulerPolicy") {
980 const std::map<std::string, int> POLICY_MAP = {
981 {"SCHED_OTHER", SCHED_OTHER},
982 {"SCHED_BATCH", SCHED_BATCH},
983 {"SCHED_IDLE", SCHED_IDLE},
984 {"SCHED_FIFO", SCHED_FIFO},
985 {"SCHED_RR", SCHED_RR},
986 };
987 const std::string policy_str = params_val["Policy"].asString();
988
989 const auto it = POLICY_MAP.find(policy_str);
990 if (it == POLICY_MAP.end()) {
991 LOG(WARNING) << "SetSchedulerPolicy: invalid policy " << policy_str;
992 continue;
993 }
994
995 const int policy = it->second;
996
997 if (SetSchedulerPolicyAction::isNormalPolicy(policy)) {
998 if (params_val.isMember("Priority")) {
999 LOG(WARNING) << "SetSchedulerPolicy: Normal policies (" << policy_str
1000 << ") use Nice values, not Priority values";
1001 }
1002
1003 if (params_val.isMember("Nice")) {
1004 // If present, this optional value will be passed in an additional syscall
1005 // to setpriority(), since the sched_priority value must be 0 for calls to
1006 // sched_setscheduler() with "normal" policies.
Siarhei Vishniakou930f77b2024-10-15 13:21:19 -07001007 const std::string nice_string = params_val["Nice"].asString();
1008 const std::optional<int> nice = readLong(nice_string);
T.J. Mercier39846112024-10-09 22:40:26 +00001009
Siarhei Vishniakou930f77b2024-10-15 13:21:19 -07001010 if (!nice) {
1011 LOG(FATAL) << "Invalid nice value specified: " << nice_string;
1012 }
T.J. Mercier39846112024-10-09 22:40:26 +00001013 const int LINUX_MIN_NICE = -20;
1014 const int LINUX_MAX_NICE = 19;
Siarhei Vishniakou930f77b2024-10-15 13:21:19 -07001015 if (*nice < LINUX_MIN_NICE || *nice > LINUX_MAX_NICE) {
1016 LOG(WARNING) << "SetSchedulerPolicy: Provided nice (" << *nice
T.J. Mercier39846112024-10-09 22:40:26 +00001017 << ") appears out of range.";
1018 }
Siarhei Vishniakou930f77b2024-10-15 13:21:19 -07001019 profile->Add(std::make_unique<SetSchedulerPolicyAction>(policy, *nice));
T.J. Mercier39846112024-10-09 22:40:26 +00001020 } else {
1021 profile->Add(std::make_unique<SetSchedulerPolicyAction>(policy));
1022 }
1023 } else {
1024 if (params_val.isMember("Nice")) {
1025 LOG(WARNING) << "SetSchedulerPolicy: Real-time policies (" << policy_str
1026 << ") use Priority values, not Nice values";
1027 }
1028
1029 // This is a "virtual priority" as described by `man 2 sched_get_priority_min`
1030 // that will be mapped onto the following range for the provided policy:
1031 // [sched_get_priority_min(), sched_get_priority_max()]
T.J. Mercier39846112024-10-09 22:40:26 +00001032
Siarhei Vishniakou930f77b2024-10-15 13:21:19 -07001033 const std::string priority_string = params_val["Priority"].asString();
1034 std::optional<long> virtual_priority = readLong(priority_string);
1035 if (virtual_priority && *virtual_priority > 0) {
1036 int priority;
1037 if (SetSchedulerPolicyAction::toPriority(policy, *virtual_priority,
1038 priority)) {
1039 profile->Add(
1040 std::make_unique<SetSchedulerPolicyAction>(policy, priority));
1041 }
1042 } else {
1043 LOG(WARNING) << "Invalid priority value: " << priority_string;
T.J. Mercier39846112024-10-09 22:40:26 +00001044 }
1045 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -08001046 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -08001047 LOG(WARNING) << "Unknown profile action: " << action_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -08001048 }
1049 }
Suren Baghdasaryan84385952020-01-24 16:36:10 -08001050 auto iter = profiles_.find(profile_name);
1051 if (iter == profiles_.end()) {
1052 profiles_[profile_name] = profile;
1053 } else {
1054 // Move the content rather that replace the profile because old profile might be
1055 // referenced from an aggregate profile if vendor overrides task profiles
1056 profile->MoveTo(iter->second.get());
1057 profile.reset();
1058 }
Rick Yiu0b211fa2019-09-16 19:07:17 +08001059 }
1060
1061 const Json::Value& aggregateprofiles_val = root["AggregateProfiles"];
1062 for (Json::Value::ArrayIndex i = 0; i < aggregateprofiles_val.size(); ++i) {
1063 const Json::Value& aggregateprofile_val = aggregateprofiles_val[i];
1064
1065 std::string aggregateprofile_name = aggregateprofile_val["Name"].asString();
1066 const Json::Value& aggregateprofiles = aggregateprofile_val["Profiles"];
1067 std::vector<std::shared_ptr<TaskProfile>> profiles;
1068 bool ret = true;
1069
1070 for (Json::Value::ArrayIndex pf_idx = 0; pf_idx < aggregateprofiles.size(); ++pf_idx) {
1071 std::string profile_name = aggregateprofiles[pf_idx].asString();
1072
1073 if (profile_name == aggregateprofile_name) {
1074 LOG(WARNING) << "AggregateProfiles: recursive profile name: " << profile_name;
1075 ret = false;
1076 break;
1077 } else if (profiles_.find(profile_name) == profiles_.end()) {
1078 LOG(WARNING) << "AggregateProfiles: undefined profile name: " << profile_name;
1079 ret = false;
1080 break;
1081 } else {
1082 profiles.push_back(profiles_[profile_name]);
1083 }
1084 }
1085 if (ret) {
Bart Van Asschef096bd22022-01-24 19:59:13 +00001086 auto profile = std::make_shared<TaskProfile>(aggregateprofile_name);
Rick Yiu0b211fa2019-09-16 19:07:17 +08001087 profile->Add(std::make_unique<ApplyProfileAction>(profiles));
1088 profiles_[aggregateprofile_name] = profile;
1089 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -08001090 }
1091
1092 return true;
1093}
1094
Bart Van Assched0b8ce22022-08-02 13:06:26 -07001095TaskProfile* TaskProfiles::GetProfile(std::string_view name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -08001096 auto iter = profiles_.find(name);
1097
1098 if (iter != profiles_.end()) {
1099 return iter->second.get();
1100 }
1101 return nullptr;
1102}
1103
Bart Van Assched0b8ce22022-08-02 13:06:26 -07001104const IProfileAttribute* TaskProfiles::GetAttribute(std::string_view name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -08001105 auto iter = attributes_.find(name);
1106
1107 if (iter != attributes_.end()) {
1108 return iter->second.get();
1109 }
1110 return nullptr;
1111}
Rick Yiu0b211fa2019-09-16 19:07:17 +08001112
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001113template <typename T>
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +00001114bool TaskProfiles::SetUserProfiles(uid_t uid, std::span<const T> profiles, bool use_fd_cache) {
1115 for (const auto& name : profiles) {
1116 TaskProfile* profile = GetProfile(name);
1117 if (profile != nullptr) {
1118 if (use_fd_cache) {
1119 profile->EnableResourceCaching(ProfileAction::RCT_PROCESS);
1120 }
1121 if (!profile->ExecuteForUID(uid)) {
1122 PLOG(WARNING) << "Failed to apply " << name << " process profile";
1123 }
1124 } else {
1125 PLOG(WARNING) << "Failed to find " << name << "process profile";
1126 }
1127 }
1128 return true;
1129}
1130
1131template <typename T>
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001132bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid, std::span<const T> profiles,
1133 bool use_fd_cache) {
Inseob Kim538fc1f2022-04-13 18:50:12 +00001134 bool success = true;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001135 for (const auto& name : profiles) {
1136 TaskProfile* profile = GetProfile(name);
1137 if (profile != nullptr) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -08001138 if (use_fd_cache) {
1139 profile->EnableResourceCaching(ProfileAction::RCT_PROCESS);
1140 }
Rick Yiu0b211fa2019-09-16 19:07:17 +08001141 if (!profile->ExecuteForProcess(uid, pid)) {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001142 LOG(WARNING) << "Failed to apply " << name << " process profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001143 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001144 }
1145 } else {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001146 LOG(WARNING) << "Failed to find " << name << " process profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001147 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001148 }
1149 }
Inseob Kim538fc1f2022-04-13 18:50:12 +00001150 return success;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001151}
1152
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001153template <typename T>
T.J. Mercier1c007992024-01-25 16:29:54 +00001154bool TaskProfiles::SetTaskProfiles(pid_t tid, std::span<const T> profiles, bool use_fd_cache) {
Inseob Kim538fc1f2022-04-13 18:50:12 +00001155 bool success = true;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001156 for (const auto& name : profiles) {
1157 TaskProfile* profile = GetProfile(name);
1158 if (profile != nullptr) {
1159 if (use_fd_cache) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -08001160 profile->EnableResourceCaching(ProfileAction::RCT_TASK);
Rick Yiu0b211fa2019-09-16 19:07:17 +08001161 }
1162 if (!profile->ExecuteForTask(tid)) {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001163 LOG(WARNING) << "Failed to apply " << name << " task profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001164 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001165 }
1166 } else {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001167 LOG(WARNING) << "Failed to find " << name << " task profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001168 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001169 }
1170 }
Inseob Kim538fc1f2022-04-13 18:50:12 +00001171 return success;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001172}
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001173
1174template bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
1175 std::span<const std::string> profiles,
1176 bool use_fd_cache);
1177template bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
1178 std::span<const std::string_view> profiles,
1179 bool use_fd_cache);
T.J. Mercier1c007992024-01-25 16:29:54 +00001180template bool TaskProfiles::SetTaskProfiles(pid_t tid, std::span<const std::string> profiles,
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001181 bool use_fd_cache);
T.J. Mercier1c007992024-01-25 16:29:54 +00001182template bool TaskProfiles::SetTaskProfiles(pid_t tid, std::span<const std::string_view> profiles,
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001183 bool use_fd_cache);
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +00001184template bool TaskProfiles::SetUserProfiles(uid_t uid, std::span<const std::string> profiles,
1185 bool use_fd_cache);