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