blob: 40d8d902c4d654da0f2ae7462bc7581deead4ac1 [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>
26#include <android-base/stringprintf.h>
27#include <android-base/threads.h>
28
29#include <cutils/android_filesystem_config.h>
30
31#include <json/reader.h>
32#include <json/value.h>
33
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -080034// To avoid issues in sdk_mac build
35#if defined(__ANDROID__)
36#include <sys/prctl.h>
37#endif
38
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080039using android::base::GetThreadId;
40using android::base::StringPrintf;
41using android::base::unique_fd;
42using android::base::WriteStringToFile;
43
44#define TASK_PROFILE_DB_FILE "/etc/task_profiles.json"
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -080045#define TASK_PROFILE_DB_VENDOR_FILE "/vendor/etc/task_profiles.json"
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080046
47bool ProfileAttribute::GetPathForTask(int tid, std::string* path) const {
48 std::string subgroup;
Yifan Hong53e0deb2019-03-22 17:01:08 -070049 if (!controller()->GetTaskGroup(tid, &subgroup)) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080050 return false;
51 }
52
53 if (path == nullptr) {
54 return true;
55 }
56
57 if (subgroup.empty()) {
Yifan Hong53e0deb2019-03-22 17:01:08 -070058 *path = StringPrintf("%s/%s", controller()->path(), file_name_.c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080059 } else {
Yifan Hong53e0deb2019-03-22 17:01:08 -070060 *path = StringPrintf("%s/%s/%s", controller()->path(), subgroup.c_str(),
61 file_name_.c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080062 }
63 return true;
64}
65
66bool SetClampsAction::ExecuteForProcess(uid_t, pid_t) const {
67 // TODO: add support when kernel supports util_clamp
68 LOG(WARNING) << "SetClampsAction::ExecuteForProcess is not supported";
69 return false;
70}
71
72bool SetClampsAction::ExecuteForTask(int) const {
73 // TODO: add support when kernel supports util_clamp
74 LOG(WARNING) << "SetClampsAction::ExecuteForTask is not supported";
75 return false;
76}
77
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -080078// To avoid issues in sdk_mac build
79#if defined(__ANDROID__)
80
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080081bool SetTimerSlackAction::IsTimerSlackSupported(int tid) {
82 auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
83
84 return (access(file.c_str(), W_OK) == 0);
85}
86
87bool SetTimerSlackAction::ExecuteForTask(int tid) const {
88 static bool sys_supports_timerslack = IsTimerSlackSupported(tid);
89
90 // v4.6+ kernels support the /proc/<tid>/timerslack_ns interface.
91 // TODO: once we've backported this, log if the open(2) fails.
92 if (sys_supports_timerslack) {
93 auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
94 if (!WriteStringToFile(std::to_string(slack_), file)) {
Suren Baghdasaryan2bc52282019-02-12 17:30:26 -080095 if (errno == ENOENT) {
96 // This happens when process is already dead
97 return true;
98 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080099 PLOG(ERROR) << "set_timerslack_ns write failed";
100 }
101 }
102
103 // TODO: Remove when /proc/<tid>/timerslack_ns interface is backported.
104 if (tid == 0 || tid == GetThreadId()) {
105 if (prctl(PR_SET_TIMERSLACK, slack_) == -1) {
106 PLOG(ERROR) << "set_timerslack_ns prctl failed";
107 }
108 }
109
110 return true;
111}
112
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -0800113#endif
114
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800115bool SetAttributeAction::ExecuteForProcess(uid_t, pid_t pid) const {
116 return ExecuteForTask(pid);
117}
118
119bool SetAttributeAction::ExecuteForTask(int tid) const {
120 std::string path;
121
122 if (!attribute_->GetPathForTask(tid, &path)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800123 LOG(ERROR) << "Failed to find cgroup for tid " << tid;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800124 return false;
125 }
126
127 if (!WriteStringToFile(value_, path)) {
128 PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
129 return false;
130 }
131
132 return true;
133}
134
135bool SetCgroupAction::IsAppDependentPath(const std::string& path) {
136 return path.find("<uid>", 0) != std::string::npos || path.find("<pid>", 0) != std::string::npos;
137}
138
Yifan Hong53e0deb2019-03-22 17:01:08 -0700139SetCgroupAction::SetCgroupAction(const CgroupController& c, const std::string& p)
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800140 : controller_(c), path_(p) {
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800141 // file descriptors for app-dependent paths can't be cached
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800142 if (IsAppDependentPath(path_)) {
143 // file descriptor is not cached
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800144 fd_.reset(FDS_APP_DEPENDENT);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800145 return;
146 }
147
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800148 // file descriptor can be cached later on request
149 fd_.reset(FDS_NOT_CACHED);
150}
151
152void SetCgroupAction::EnableResourceCaching() {
153 if (fd_ != FDS_NOT_CACHED) {
154 return;
155 }
156
157 std::string tasks_path = controller_.GetTasksFilePath(path_);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800158
159 if (access(tasks_path.c_str(), W_OK) != 0) {
160 // file is not accessible
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800161 fd_.reset(FDS_INACCESSIBLE);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800162 return;
163 }
164
165 unique_fd fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
166 if (fd < 0) {
167 PLOG(ERROR) << "Failed to cache fd '" << tasks_path << "'";
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800168 fd_.reset(FDS_INACCESSIBLE);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800169 return;
170 }
171
172 fd_ = std::move(fd);
173}
174
175bool SetCgroupAction::AddTidToCgroup(int tid, int fd) {
176 if (tid <= 0) {
177 return true;
178 }
179
180 std::string value = std::to_string(tid);
181
182 if (TEMP_FAILURE_RETRY(write(fd, value.c_str(), value.length())) < 0) {
183 // If the thread is in the process of exiting, don't flag an error
184 if (errno != ESRCH) {
Wei Wangd71d3012019-03-07 11:59:12 -0800185 PLOG(ERROR) << "AddTidToCgroup failed to write '" << value << "'; fd=" << fd;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800186 return false;
187 }
188 }
189
190 return true;
191}
192
193bool SetCgroupAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800194 if (IsFdValid()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800195 // fd is cached, reuse it
196 if (!AddTidToCgroup(pid, fd_)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800197 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800198 return false;
199 }
200 return true;
201 }
202
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800203 if (fd_ == FDS_INACCESSIBLE) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800204 // no permissions to access the file, ignore
205 return true;
206 }
207
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800208 // this is app-dependent path and fd is not cached or cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700209 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800210 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(procs_path.c_str(), O_WRONLY | O_CLOEXEC)));
211 if (tmp_fd < 0) {
Elliott Hughes08b4d322019-03-14 20:06:36 -0700212 PLOG(WARNING) << "Failed to open " << procs_path;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800213 return false;
214 }
215 if (!AddTidToCgroup(pid, tmp_fd)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800216 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800217 return false;
218 }
219
220 return true;
221}
222
223bool SetCgroupAction::ExecuteForTask(int tid) const {
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800224 if (IsFdValid()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800225 // fd is cached, reuse it
226 if (!AddTidToCgroup(tid, fd_)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800227 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800228 return false;
229 }
230 return true;
231 }
232
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800233 if (fd_ == FDS_INACCESSIBLE) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800234 // no permissions to access the file, ignore
235 return true;
236 }
237
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800238 if (fd_ == FDS_APP_DEPENDENT) {
239 // application-dependent path can't be used with tid
240 PLOG(ERROR) << "Application profile can't be applied to a thread";
241 return false;
242 }
243
244 // fd was not cached because cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700245 std::string tasks_path = controller()->GetTasksFilePath(path_);
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800246 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
247 if (tmp_fd < 0) {
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800248 PLOG(WARNING) << "Failed to open " << tasks_path << ": " << strerror(errno);
249 return false;
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800250 }
251 if (!AddTidToCgroup(tid, tmp_fd)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800252 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800253 return false;
254 }
255
256 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800257}
258
259bool TaskProfile::ExecuteForProcess(uid_t uid, pid_t pid) const {
260 for (const auto& element : elements_) {
261 if (!element->ExecuteForProcess(uid, pid)) {
262 return false;
263 }
264 }
265 return true;
266}
267
268bool TaskProfile::ExecuteForTask(int tid) const {
269 if (tid == 0) {
270 tid = GetThreadId();
271 }
272 for (const auto& element : elements_) {
273 if (!element->ExecuteForTask(tid)) {
274 return false;
275 }
276 }
277 return true;
278}
279
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800280void TaskProfile::EnableResourceCaching() {
281 if (res_cached_) {
282 return;
283 }
284
285 for (auto& element : elements_) {
286 element->EnableResourceCaching();
287 }
288
289 res_cached_ = true;
290}
291
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800292TaskProfiles& TaskProfiles::GetInstance() {
Peter Collingbournedba6d442019-03-20 21:09:46 -0700293 // Deliberately leak this object to avoid a race between destruction on
294 // process exit and concurrent access from another thread.
295 static auto* instance = new TaskProfiles;
296 return *instance;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800297}
298
299TaskProfiles::TaskProfiles() {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800300 // load system task profiles
301 if (!Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_FILE)) {
302 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_FILE << " for [" << getpid() << "] failed";
303 }
304
305 // load vendor task profiles if the file exists
306 if (!access(TASK_PROFILE_DB_VENDOR_FILE, F_OK) &&
307 !Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_VENDOR_FILE)) {
308 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_VENDOR_FILE << " for [" << getpid()
309 << "] failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800310 }
311}
312
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800313bool TaskProfiles::Load(const CgroupMap& cg_map, const std::string& file_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800314 std::string json_doc;
315
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800316 if (!android::base::ReadFileToString(file_name, &json_doc)) {
317 LOG(ERROR) << "Failed to read task profiles from " << file_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800318 return false;
319 }
320
321 Json::Reader reader;
322 Json::Value root;
323 if (!reader.parse(json_doc, root)) {
324 LOG(ERROR) << "Failed to parse task profiles: " << reader.getFormattedErrorMessages();
325 return false;
326 }
327
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800328 const Json::Value& attr = root["Attributes"];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800329 for (Json::Value::ArrayIndex i = 0; i < attr.size(); ++i) {
330 std::string name = attr[i]["Name"].asString();
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800331 std::string controller_name = attr[i]["Controller"].asString();
332 std::string file_attr = attr[i]["File"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800333
334 if (attributes_.find(name) == attributes_.end()) {
Yifan Hong53e0deb2019-03-22 17:01:08 -0700335 auto controller = cg_map.FindController(controller_name);
336 if (controller.HasValue()) {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800337 attributes_[name] = std::make_unique<ProfileAttribute>(controller, file_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800338 } else {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800339 LOG(WARNING) << "Controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800340 }
341 } else {
342 LOG(WARNING) << "Attribute " << name << " is already defined";
343 }
344 }
345
346 std::map<std::string, std::string> params;
347
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800348 const Json::Value& profiles_val = root["Profiles"];
349 for (Json::Value::ArrayIndex i = 0; i < profiles_val.size(); ++i) {
350 const Json::Value& profile_val = profiles_val[i];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800351
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800352 std::string profile_name = profile_val["Name"].asString();
353 const Json::Value& actions = profile_val["Actions"];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800354 auto profile = std::make_unique<TaskProfile>();
355
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800356 for (Json::Value::ArrayIndex act_idx = 0; act_idx < actions.size(); ++act_idx) {
357 const Json::Value& action_val = actions[act_idx];
358 std::string action_name = action_val["Name"].asString();
359 const Json::Value& params_val = action_val["Params"];
360 if (action_name == "JoinCgroup") {
361 std::string controller_name = params_val["Controller"].asString();
362 std::string path = params_val["Path"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800363
Yifan Hong53e0deb2019-03-22 17:01:08 -0700364 auto controller = cg_map.FindController(controller_name);
365 if (controller.HasValue()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800366 profile->Add(std::make_unique<SetCgroupAction>(controller, path));
367 } else {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800368 LOG(WARNING) << "JoinCgroup: controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800369 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800370 } else if (action_name == "SetTimerSlack") {
371 std::string slack_value = params_val["Slack"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800372 char* end;
373 unsigned long slack;
374
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800375 slack = strtoul(slack_value.c_str(), &end, 10);
376 if (end > slack_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800377 profile->Add(std::make_unique<SetTimerSlackAction>(slack));
378 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800379 LOG(WARNING) << "SetTimerSlack: invalid parameter: " << slack_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800380 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800381 } else if (action_name == "SetAttribute") {
382 std::string attr_name = params_val["Name"].asString();
383 std::string attr_value = params_val["Value"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800384
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800385 auto iter = attributes_.find(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800386 if (iter != attributes_.end()) {
387 profile->Add(
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800388 std::make_unique<SetAttributeAction>(iter->second.get(), attr_value));
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800389 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800390 LOG(WARNING) << "SetAttribute: unknown attribute: " << attr_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800391 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800392 } else if (action_name == "SetClamps") {
393 std::string boost_value = params_val["Boost"].asString();
394 std::string clamp_value = params_val["Clamp"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800395 char* end;
396 unsigned long boost;
397
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800398 boost = strtoul(boost_value.c_str(), &end, 10);
399 if (end > boost_value.c_str()) {
400 unsigned long clamp = strtoul(clamp_value.c_str(), &end, 10);
401 if (end > clamp_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800402 profile->Add(std::make_unique<SetClampsAction>(boost, clamp));
403 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800404 LOG(WARNING) << "SetClamps: invalid parameter " << clamp_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800405 }
406 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800407 LOG(WARNING) << "SetClamps: invalid parameter: " << boost_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800408 }
409 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800410 LOG(WARNING) << "Unknown profile action: " << action_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800411 }
412 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800413 profiles_[profile_name] = std::move(profile);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800414 }
415
416 return true;
417}
418
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800419TaskProfile* TaskProfiles::GetProfile(const std::string& name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800420 auto iter = profiles_.find(name);
421
422 if (iter != profiles_.end()) {
423 return iter->second.get();
424 }
425 return nullptr;
426}
427
428const ProfileAttribute* TaskProfiles::GetAttribute(const std::string& name) const {
429 auto iter = attributes_.find(name);
430
431 if (iter != attributes_.end()) {
432 return iter->second.get();
433 }
434 return nullptr;
435}