blob: 0c2252b17df4a72fd6eee153c277e668204b51b3 [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
T.J. Mercier1cfa2c42024-04-08 21:14:32 +000036#include <build_flags.h>
37
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -080038// To avoid issues in sdk_mac build
39#if defined(__ANDROID__)
40#include <sys/prctl.h>
41#endif
42
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080043using android::base::GetThreadId;
Suren Baghdasaryan35221b52020-11-20 17:08:51 -080044using android::base::GetUintProperty;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080045using android::base::StringPrintf;
Rick Yiubc1ad962020-10-26 20:32:52 +080046using android::base::StringReplace;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080047using android::base::unique_fd;
48using android::base::WriteStringToFile;
49
Suren Baghdasaryan35221b52020-11-20 17:08:51 -080050static constexpr const char* TASK_PROFILE_DB_FILE = "/etc/task_profiles.json";
51static constexpr const char* TASK_PROFILE_DB_VENDOR_FILE = "/vendor/etc/task_profiles.json";
52
53static constexpr const char* TEMPLATE_TASK_PROFILE_API_FILE =
54 "/etc/task_profiles/task_profiles_%u.json";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080055
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -080056class FdCacheHelper {
57 public:
58 enum FdState {
59 FDS_INACCESSIBLE = -1,
60 FDS_APP_DEPENDENT = -2,
61 FDS_NOT_CACHED = -3,
62 };
63
64 static void Cache(const std::string& path, android::base::unique_fd& fd);
65 static void Drop(android::base::unique_fd& fd);
66 static void Init(const std::string& path, android::base::unique_fd& fd);
67 static bool IsCached(const android::base::unique_fd& fd) { return fd > FDS_INACCESSIBLE; }
68
69 private:
70 static bool IsAppDependentPath(const std::string& path);
71};
72
73void FdCacheHelper::Init(const std::string& path, android::base::unique_fd& fd) {
74 // file descriptors for app-dependent paths can't be cached
75 if (IsAppDependentPath(path)) {
76 // file descriptor is not cached
77 fd.reset(FDS_APP_DEPENDENT);
78 return;
79 }
80 // file descriptor can be cached later on request
81 fd.reset(FDS_NOT_CACHED);
82}
83
84void FdCacheHelper::Cache(const std::string& path, android::base::unique_fd& fd) {
85 if (fd != FDS_NOT_CACHED) {
86 return;
87 }
88
89 if (access(path.c_str(), W_OK) != 0) {
90 // file is not accessible
91 fd.reset(FDS_INACCESSIBLE);
92 return;
93 }
94
95 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_WRONLY | O_CLOEXEC)));
96 if (tmp_fd < 0) {
97 PLOG(ERROR) << "Failed to cache fd '" << path << "'";
98 fd.reset(FDS_INACCESSIBLE);
99 return;
100 }
101
102 fd = std::move(tmp_fd);
103}
104
105void FdCacheHelper::Drop(android::base::unique_fd& fd) {
106 if (fd == FDS_NOT_CACHED) {
107 return;
108 }
109
110 fd.reset(FDS_NOT_CACHED);
111}
112
113bool FdCacheHelper::IsAppDependentPath(const std::string& path) {
114 return path.find("<uid>", 0) != std::string::npos || path.find("<pid>", 0) != std::string::npos;
115}
116
Bart Van Assche4c99e962022-02-03 19:50:16 +0000117IProfileAttribute::~IProfileAttribute() = default;
118
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700119const std::string& ProfileAttribute::file_name() const {
120 if (controller()->version() == 2 && !file_v2_name_.empty()) return file_v2_name_;
121 return file_name_;
122}
123
124void ProfileAttribute::Reset(const CgroupController& controller, const std::string& file_name,
125 const std::string& file_v2_name) {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700126 controller_ = controller;
127 file_name_ = file_name;
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700128 file_v2_name_ = file_v2_name;
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700129}
130
T.J. Mercier1cfa2c42024-04-08 21:14:32 +0000131static bool isSystemApp(uid_t uid) {
132 return uid < AID_APP_START;
133}
134
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000135std::string ConvertUidToPath(const char* root_cgroup_path, uid_t uid) {
T.J. Mercier1cfa2c42024-04-08 21:14:32 +0000136 if (android::libprocessgroup_flags::cgroup_v2_sys_app_isolation()) {
137 if (isSystemApp(uid))
138 return StringPrintf("%s/system/uid_%u", root_cgroup_path, uid);
139 else
140 return StringPrintf("%s/apps/uid_%u", root_cgroup_path, uid);
141 }
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000142 return StringPrintf("%s/uid_%u", root_cgroup_path, uid);
143}
144
145std::string ConvertUidPidToPath(const char* root_cgroup_path, uid_t uid, pid_t pid) {
146 const std::string uid_path = ConvertUidToPath(root_cgroup_path, uid);
147 return StringPrintf("%s/pid_%d", uid_path.c_str(), pid);
148}
149
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700150bool ProfileAttribute::GetPathForProcess(uid_t uid, pid_t pid, std::string* path) const {
151 if (controller()->version() == 2) {
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000152 const std::string cgroup_path = ConvertUidPidToPath(controller()->path(), uid, pid);
153 *path = cgroup_path + "/" + file_name();
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700154 return true;
155 }
156 return GetPathForTask(pid, path);
157}
158
T.J. Mercier1c007992024-01-25 16:29:54 +0000159bool ProfileAttribute::GetPathForTask(pid_t tid, std::string* path) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800160 std::string subgroup;
Yifan Hong53e0deb2019-03-22 17:01:08 -0700161 if (!controller()->GetTaskGroup(tid, &subgroup)) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800162 return false;
163 }
164
165 if (path == nullptr) {
166 return true;
167 }
168
169 if (subgroup.empty()) {
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700170 *path = StringPrintf("%s/%s", controller()->path(), file_name().c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800171 } else {
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700172 *path = StringPrintf("%s/%s/%s", controller()->path(), subgroup.c_str(),
173 file_name().c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800174 }
175 return true;
176}
177
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000178// NOTE: This function is for cgroup v2 only
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000179bool ProfileAttribute::GetPathForUID(uid_t uid, std::string* path) const {
180 if (path == nullptr) {
181 return true;
182 }
183
T.J. Mercierd1e048f2024-03-28 00:33:44 +0000184 const std::string cgroup_path = ConvertUidToPath(controller()->path(), uid);
185 *path = cgroup_path + "/" + file_name();
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000186 return true;
187}
188
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800189bool SetClampsAction::ExecuteForProcess(uid_t, pid_t) const {
190 // TODO: add support when kernel supports util_clamp
191 LOG(WARNING) << "SetClampsAction::ExecuteForProcess is not supported";
192 return false;
193}
194
195bool SetClampsAction::ExecuteForTask(int) const {
196 // TODO: add support when kernel supports util_clamp
197 LOG(WARNING) << "SetClampsAction::ExecuteForTask is not supported";
198 return false;
199}
200
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -0800201// To avoid issues in sdk_mac build
202#if defined(__ANDROID__)
203
T.J. Mercier1c007992024-01-25 16:29:54 +0000204bool SetTimerSlackAction::IsTimerSlackSupported(pid_t tid) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800205 auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
206
207 return (access(file.c_str(), W_OK) == 0);
208}
209
T.J. Mercier1c007992024-01-25 16:29:54 +0000210bool SetTimerSlackAction::ExecuteForTask(pid_t tid) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800211 static bool sys_supports_timerslack = IsTimerSlackSupported(tid);
212
213 // v4.6+ kernels support the /proc/<tid>/timerslack_ns interface.
214 // TODO: once we've backported this, log if the open(2) fails.
215 if (sys_supports_timerslack) {
216 auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
217 if (!WriteStringToFile(std::to_string(slack_), file)) {
Suren Baghdasaryan2bc52282019-02-12 17:30:26 -0800218 if (errno == ENOENT) {
219 // This happens when process is already dead
220 return true;
221 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800222 PLOG(ERROR) << "set_timerslack_ns write failed";
223 }
224 }
225
226 // TODO: Remove when /proc/<tid>/timerslack_ns interface is backported.
227 if (tid == 0 || tid == GetThreadId()) {
228 if (prctl(PR_SET_TIMERSLACK, slack_) == -1) {
229 PLOG(ERROR) << "set_timerslack_ns prctl failed";
230 }
231 }
232
233 return true;
234}
235
Bart Van Assche20d59bd2022-01-24 19:45:59 +0000236#else
237
238bool SetTimerSlackAction::ExecuteForTask(int) const {
239 return true;
240};
241
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -0800242#endif
243
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700244bool SetAttributeAction::WriteValueToFile(const std::string& path) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800245 if (!WriteStringToFile(value_, path)) {
Bart Van Assche9b5a2322022-03-22 16:15:00 -0700246 if (access(path.c_str(), F_OK) < 0) {
Bart Van Assche59af6802022-01-24 21:08:57 +0000247 if (optional_) {
248 return true;
249 } else {
250 LOG(ERROR) << "No such cgroup attribute: " << path;
251 return false;
252 }
253 }
Bart Van Assche54136f82022-03-31 11:26:42 -0700254 // The PLOG() statement below uses the error code stored in `errno` by
255 // WriteStringToFile() because access() only overwrites `errno` if it fails
256 // and because this code is only reached if the access() function returns 0.
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800257 PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
258 return false;
259 }
260
261 return true;
262}
263
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700264bool SetAttributeAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
265 std::string path;
266
267 if (!attribute_->GetPathForProcess(uid, pid, &path)) {
268 LOG(ERROR) << "Failed to find cgroup for uid " << uid << " pid " << pid;
269 return false;
270 }
271
272 return WriteValueToFile(path);
273}
274
T.J. Mercier1c007992024-01-25 16:29:54 +0000275bool SetAttributeAction::ExecuteForTask(pid_t tid) const {
Suren Baghdasaryan34837982023-07-25 15:45:45 -0700276 std::string path;
277
278 if (!attribute_->GetPathForTask(tid, &path)) {
279 LOG(ERROR) << "Failed to find cgroup for tid " << tid;
280 return false;
281 }
282
283 return WriteValueToFile(path);
284}
285
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000286bool SetAttributeAction::ExecuteForUID(uid_t uid) const {
287 std::string path;
288
289 if (!attribute_->GetPathForUID(uid, &path)) {
290 LOG(ERROR) << "Failed to find cgroup for uid " << uid;
291 return false;
292 }
293
294 if (!WriteStringToFile(value_, path)) {
295 if (access(path.c_str(), F_OK) < 0) {
296 if (optional_) {
297 return true;
298 } else {
299 LOG(ERROR) << "No such cgroup attribute: " << path;
300 return false;
301 }
302 }
303 PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
304 return false;
305 }
306 return true;
307}
308
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000309bool SetAttributeAction::IsValidForProcess(uid_t, pid_t pid) const {
310 return IsValidForTask(pid);
311}
312
T.J. Mercier1c007992024-01-25 16:29:54 +0000313bool SetAttributeAction::IsValidForTask(pid_t tid) const {
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000314 std::string path;
315
316 if (!attribute_->GetPathForTask(tid, &path)) {
317 return false;
318 }
319
320 if (!access(path.c_str(), W_OK)) {
321 // operation will succeed
322 return true;
323 }
324
325 if (!access(path.c_str(), F_OK)) {
326 // file exists but not writable
327 return false;
328 }
329
330 // file does not exist, ignore if optional
331 return optional_;
332}
333
Rick Yiud4c53512021-11-21 15:57:36 +0800334SetCgroupAction::SetCgroupAction(const CgroupController& c, const std::string& p)
335 : controller_(c), path_(p) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800336 FdCacheHelper::Init(controller_.GetTasksFilePath(path_), fd_[ProfileAction::RCT_TASK]);
337 // uid and pid don't matter because IsAppDependentPath ensures the path doesn't use them
338 FdCacheHelper::Init(controller_.GetProcsFilePath(path_, 0, 0), fd_[ProfileAction::RCT_PROCESS]);
Rick Yiud4c53512021-11-21 15:57:36 +0800339}
340
T.J. Mercier1c007992024-01-25 16:29:54 +0000341bool SetCgroupAction::AddTidToCgroup(pid_t tid, int fd, ResourceCacheType cache_type) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800342 if (tid <= 0) {
343 return true;
344 }
345
346 std::string value = std::to_string(tid);
347
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700348 if (TEMP_FAILURE_RETRY(write(fd, value.c_str(), value.length())) == value.length()) {
349 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800350 }
351
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700352 // If the thread is in the process of exiting, don't flag an error
353 if (errno == ESRCH) {
354 return true;
355 }
356
Bart Van Asschedf985342023-11-13 15:19:43 -0800357 const char* controller_name = controller()->name();
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700358 // ENOSPC is returned when cpuset cgroup that we are joining has no online cpus
359 if (errno == ENOSPC && !strcmp(controller_name, "cpuset")) {
360 // This is an abnormal case happening only in testing, so report it only once
361 static bool empty_cpuset_reported = false;
362
363 if (empty_cpuset_reported) {
364 return true;
365 }
366
367 LOG(ERROR) << "Failed to add task '" << value
368 << "' into cpuset because all cpus in that cpuset are offline";
369 empty_cpuset_reported = true;
370 } else {
Bart Van Asschedf985342023-11-13 15:19:43 -0800371 PLOG(ERROR) << "AddTidToCgroup failed to write '" << value << "'; path=" << path_ << "; "
372 << (cache_type == RCT_TASK ? "task" : "process");
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700373 }
374
375 return false;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800376}
377
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800378ProfileAction::CacheUseResult SetCgroupAction::UseCachedFd(ResourceCacheType cache_type,
379 int id) const {
380 std::lock_guard<std::mutex> lock(fd_mutex_);
381 if (FdCacheHelper::IsCached(fd_[cache_type])) {
382 // fd is cached, reuse it
Bart Van Asschedf985342023-11-13 15:19:43 -0800383 if (!AddTidToCgroup(id, fd_[cache_type], cache_type)) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800384 LOG(ERROR) << "Failed to add task into cgroup";
385 return ProfileAction::FAIL;
386 }
387 return ProfileAction::SUCCESS;
388 }
389
390 if (fd_[cache_type] == FdCacheHelper::FDS_INACCESSIBLE) {
391 // no permissions to access the file, ignore
392 return ProfileAction::SUCCESS;
393 }
394
395 if (cache_type == ResourceCacheType::RCT_TASK &&
396 fd_[cache_type] == FdCacheHelper::FDS_APP_DEPENDENT) {
397 // application-dependent path can't be used with tid
Bart Van Assche7a952612022-10-12 13:27:28 -0700398 LOG(ERROR) << Name() << ": application profile can't be applied to a thread";
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800399 return ProfileAction::FAIL;
400 }
401
402 return ProfileAction::UNUSED;
403}
404
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800405bool SetCgroupAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800406 CacheUseResult result = UseCachedFd(ProfileAction::RCT_PROCESS, pid);
407 if (result != ProfileAction::UNUSED) {
408 return result == ProfileAction::SUCCESS;
409 }
410
411 // fd was not cached or cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700412 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800413 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(procs_path.c_str(), O_WRONLY | O_CLOEXEC)));
414 if (tmp_fd < 0) {
Bart Van Assche7a952612022-10-12 13:27:28 -0700415 PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << procs_path;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800416 return false;
417 }
Bart Van Asschedf985342023-11-13 15:19:43 -0800418 if (!AddTidToCgroup(pid, tmp_fd, RCT_PROCESS)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800419 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800420 return false;
421 }
422
423 return true;
424}
425
T.J. Mercier1c007992024-01-25 16:29:54 +0000426bool SetCgroupAction::ExecuteForTask(pid_t tid) const {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800427 CacheUseResult result = UseCachedFd(ProfileAction::RCT_TASK, tid);
428 if (result != ProfileAction::UNUSED) {
429 return result == ProfileAction::SUCCESS;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800430 }
431
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800432 // fd was not cached or cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700433 std::string tasks_path = controller()->GetTasksFilePath(path_);
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800434 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
435 if (tmp_fd < 0) {
Bart Van Assche7a952612022-10-12 13:27:28 -0700436 PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << tasks_path;
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800437 return false;
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800438 }
Bart Van Asschedf985342023-11-13 15:19:43 -0800439 if (!AddTidToCgroup(tid, tmp_fd, RCT_TASK)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800440 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800441 return false;
442 }
443
444 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800445}
446
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800447void SetCgroupAction::EnableResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800448 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800449 // Return early to prevent unnecessary calls to controller_.Get{Tasks|Procs}FilePath() which
450 // include regex evaluations
451 if (fd_[cache_type] != FdCacheHelper::FDS_NOT_CACHED) {
452 return;
453 }
454 switch (cache_type) {
455 case (ProfileAction::RCT_TASK):
456 FdCacheHelper::Cache(controller_.GetTasksFilePath(path_), fd_[cache_type]);
457 break;
458 case (ProfileAction::RCT_PROCESS):
459 // uid and pid don't matter because IsAppDependentPath ensures the path doesn't use them
460 FdCacheHelper::Cache(controller_.GetProcsFilePath(path_, 0, 0), fd_[cache_type]);
461 break;
462 default:
463 LOG(ERROR) << "Invalid cache type is specified!";
464 break;
465 }
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800466}
467
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800468void SetCgroupAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800469 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800470 FdCacheHelper::Drop(fd_[cache_type]);
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800471}
472
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000473bool SetCgroupAction::IsValidForProcess(uid_t uid, pid_t pid) const {
474 std::lock_guard<std::mutex> lock(fd_mutex_);
475 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_PROCESS])) {
476 return true;
477 }
478
479 if (fd_[ProfileAction::RCT_PROCESS] == FdCacheHelper::FDS_INACCESSIBLE) {
480 return false;
481 }
482
483 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
484 return access(procs_path.c_str(), W_OK) == 0;
485}
486
487bool SetCgroupAction::IsValidForTask(int) const {
488 std::lock_guard<std::mutex> lock(fd_mutex_);
489 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_TASK])) {
490 return true;
491 }
492
493 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_INACCESSIBLE) {
494 return false;
495 }
496
497 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_APP_DEPENDENT) {
498 // application-dependent path can't be used with tid
499 return false;
500 }
501
502 std::string tasks_path = controller()->GetTasksFilePath(path_);
503 return access(tasks_path.c_str(), W_OK) == 0;
504}
505
Rick Yiu9221b1e2022-02-10 16:44:43 +0800506WriteFileAction::WriteFileAction(const std::string& task_path, const std::string& proc_path,
507 const std::string& value, bool logfailures)
508 : task_path_(task_path), proc_path_(proc_path), value_(value), logfailures_(logfailures) {
509 FdCacheHelper::Init(task_path_, fd_[ProfileAction::RCT_TASK]);
510 if (!proc_path_.empty()) FdCacheHelper::Init(proc_path_, fd_[ProfileAction::RCT_PROCESS]);
Rick Yiud4c53512021-11-21 15:57:36 +0800511}
Rick Yiubc1ad962020-10-26 20:32:52 +0800512
Rick Yiu9221b1e2022-02-10 16:44:43 +0800513bool WriteFileAction::WriteValueToFile(const std::string& value_, ResourceCacheType cache_type,
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000514 uid_t uid, pid_t pid, bool logfailures) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800515 std::string value(value_);
516
517 value = StringReplace(value, "<uid>", std::to_string(uid), true);
518 value = StringReplace(value, "<pid>", std::to_string(pid), true);
519
520 CacheUseResult result = UseCachedFd(cache_type, value);
521
522 if (result != ProfileAction::UNUSED) {
523 return result == ProfileAction::SUCCESS;
524 }
525
526 std::string path;
527 if (cache_type == ProfileAction::RCT_TASK || proc_path_.empty()) {
528 path = task_path_;
529 } else {
530 path = proc_path_;
531 }
532
Rick Yiud4c53512021-11-21 15:57:36 +0800533 // Use WriteStringToFd instead of WriteStringToFile because the latter will open file with
534 // O_TRUNC which causes kernfs_mutex contention
535 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_WRONLY | O_CLOEXEC)));
Rick Yiubc1ad962020-10-26 20:32:52 +0800536
Rick Yiud4c53512021-11-21 15:57:36 +0800537 if (tmp_fd < 0) {
Bart Van Assche7a952612022-10-12 13:27:28 -0700538 if (logfailures) PLOG(WARNING) << Name() << "::" << __func__ << ": failed to open " << path;
Rick Yiud4c53512021-11-21 15:57:36 +0800539 return false;
540 }
541
542 if (!WriteStringToFd(value, tmp_fd)) {
543 if (logfailures) PLOG(ERROR) << "Failed to write '" << value << "' to " << path;
Rick Yiubc1ad962020-10-26 20:32:52 +0800544 return false;
545 }
546
547 return true;
548}
549
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800550ProfileAction::CacheUseResult WriteFileAction::UseCachedFd(ResourceCacheType cache_type,
551 const std::string& value) const {
Rick Yiud4c53512021-11-21 15:57:36 +0800552 std::lock_guard<std::mutex> lock(fd_mutex_);
Rick Yiu9221b1e2022-02-10 16:44:43 +0800553 if (FdCacheHelper::IsCached(fd_[cache_type])) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800554 // fd is cached, reuse it
Rick Yiu9221b1e2022-02-10 16:44:43 +0800555 bool ret = WriteStringToFd(value, fd_[cache_type]);
556
557 if (!ret && logfailures_) {
558 if (cache_type == ProfileAction::RCT_TASK || proc_path_.empty()) {
559 PLOG(ERROR) << "Failed to write '" << value << "' to " << task_path_;
560 } else {
561 PLOG(ERROR) << "Failed to write '" << value << "' to " << proc_path_;
562 }
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800563 }
Rick Yiu9221b1e2022-02-10 16:44:43 +0800564 return ret ? ProfileAction::SUCCESS : ProfileAction::FAIL;
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800565 }
566
Rick Yiu9221b1e2022-02-10 16:44:43 +0800567 if (fd_[cache_type] == FdCacheHelper::FDS_INACCESSIBLE) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800568 // no permissions to access the file, ignore
569 return ProfileAction::SUCCESS;
570 }
571
Rick Yiu9221b1e2022-02-10 16:44:43 +0800572 if (cache_type == ResourceCacheType::RCT_TASK &&
573 fd_[cache_type] == FdCacheHelper::FDS_APP_DEPENDENT) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800574 // application-dependent path can't be used with tid
Bart Van Assche7a952612022-10-12 13:27:28 -0700575 LOG(ERROR) << Name() << ": application profile can't be applied to a thread";
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800576 return ProfileAction::FAIL;
577 }
578 return ProfileAction::UNUSED;
579}
580
581bool WriteFileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800582 if (!proc_path_.empty()) {
583 return WriteValueToFile(value_, ProfileAction::RCT_PROCESS, uid, pid, logfailures_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800584 }
585
Rick Yiu9221b1e2022-02-10 16:44:43 +0800586 DIR* d;
587 struct dirent* de;
588 char proc_path[255];
T.J. Mercierd6fb2252024-01-24 23:42:39 +0000589 pid_t t_pid;
Rick Yiud4c53512021-11-21 15:57:36 +0800590
Rick Yiu9221b1e2022-02-10 16:44:43 +0800591 sprintf(proc_path, "/proc/%d/task", pid);
592 if (!(d = opendir(proc_path))) {
593 return false;
594 }
595
596 while ((de = readdir(d))) {
597 if (de->d_name[0] == '.') {
598 continue;
599 }
600
601 t_pid = atoi(de->d_name);
602
603 if (!t_pid) {
604 continue;
605 }
606
607 WriteValueToFile(value_, ProfileAction::RCT_TASK, uid, t_pid, logfailures_);
608 }
609
610 closedir(d);
611
612 return true;
Rick Yiud4c53512021-11-21 15:57:36 +0800613}
614
T.J. Mercier1c007992024-01-25 16:29:54 +0000615bool WriteFileAction::ExecuteForTask(pid_t tid) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800616 return WriteValueToFile(value_, ProfileAction::RCT_TASK, getuid(), tid, logfailures_);
617}
Rick Yiubc1ad962020-10-26 20:32:52 +0800618
Rick Yiu9221b1e2022-02-10 16:44:43 +0800619void WriteFileAction::EnableResourceCaching(ResourceCacheType cache_type) {
620 std::lock_guard<std::mutex> lock(fd_mutex_);
621 if (fd_[cache_type] != FdCacheHelper::FDS_NOT_CACHED) {
622 return;
Rick Yiubc1ad962020-10-26 20:32:52 +0800623 }
Rick Yiu9221b1e2022-02-10 16:44:43 +0800624 switch (cache_type) {
625 case (ProfileAction::RCT_TASK):
626 FdCacheHelper::Cache(task_path_, fd_[cache_type]);
627 break;
628 case (ProfileAction::RCT_PROCESS):
629 if (!proc_path_.empty()) FdCacheHelper::Cache(proc_path_, fd_[cache_type]);
630 break;
631 default:
632 LOG(ERROR) << "Invalid cache type is specified!";
633 break;
634 }
Rick Yiubc1ad962020-10-26 20:32:52 +0800635}
636
Rick Yiu9221b1e2022-02-10 16:44:43 +0800637void WriteFileAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800638 std::lock_guard<std::mutex> lock(fd_mutex_);
Rick Yiu9221b1e2022-02-10 16:44:43 +0800639 FdCacheHelper::Drop(fd_[cache_type]);
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800640}
641
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000642bool WriteFileAction::IsValidForProcess(uid_t, pid_t) const {
643 std::lock_guard<std::mutex> lock(fd_mutex_);
644 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_PROCESS])) {
645 return true;
646 }
647
648 if (fd_[ProfileAction::RCT_PROCESS] == FdCacheHelper::FDS_INACCESSIBLE) {
649 return false;
650 }
651
652 return access(proc_path_.empty() ? task_path_.c_str() : proc_path_.c_str(), W_OK) == 0;
653}
654
655bool WriteFileAction::IsValidForTask(int) const {
656 std::lock_guard<std::mutex> lock(fd_mutex_);
657 if (FdCacheHelper::IsCached(fd_[ProfileAction::RCT_TASK])) {
658 return true;
659 }
660
661 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_INACCESSIBLE) {
662 return false;
663 }
664
665 if (fd_[ProfileAction::RCT_TASK] == FdCacheHelper::FDS_APP_DEPENDENT) {
666 // application-dependent path can't be used with tid
667 return false;
668 }
669
670 return access(task_path_.c_str(), W_OK) == 0;
671}
672
Rick Yiu0b211fa2019-09-16 19:07:17 +0800673bool ApplyProfileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
674 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800675 profile->ExecuteForProcess(uid, pid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800676 }
677 return true;
678}
679
T.J. Mercier1c007992024-01-25 16:29:54 +0000680bool ApplyProfileAction::ExecuteForTask(pid_t tid) const {
Rick Yiu0b211fa2019-09-16 19:07:17 +0800681 for (const auto& profile : profiles_) {
Wei Wang8722e4d2021-05-14 12:34:54 -0700682 profile->ExecuteForTask(tid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800683 }
684 return true;
685}
686
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800687void ApplyProfileAction::EnableResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800688 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800689 profile->EnableResourceCaching(cache_type);
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800690 }
691}
692
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800693void ApplyProfileAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800694 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800695 profile->DropResourceCaching(cache_type);
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800696 }
697}
698
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000699bool ApplyProfileAction::IsValidForProcess(uid_t uid, pid_t pid) const {
700 for (const auto& profile : profiles_) {
701 if (!profile->IsValidForProcess(uid, pid)) {
702 return false;
703 }
704 }
705 return true;
706}
707
T.J. Mercier1c007992024-01-25 16:29:54 +0000708bool ApplyProfileAction::IsValidForTask(pid_t tid) const {
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000709 for (const auto& profile : profiles_) {
710 if (!profile->IsValidForTask(tid)) {
711 return false;
712 }
713 }
714 return true;
715}
716
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800717void TaskProfile::MoveTo(TaskProfile* profile) {
718 profile->elements_ = std::move(elements_);
719 profile->res_cached_ = res_cached_;
720}
721
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800722bool TaskProfile::ExecuteForProcess(uid_t uid, pid_t pid) const {
723 for (const auto& element : elements_) {
724 if (!element->ExecuteForProcess(uid, pid)) {
Bart Van Asschef096bd22022-01-24 19:59:13 +0000725 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800726 return false;
727 }
728 }
729 return true;
730}
731
T.J. Mercier1c007992024-01-25 16:29:54 +0000732bool TaskProfile::ExecuteForTask(pid_t tid) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800733 if (tid == 0) {
734 tid = GetThreadId();
735 }
736 for (const auto& element : elements_) {
737 if (!element->ExecuteForTask(tid)) {
Bart Van Asschef096bd22022-01-24 19:59:13 +0000738 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800739 return false;
740 }
741 }
742 return true;
743}
744
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +0000745bool TaskProfile::ExecuteForUID(uid_t uid) const {
746 for (const auto& element : elements_) {
747 if (!element->ExecuteForUID(uid)) {
748 LOG(VERBOSE) << "Applying profile action " << element->Name() << " failed";
749 return false;
750 }
751 }
752 return true;
753}
754
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800755void TaskProfile::EnableResourceCaching(ProfileAction::ResourceCacheType cache_type) {
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800756 if (res_cached_) {
757 return;
758 }
759
760 for (auto& element : elements_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800761 element->EnableResourceCaching(cache_type);
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800762 }
763
764 res_cached_ = true;
765}
766
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800767void TaskProfile::DropResourceCaching(ProfileAction::ResourceCacheType cache_type) {
Riddle Hsua6abd822019-06-18 15:53:53 -0600768 if (!res_cached_) {
769 return;
770 }
771
772 for (auto& element : elements_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800773 element->DropResourceCaching(cache_type);
Riddle Hsua6abd822019-06-18 15:53:53 -0600774 }
775
776 res_cached_ = false;
777}
778
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000779bool TaskProfile::IsValidForProcess(uid_t uid, pid_t pid) const {
780 for (const auto& element : elements_) {
781 if (!element->IsValidForProcess(uid, pid)) return false;
782 }
783 return true;
784}
785
T.J. Mercier1c007992024-01-25 16:29:54 +0000786bool TaskProfile::IsValidForTask(pid_t tid) const {
Suren Baghdasaryan8cacb612023-04-12 01:24:23 +0000787 for (const auto& element : elements_) {
788 if (!element->IsValidForTask(tid)) return false;
789 }
790 return true;
791}
792
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800793void TaskProfiles::DropResourceCaching(ProfileAction::ResourceCacheType cache_type) const {
Riddle Hsua6abd822019-06-18 15:53:53 -0600794 for (auto& iter : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800795 iter.second->DropResourceCaching(cache_type);
Riddle Hsua6abd822019-06-18 15:53:53 -0600796 }
797}
798
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800799TaskProfiles& TaskProfiles::GetInstance() {
Peter Collingbournedba6d442019-03-20 21:09:46 -0700800 // Deliberately leak this object to avoid a race between destruction on
801 // process exit and concurrent access from another thread.
802 static auto* instance = new TaskProfiles;
803 return *instance;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800804}
805
806TaskProfiles::TaskProfiles() {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800807 // load system task profiles
808 if (!Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_FILE)) {
809 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_FILE << " for [" << getpid() << "] failed";
810 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800811
812 // load API-level specific system task profiles if available
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800813 unsigned int api_level = GetUintProperty<unsigned int>("ro.product.first_api_level", 0);
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800814 if (api_level > 0) {
815 std::string api_profiles_path =
816 android::base::StringPrintf(TEMPLATE_TASK_PROFILE_API_FILE, api_level);
817 if (!access(api_profiles_path.c_str(), F_OK) || errno != ENOENT) {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800818 if (!Load(CgroupMap::GetInstance(), api_profiles_path)) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800819 LOG(ERROR) << "Loading " << api_profiles_path << " for [" << getpid() << "] failed";
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800820 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800821 }
822 }
823
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800824 // load vendor task profiles if the file exists
825 if (!access(TASK_PROFILE_DB_VENDOR_FILE, F_OK) &&
826 !Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_VENDOR_FILE)) {
827 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_VENDOR_FILE << " for [" << getpid()
828 << "] failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800829 }
830}
831
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800832bool TaskProfiles::Load(const CgroupMap& cg_map, const std::string& file_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800833 std::string json_doc;
834
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800835 if (!android::base::ReadFileToString(file_name, &json_doc)) {
836 LOG(ERROR) << "Failed to read task profiles from " << file_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800837 return false;
838 }
839
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800840 Json::CharReaderBuilder builder;
841 std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800842 Json::Value root;
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800843 std::string errorMessage;
844 if (!reader->parse(&*json_doc.begin(), &*json_doc.end(), &root, &errorMessage)) {
845 LOG(ERROR) << "Failed to parse task profiles: " << errorMessage;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800846 return false;
847 }
848
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800849 const Json::Value& attr = root["Attributes"];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800850 for (Json::Value::ArrayIndex i = 0; i < attr.size(); ++i) {
851 std::string name = attr[i]["Name"].asString();
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800852 std::string controller_name = attr[i]["Controller"].asString();
853 std::string file_attr = attr[i]["File"].asString();
Bart Van Asschebc077ff2022-02-17 01:26:44 +0000854 std::string file_v2_attr = attr[i]["FileV2"].asString();
855
856 if (!file_v2_attr.empty() && file_attr.empty()) {
857 LOG(ERROR) << "Attribute " << name << " has FileV2 but no File property";
858 return false;
859 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800860
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700861 auto controller = cg_map.FindController(controller_name);
862 if (controller.HasValue()) {
863 auto iter = attributes_.find(name);
864 if (iter == attributes_.end()) {
Bart Van Asschebc077ff2022-02-17 01:26:44 +0000865 attributes_[name] =
866 std::make_unique<ProfileAttribute>(controller, file_attr, file_v2_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800867 } else {
Suren Baghdasaryan35078462023-07-25 14:50:18 -0700868 iter->second->Reset(controller, file_attr, file_v2_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800869 }
870 } else {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700871 LOG(WARNING) << "Controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800872 }
873 }
874
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800875 const Json::Value& profiles_val = root["Profiles"];
876 for (Json::Value::ArrayIndex i = 0; i < profiles_val.size(); ++i) {
877 const Json::Value& profile_val = profiles_val[i];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800878
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800879 std::string profile_name = profile_val["Name"].asString();
880 const Json::Value& actions = profile_val["Actions"];
Bart Van Asschef096bd22022-01-24 19:59:13 +0000881 auto profile = std::make_shared<TaskProfile>(profile_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800882
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800883 for (Json::Value::ArrayIndex act_idx = 0; act_idx < actions.size(); ++act_idx) {
884 const Json::Value& action_val = actions[act_idx];
885 std::string action_name = action_val["Name"].asString();
886 const Json::Value& params_val = action_val["Params"];
887 if (action_name == "JoinCgroup") {
888 std::string controller_name = params_val["Controller"].asString();
889 std::string path = params_val["Path"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800890
Yifan Hong53e0deb2019-03-22 17:01:08 -0700891 auto controller = cg_map.FindController(controller_name);
892 if (controller.HasValue()) {
Bart Van Assche2953a922023-11-14 07:33:00 -0800893 if (controller.version() == 1) {
894 profile->Add(std::make_unique<SetCgroupAction>(controller, path));
895 } else {
896 LOG(WARNING) << "A JoinCgroup action in the " << profile_name
897 << " profile is used for controller " << controller_name
898 << " in the cgroup v2 hierarchy and will be ignored";
899 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800900 } else {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800901 LOG(WARNING) << "JoinCgroup: controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800902 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800903 } else if (action_name == "SetTimerSlack") {
904 std::string slack_value = params_val["Slack"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800905 char* end;
906 unsigned long slack;
907
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800908 slack = strtoul(slack_value.c_str(), &end, 10);
909 if (end > slack_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800910 profile->Add(std::make_unique<SetTimerSlackAction>(slack));
911 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800912 LOG(WARNING) << "SetTimerSlack: invalid parameter: " << slack_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800913 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800914 } else if (action_name == "SetAttribute") {
915 std::string attr_name = params_val["Name"].asString();
916 std::string attr_value = params_val["Value"].asString();
Bart Van Assche59af6802022-01-24 21:08:57 +0000917 bool optional = strcmp(params_val["Optional"].asString().c_str(), "true") == 0;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800918
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800919 auto iter = attributes_.find(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800920 if (iter != attributes_.end()) {
Bart Van Assche59af6802022-01-24 21:08:57 +0000921 profile->Add(std::make_unique<SetAttributeAction>(iter->second.get(),
922 attr_value, optional));
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800923 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800924 LOG(WARNING) << "SetAttribute: unknown attribute: " << attr_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800925 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800926 } else if (action_name == "SetClamps") {
927 std::string boost_value = params_val["Boost"].asString();
928 std::string clamp_value = params_val["Clamp"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800929 char* end;
930 unsigned long boost;
931
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800932 boost = strtoul(boost_value.c_str(), &end, 10);
933 if (end > boost_value.c_str()) {
934 unsigned long clamp = strtoul(clamp_value.c_str(), &end, 10);
935 if (end > clamp_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800936 profile->Add(std::make_unique<SetClampsAction>(boost, clamp));
937 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800938 LOG(WARNING) << "SetClamps: invalid parameter " << clamp_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800939 }
940 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800941 LOG(WARNING) << "SetClamps: invalid parameter: " << boost_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800942 }
Rick Yiubc1ad962020-10-26 20:32:52 +0800943 } else if (action_name == "WriteFile") {
944 std::string attr_filepath = params_val["FilePath"].asString();
Rick Yiu9221b1e2022-02-10 16:44:43 +0800945 std::string attr_procfilepath = params_val["ProcFilePath"].asString();
Rick Yiubc1ad962020-10-26 20:32:52 +0800946 std::string attr_value = params_val["Value"].asString();
Rick Yiu9221b1e2022-02-10 16:44:43 +0800947 // FilePath and Value are mandatory
Rick Yiubc1ad962020-10-26 20:32:52 +0800948 if (!attr_filepath.empty() && !attr_value.empty()) {
Rick Yiu49fce952021-04-08 22:10:06 +0800949 std::string attr_logfailures = params_val["LogFailures"].asString();
950 bool logfailures = attr_logfailures.empty() || attr_logfailures == "true";
Rick Yiu9221b1e2022-02-10 16:44:43 +0800951 profile->Add(std::make_unique<WriteFileAction>(attr_filepath, attr_procfilepath,
952 attr_value, logfailures));
Rick Yiubc1ad962020-10-26 20:32:52 +0800953 } else if (attr_filepath.empty()) {
954 LOG(WARNING) << "WriteFile: invalid parameter: "
955 << "empty filepath";
956 } else if (attr_value.empty()) {
957 LOG(WARNING) << "WriteFile: invalid parameter: "
958 << "empty value";
959 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800960 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800961 LOG(WARNING) << "Unknown profile action: " << action_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800962 }
963 }
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800964 auto iter = profiles_.find(profile_name);
965 if (iter == profiles_.end()) {
966 profiles_[profile_name] = profile;
967 } else {
968 // Move the content rather that replace the profile because old profile might be
969 // referenced from an aggregate profile if vendor overrides task profiles
970 profile->MoveTo(iter->second.get());
971 profile.reset();
972 }
Rick Yiu0b211fa2019-09-16 19:07:17 +0800973 }
974
975 const Json::Value& aggregateprofiles_val = root["AggregateProfiles"];
976 for (Json::Value::ArrayIndex i = 0; i < aggregateprofiles_val.size(); ++i) {
977 const Json::Value& aggregateprofile_val = aggregateprofiles_val[i];
978
979 std::string aggregateprofile_name = aggregateprofile_val["Name"].asString();
980 const Json::Value& aggregateprofiles = aggregateprofile_val["Profiles"];
981 std::vector<std::shared_ptr<TaskProfile>> profiles;
982 bool ret = true;
983
984 for (Json::Value::ArrayIndex pf_idx = 0; pf_idx < aggregateprofiles.size(); ++pf_idx) {
985 std::string profile_name = aggregateprofiles[pf_idx].asString();
986
987 if (profile_name == aggregateprofile_name) {
988 LOG(WARNING) << "AggregateProfiles: recursive profile name: " << profile_name;
989 ret = false;
990 break;
991 } else if (profiles_.find(profile_name) == profiles_.end()) {
992 LOG(WARNING) << "AggregateProfiles: undefined profile name: " << profile_name;
993 ret = false;
994 break;
995 } else {
996 profiles.push_back(profiles_[profile_name]);
997 }
998 }
999 if (ret) {
Bart Van Asschef096bd22022-01-24 19:59:13 +00001000 auto profile = std::make_shared<TaskProfile>(aggregateprofile_name);
Rick Yiu0b211fa2019-09-16 19:07:17 +08001001 profile->Add(std::make_unique<ApplyProfileAction>(profiles));
1002 profiles_[aggregateprofile_name] = profile;
1003 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -08001004 }
1005
1006 return true;
1007}
1008
Bart Van Assched0b8ce22022-08-02 13:06:26 -07001009TaskProfile* TaskProfiles::GetProfile(std::string_view name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -08001010 auto iter = profiles_.find(name);
1011
1012 if (iter != profiles_.end()) {
1013 return iter->second.get();
1014 }
1015 return nullptr;
1016}
1017
Bart Van Assched0b8ce22022-08-02 13:06:26 -07001018const IProfileAttribute* TaskProfiles::GetAttribute(std::string_view name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -08001019 auto iter = attributes_.find(name);
1020
1021 if (iter != attributes_.end()) {
1022 return iter->second.get();
1023 }
1024 return nullptr;
1025}
Rick Yiu0b211fa2019-09-16 19:07:17 +08001026
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001027template <typename T>
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +00001028bool TaskProfiles::SetUserProfiles(uid_t uid, std::span<const T> profiles, bool use_fd_cache) {
1029 for (const auto& name : profiles) {
1030 TaskProfile* profile = GetProfile(name);
1031 if (profile != nullptr) {
1032 if (use_fd_cache) {
1033 profile->EnableResourceCaching(ProfileAction::RCT_PROCESS);
1034 }
1035 if (!profile->ExecuteForUID(uid)) {
1036 PLOG(WARNING) << "Failed to apply " << name << " process profile";
1037 }
1038 } else {
1039 PLOG(WARNING) << "Failed to find " << name << "process profile";
1040 }
1041 }
1042 return true;
1043}
1044
1045template <typename T>
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001046bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid, std::span<const T> profiles,
1047 bool use_fd_cache) {
Inseob Kim538fc1f2022-04-13 18:50:12 +00001048 bool success = true;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001049 for (const auto& name : profiles) {
1050 TaskProfile* profile = GetProfile(name);
1051 if (profile != nullptr) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -08001052 if (use_fd_cache) {
1053 profile->EnableResourceCaching(ProfileAction::RCT_PROCESS);
1054 }
Rick Yiu0b211fa2019-09-16 19:07:17 +08001055 if (!profile->ExecuteForProcess(uid, pid)) {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001056 LOG(WARNING) << "Failed to apply " << name << " process profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001057 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001058 }
1059 } else {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001060 LOG(WARNING) << "Failed to find " << name << " process profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001061 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001062 }
1063 }
Inseob Kim538fc1f2022-04-13 18:50:12 +00001064 return success;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001065}
1066
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001067template <typename T>
T.J. Mercier1c007992024-01-25 16:29:54 +00001068bool TaskProfiles::SetTaskProfiles(pid_t tid, std::span<const T> profiles, bool use_fd_cache) {
Inseob Kim538fc1f2022-04-13 18:50:12 +00001069 bool success = true;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001070 for (const auto& name : profiles) {
1071 TaskProfile* profile = GetProfile(name);
1072 if (profile != nullptr) {
1073 if (use_fd_cache) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -08001074 profile->EnableResourceCaching(ProfileAction::RCT_TASK);
Rick Yiu0b211fa2019-09-16 19:07:17 +08001075 }
1076 if (!profile->ExecuteForTask(tid)) {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001077 LOG(WARNING) << "Failed to apply " << name << " task profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001078 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001079 }
1080 } else {
Krzysztof Kosiński0310ec42023-03-01 04:17:57 +00001081 LOG(WARNING) << "Failed to find " << name << " task profile";
Inseob Kim538fc1f2022-04-13 18:50:12 +00001082 success = false;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001083 }
1084 }
Inseob Kim538fc1f2022-04-13 18:50:12 +00001085 return success;
Rick Yiu0b211fa2019-09-16 19:07:17 +08001086}
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001087
1088template bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
1089 std::span<const std::string> profiles,
1090 bool use_fd_cache);
1091template bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
1092 std::span<const std::string_view> profiles,
1093 bool use_fd_cache);
T.J. Mercier1c007992024-01-25 16:29:54 +00001094template bool TaskProfiles::SetTaskProfiles(pid_t tid, std::span<const std::string> profiles,
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001095 bool use_fd_cache);
T.J. Mercier1c007992024-01-25 16:29:54 +00001096template bool TaskProfiles::SetTaskProfiles(pid_t tid, std::span<const std::string_view> profiles,
Bart Van Asschef32c4ec2022-08-02 13:18:12 -07001097 bool use_fd_cache);
T.J. Mercier5ed5e1b2022-08-22 21:25:09 +00001098template bool TaskProfiles::SetUserProfiles(uid_t uid, std::span<const std::string> profiles,
1099 bool use_fd_cache);