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