blob: 0bc19df6ac8a3b8bcd860e14122f00aaa52fe1f7 [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;
49 if (!controller_->GetTaskGroup(tid, &subgroup)) {
50 return false;
51 }
52
53 if (path == nullptr) {
54 return true;
55 }
56
57 if (subgroup.empty()) {
58 *path = StringPrintf("%s/%s", controller_->path(), file_name_.c_str());
59 } else {
60 *path = StringPrintf("%s/%s/%s", controller_->path(), subgroup.c_str(), file_name_.c_str());
61 }
62 return true;
63}
64
65bool SetClampsAction::ExecuteForProcess(uid_t, pid_t) const {
66 // TODO: add support when kernel supports util_clamp
67 LOG(WARNING) << "SetClampsAction::ExecuteForProcess is not supported";
68 return false;
69}
70
71bool SetClampsAction::ExecuteForTask(int) const {
72 // TODO: add support when kernel supports util_clamp
73 LOG(WARNING) << "SetClampsAction::ExecuteForTask is not supported";
74 return false;
75}
76
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -080077// To avoid issues in sdk_mac build
78#if defined(__ANDROID__)
79
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080080bool SetTimerSlackAction::IsTimerSlackSupported(int tid) {
81 auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
82
83 return (access(file.c_str(), W_OK) == 0);
84}
85
86bool SetTimerSlackAction::ExecuteForTask(int tid) const {
87 static bool sys_supports_timerslack = IsTimerSlackSupported(tid);
88
89 // v4.6+ kernels support the /proc/<tid>/timerslack_ns interface.
90 // TODO: once we've backported this, log if the open(2) fails.
91 if (sys_supports_timerslack) {
92 auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
93 if (!WriteStringToFile(std::to_string(slack_), file)) {
Suren Baghdasaryan2bc52282019-02-12 17:30:26 -080094 if (errno == ENOENT) {
95 // This happens when process is already dead
96 return true;
97 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080098 PLOG(ERROR) << "set_timerslack_ns write failed";
99 }
100 }
101
102 // TODO: Remove when /proc/<tid>/timerslack_ns interface is backported.
103 if (tid == 0 || tid == GetThreadId()) {
104 if (prctl(PR_SET_TIMERSLACK, slack_) == -1) {
105 PLOG(ERROR) << "set_timerslack_ns prctl failed";
106 }
107 }
108
109 return true;
110}
111
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -0800112#endif
113
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800114bool SetAttributeAction::ExecuteForProcess(uid_t, pid_t pid) const {
115 return ExecuteForTask(pid);
116}
117
118bool SetAttributeAction::ExecuteForTask(int tid) const {
119 std::string path;
120
121 if (!attribute_->GetPathForTask(tid, &path)) {
122 PLOG(ERROR) << "Failed to find cgroup for tid " << tid;
123 return false;
124 }
125
126 if (!WriteStringToFile(value_, path)) {
127 PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
128 return false;
129 }
130
131 return true;
132}
133
134bool SetCgroupAction::IsAppDependentPath(const std::string& path) {
135 return path.find("<uid>", 0) != std::string::npos || path.find("<pid>", 0) != std::string::npos;
136}
137
138SetCgroupAction::SetCgroupAction(const CgroupController* c, const std::string& p)
139 : controller_(c), path_(p) {
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800140#ifdef CACHE_FILE_DESCRIPTORS
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800141 // cache file descriptor only if path is app independent
142 if (IsAppDependentPath(path_)) {
143 // file descriptor is not cached
144 fd_.reset(-2);
145 return;
146 }
147
148 std::string tasks_path = c->GetTasksFilePath(p.c_str());
149
150 if (access(tasks_path.c_str(), W_OK) != 0) {
151 // file is not accessible
152 fd_.reset(-1);
153 return;
154 }
155
156 unique_fd fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
157 if (fd < 0) {
158 PLOG(ERROR) << "Failed to cache fd '" << tasks_path << "'";
159 fd_.reset(-1);
160 return;
161 }
162
163 fd_ = std::move(fd);
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800164#endif
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800165}
166
167bool SetCgroupAction::AddTidToCgroup(int tid, int fd) {
168 if (tid <= 0) {
169 return true;
170 }
171
172 std::string value = std::to_string(tid);
173
174 if (TEMP_FAILURE_RETRY(write(fd, value.c_str(), value.length())) < 0) {
175 // If the thread is in the process of exiting, don't flag an error
176 if (errno != ESRCH) {
177 PLOG(ERROR) << "JoinGroup failed to write '" << value << "'; fd=" << fd;
178 return false;
179 }
180 }
181
182 return true;
183}
184
185bool SetCgroupAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800186#ifdef CACHE_FILE_DESCRIPTORS
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800187 if (fd_ >= 0) {
188 // fd is cached, reuse it
189 if (!AddTidToCgroup(pid, fd_)) {
190 PLOG(ERROR) << "Failed to add task into cgroup";
191 return false;
192 }
193 return true;
194 }
195
196 if (fd_ == -1) {
197 // no permissions to access the file, ignore
198 return true;
199 }
200
201 // this is app-dependent path, file descriptor is not cached
Wei Wang17705662019-02-26 14:43:51 -0800202 std::string procs_path = controller_->GetProcsFilePath(path_, uid, pid);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800203 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(procs_path.c_str(), O_WRONLY | O_CLOEXEC)));
204 if (tmp_fd < 0) {
205 PLOG(WARNING) << "Failed to open " << procs_path << ": " << strerror(errno);
206 return false;
207 }
208 if (!AddTidToCgroup(pid, tmp_fd)) {
209 PLOG(ERROR) << "Failed to add task into cgroup";
210 return false;
211 }
212
213 return true;
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800214#else
Wei Wang17705662019-02-26 14:43:51 -0800215 std::string procs_path = controller_->GetProcsFilePath(path_, uid, pid);
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800216 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(procs_path.c_str(), O_WRONLY | O_CLOEXEC)));
217 if (tmp_fd < 0) {
218 // no permissions to access the file, ignore
219 return true;
220 }
221 if (!AddTidToCgroup(pid, tmp_fd)) {
222 PLOG(ERROR) << "Failed to add task into cgroup";
223 return false;
224 }
225
226 return true;
227#endif
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800228}
229
230bool SetCgroupAction::ExecuteForTask(int tid) const {
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800231#ifdef CACHE_FILE_DESCRIPTORS
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800232 if (fd_ >= 0) {
233 // fd is cached, reuse it
234 if (!AddTidToCgroup(tid, fd_)) {
235 PLOG(ERROR) << "Failed to add task into cgroup";
236 return false;
237 }
238 return true;
239 }
240
241 if (fd_ == -1) {
242 // no permissions to access the file, ignore
243 return true;
244 }
245
246 // application-dependent path can't be used with tid
247 PLOG(ERROR) << "Application profile can't be applied to a thread";
248 return false;
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800249#else
Wei Wang17705662019-02-26 14:43:51 -0800250 std::string tasks_path = controller_->GetTasksFilePath(path_);
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800251 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
252 if (tmp_fd < 0) {
253 // no permissions to access the file, ignore
254 return true;
255 }
256 if (!AddTidToCgroup(tid, tmp_fd)) {
257 PLOG(ERROR) << "Failed to add task into cgroup";
258 return false;
259 }
260
261 return true;
262#endif
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800263}
264
265bool TaskProfile::ExecuteForProcess(uid_t uid, pid_t pid) const {
266 for (const auto& element : elements_) {
267 if (!element->ExecuteForProcess(uid, pid)) {
268 return false;
269 }
270 }
271 return true;
272}
273
274bool TaskProfile::ExecuteForTask(int tid) const {
275 if (tid == 0) {
276 tid = GetThreadId();
277 }
278 for (const auto& element : elements_) {
279 if (!element->ExecuteForTask(tid)) {
280 return false;
281 }
282 }
283 return true;
284}
285
286TaskProfiles& TaskProfiles::GetInstance() {
287 static TaskProfiles instance;
288 return instance;
289}
290
291TaskProfiles::TaskProfiles() {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800292 // load system task profiles
293 if (!Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_FILE)) {
294 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_FILE << " for [" << getpid() << "] failed";
295 }
296
297 // load vendor task profiles if the file exists
298 if (!access(TASK_PROFILE_DB_VENDOR_FILE, F_OK) &&
299 !Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_VENDOR_FILE)) {
300 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_VENDOR_FILE << " for [" << getpid()
301 << "] failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800302 }
303}
304
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800305bool TaskProfiles::Load(const CgroupMap& cg_map, const std::string& file_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800306 std::string json_doc;
307
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800308 if (!android::base::ReadFileToString(file_name, &json_doc)) {
309 LOG(ERROR) << "Failed to read task profiles from " << file_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800310 return false;
311 }
312
313 Json::Reader reader;
314 Json::Value root;
315 if (!reader.parse(json_doc, root)) {
316 LOG(ERROR) << "Failed to parse task profiles: " << reader.getFormattedErrorMessages();
317 return false;
318 }
319
320 Json::Value attr = root["Attributes"];
321 for (Json::Value::ArrayIndex i = 0; i < attr.size(); ++i) {
322 std::string name = attr[i]["Name"].asString();
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800323 std::string controller_name = attr[i]["Controller"].asString();
324 std::string file_attr = attr[i]["File"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800325
326 if (attributes_.find(name) == attributes_.end()) {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800327 const CgroupController* controller = cg_map.FindController(controller_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800328 if (controller) {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800329 attributes_[name] = std::make_unique<ProfileAttribute>(controller, file_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800330 } else {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800331 LOG(WARNING) << "Controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800332 }
333 } else {
334 LOG(WARNING) << "Attribute " << name << " is already defined";
335 }
336 }
337
338 std::map<std::string, std::string> params;
339
340 Json::Value profilesVal = root["Profiles"];
341 for (Json::Value::ArrayIndex i = 0; i < profilesVal.size(); ++i) {
342 Json::Value profileVal = profilesVal[i];
343
344 std::string profileName = profileVal["Name"].asString();
345 Json::Value actions = profileVal["Actions"];
346 auto profile = std::make_unique<TaskProfile>();
347
348 for (Json::Value::ArrayIndex actIdx = 0; actIdx < actions.size(); ++actIdx) {
349 Json::Value actionVal = actions[actIdx];
350 std::string actionName = actionVal["Name"].asString();
351 Json::Value paramsVal = actionVal["Params"];
352 if (actionName == "JoinCgroup") {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800353 std::string controller_name = paramsVal["Controller"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800354 std::string path = paramsVal["Path"].asString();
355
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800356 const CgroupController* controller = cg_map.FindController(controller_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800357 if (controller) {
358 profile->Add(std::make_unique<SetCgroupAction>(controller, path));
359 } else {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800360 LOG(WARNING) << "JoinCgroup: controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800361 }
362 } else if (actionName == "SetTimerSlack") {
363 std::string slackValue = paramsVal["Slack"].asString();
364 char* end;
365 unsigned long slack;
366
367 slack = strtoul(slackValue.c_str(), &end, 10);
368 if (end > slackValue.c_str()) {
369 profile->Add(std::make_unique<SetTimerSlackAction>(slack));
370 } else {
371 LOG(WARNING) << "SetTimerSlack: invalid parameter: " << slackValue;
372 }
373 } else if (actionName == "SetAttribute") {
374 std::string attrName = paramsVal["Name"].asString();
375 std::string attrValue = paramsVal["Value"].asString();
376
377 auto iter = attributes_.find(attrName);
378 if (iter != attributes_.end()) {
379 profile->Add(
380 std::make_unique<SetAttributeAction>(iter->second.get(), attrValue));
381 } else {
382 LOG(WARNING) << "SetAttribute: unknown attribute: " << attrName;
383 }
384 } else if (actionName == "SetClamps") {
385 std::string boostValue = paramsVal["Boost"].asString();
386 std::string clampValue = paramsVal["Clamp"].asString();
387 char* end;
388 unsigned long boost;
389
390 boost = strtoul(boostValue.c_str(), &end, 10);
391 if (end > boostValue.c_str()) {
392 unsigned long clamp = strtoul(clampValue.c_str(), &end, 10);
393 if (end > clampValue.c_str()) {
394 profile->Add(std::make_unique<SetClampsAction>(boost, clamp));
395 } else {
396 LOG(WARNING) << "SetClamps: invalid parameter " << clampValue;
397 }
398 } else {
399 LOG(WARNING) << "SetClamps: invalid parameter: " << boostValue;
400 }
401 } else {
402 LOG(WARNING) << "Unknown profile action: " << actionName;
403 }
404 }
405 profiles_[profileName] = std::move(profile);
406 }
407
408 return true;
409}
410
411const TaskProfile* TaskProfiles::GetProfile(const std::string& name) const {
412 auto iter = profiles_.find(name);
413
414 if (iter != profiles_.end()) {
415 return iter->second.get();
416 }
417 return nullptr;
418}
419
420const ProfileAttribute* TaskProfiles::GetAttribute(const std::string& name) const {
421 auto iter = attributes_.find(name);
422
423 if (iter != attributes_.end()) {
424 return iter->second.get();
425 }
426 return nullptr;
427}