blob: ec6cbbc4510e3ca67f7e6e06a3dc1be9175b6c35 [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)) {
93 PLOG(ERROR) << "set_timerslack_ns write failed";
94 }
95 }
96
97 // TODO: Remove when /proc/<tid>/timerslack_ns interface is backported.
98 if (tid == 0 || tid == GetThreadId()) {
99 if (prctl(PR_SET_TIMERSLACK, slack_) == -1) {
100 PLOG(ERROR) << "set_timerslack_ns prctl failed";
101 }
102 }
103
104 return true;
105}
106
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -0800107#endif
108
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800109bool SetAttributeAction::ExecuteForProcess(uid_t, pid_t pid) const {
110 return ExecuteForTask(pid);
111}
112
113bool SetAttributeAction::ExecuteForTask(int tid) const {
114 std::string path;
115
116 if (!attribute_->GetPathForTask(tid, &path)) {
117 PLOG(ERROR) << "Failed to find cgroup for tid " << tid;
118 return false;
119 }
120
121 if (!WriteStringToFile(value_, path)) {
122 PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
123 return false;
124 }
125
126 return true;
127}
128
129bool SetCgroupAction::IsAppDependentPath(const std::string& path) {
130 return path.find("<uid>", 0) != std::string::npos || path.find("<pid>", 0) != std::string::npos;
131}
132
133SetCgroupAction::SetCgroupAction(const CgroupController* c, const std::string& p)
134 : controller_(c), path_(p) {
135 // cache file descriptor only if path is app independent
136 if (IsAppDependentPath(path_)) {
137 // file descriptor is not cached
138 fd_.reset(-2);
139 return;
140 }
141
142 std::string tasks_path = c->GetTasksFilePath(p.c_str());
143
144 if (access(tasks_path.c_str(), W_OK) != 0) {
145 // file is not accessible
146 fd_.reset(-1);
147 return;
148 }
149
150 unique_fd fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
151 if (fd < 0) {
152 PLOG(ERROR) << "Failed to cache fd '" << tasks_path << "'";
153 fd_.reset(-1);
154 return;
155 }
156
157 fd_ = std::move(fd);
158}
159
160bool SetCgroupAction::AddTidToCgroup(int tid, int fd) {
161 if (tid <= 0) {
162 return true;
163 }
164
165 std::string value = std::to_string(tid);
166
167 if (TEMP_FAILURE_RETRY(write(fd, value.c_str(), value.length())) < 0) {
168 // If the thread is in the process of exiting, don't flag an error
169 if (errno != ESRCH) {
170 PLOG(ERROR) << "JoinGroup failed to write '" << value << "'; fd=" << fd;
171 return false;
172 }
173 }
174
175 return true;
176}
177
178bool SetCgroupAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
179 if (fd_ >= 0) {
180 // fd is cached, reuse it
181 if (!AddTidToCgroup(pid, fd_)) {
182 PLOG(ERROR) << "Failed to add task into cgroup";
183 return false;
184 }
185 return true;
186 }
187
188 if (fd_ == -1) {
189 // no permissions to access the file, ignore
190 return true;
191 }
192
193 // this is app-dependent path, file descriptor is not cached
194 std::string procs_path = controller_->GetProcsFilePath(path_.c_str(), uid, pid);
195 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(procs_path.c_str(), O_WRONLY | O_CLOEXEC)));
196 if (tmp_fd < 0) {
197 PLOG(WARNING) << "Failed to open " << procs_path << ": " << strerror(errno);
198 return false;
199 }
200 if (!AddTidToCgroup(pid, tmp_fd)) {
201 PLOG(ERROR) << "Failed to add task into cgroup";
202 return false;
203 }
204
205 return true;
206}
207
208bool SetCgroupAction::ExecuteForTask(int tid) const {
209 if (fd_ >= 0) {
210 // fd is cached, reuse it
211 if (!AddTidToCgroup(tid, fd_)) {
212 PLOG(ERROR) << "Failed to add task into cgroup";
213 return false;
214 }
215 return true;
216 }
217
218 if (fd_ == -1) {
219 // no permissions to access the file, ignore
220 return true;
221 }
222
223 // application-dependent path can't be used with tid
224 PLOG(ERROR) << "Application profile can't be applied to a thread";
225 return false;
226}
227
228bool TaskProfile::ExecuteForProcess(uid_t uid, pid_t pid) const {
229 for (const auto& element : elements_) {
230 if (!element->ExecuteForProcess(uid, pid)) {
231 return false;
232 }
233 }
234 return true;
235}
236
237bool TaskProfile::ExecuteForTask(int tid) const {
238 if (tid == 0) {
239 tid = GetThreadId();
240 }
241 for (const auto& element : elements_) {
242 if (!element->ExecuteForTask(tid)) {
243 return false;
244 }
245 }
246 return true;
247}
248
249TaskProfiles& TaskProfiles::GetInstance() {
250 static TaskProfiles instance;
251 return instance;
252}
253
254TaskProfiles::TaskProfiles() {
255 if (!Load(CgroupMap::GetInstance())) {
256 LOG(ERROR) << "TaskProfiles::Load for [" << getpid() << "] failed";
257 }
258}
259
260bool TaskProfiles::Load(const CgroupMap& cg_map) {
261 std::string json_doc;
262
263 if (!android::base::ReadFileToString(TASK_PROFILE_DB_FILE, &json_doc)) {
264 LOG(ERROR) << "Failed to read task profiles from " << TASK_PROFILE_DB_FILE;
265 return false;
266 }
267
268 Json::Reader reader;
269 Json::Value root;
270 if (!reader.parse(json_doc, root)) {
271 LOG(ERROR) << "Failed to parse task profiles: " << reader.getFormattedErrorMessages();
272 return false;
273 }
274
275 Json::Value attr = root["Attributes"];
276 for (Json::Value::ArrayIndex i = 0; i < attr.size(); ++i) {
277 std::string name = attr[i]["Name"].asString();
278 std::string ctrlName = attr[i]["Controller"].asString();
279 std::string file_name = attr[i]["File"].asString();
280
281 if (attributes_.find(name) == attributes_.end()) {
282 const CgroupController* controller = cg_map.FindController(ctrlName.c_str());
283 if (controller) {
284 attributes_[name] = std::make_unique<ProfileAttribute>(controller, file_name);
285 } else {
286 LOG(WARNING) << "Controller " << ctrlName << " is not found";
287 }
288 } else {
289 LOG(WARNING) << "Attribute " << name << " is already defined";
290 }
291 }
292
293 std::map<std::string, std::string> params;
294
295 Json::Value profilesVal = root["Profiles"];
296 for (Json::Value::ArrayIndex i = 0; i < profilesVal.size(); ++i) {
297 Json::Value profileVal = profilesVal[i];
298
299 std::string profileName = profileVal["Name"].asString();
300 Json::Value actions = profileVal["Actions"];
301 auto profile = std::make_unique<TaskProfile>();
302
303 for (Json::Value::ArrayIndex actIdx = 0; actIdx < actions.size(); ++actIdx) {
304 Json::Value actionVal = actions[actIdx];
305 std::string actionName = actionVal["Name"].asString();
306 Json::Value paramsVal = actionVal["Params"];
307 if (actionName == "JoinCgroup") {
308 std::string ctrlName = paramsVal["Controller"].asString();
309 std::string path = paramsVal["Path"].asString();
310
311 const CgroupController* controller = cg_map.FindController(ctrlName.c_str());
312 if (controller) {
313 profile->Add(std::make_unique<SetCgroupAction>(controller, path));
314 } else {
315 LOG(WARNING) << "JoinCgroup: controller " << ctrlName << " is not found";
316 }
317 } else if (actionName == "SetTimerSlack") {
318 std::string slackValue = paramsVal["Slack"].asString();
319 char* end;
320 unsigned long slack;
321
322 slack = strtoul(slackValue.c_str(), &end, 10);
323 if (end > slackValue.c_str()) {
324 profile->Add(std::make_unique<SetTimerSlackAction>(slack));
325 } else {
326 LOG(WARNING) << "SetTimerSlack: invalid parameter: " << slackValue;
327 }
328 } else if (actionName == "SetAttribute") {
329 std::string attrName = paramsVal["Name"].asString();
330 std::string attrValue = paramsVal["Value"].asString();
331
332 auto iter = attributes_.find(attrName);
333 if (iter != attributes_.end()) {
334 profile->Add(
335 std::make_unique<SetAttributeAction>(iter->second.get(), attrValue));
336 } else {
337 LOG(WARNING) << "SetAttribute: unknown attribute: " << attrName;
338 }
339 } else if (actionName == "SetClamps") {
340 std::string boostValue = paramsVal["Boost"].asString();
341 std::string clampValue = paramsVal["Clamp"].asString();
342 char* end;
343 unsigned long boost;
344
345 boost = strtoul(boostValue.c_str(), &end, 10);
346 if (end > boostValue.c_str()) {
347 unsigned long clamp = strtoul(clampValue.c_str(), &end, 10);
348 if (end > clampValue.c_str()) {
349 profile->Add(std::make_unique<SetClampsAction>(boost, clamp));
350 } else {
351 LOG(WARNING) << "SetClamps: invalid parameter " << clampValue;
352 }
353 } else {
354 LOG(WARNING) << "SetClamps: invalid parameter: " << boostValue;
355 }
356 } else {
357 LOG(WARNING) << "Unknown profile action: " << actionName;
358 }
359 }
360 profiles_[profileName] = std::move(profile);
361 }
362
363 return true;
364}
365
366const TaskProfile* TaskProfiles::GetProfile(const std::string& name) const {
367 auto iter = profiles_.find(name);
368
369 if (iter != profiles_.end()) {
370 return iter->second.get();
371 }
372 return nullptr;
373}
374
375const ProfileAttribute* TaskProfiles::GetAttribute(const std::string& name) const {
376 auto iter = attributes_.find(name);
377
378 if (iter != attributes_.end()) {
379 return iter->second.get();
380 }
381 return nullptr;
382}