blob: 4b45c876586223caef086475348ed097cbb238a4 [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 Baghdasaryanbee9f572019-02-05 16:44:22 -0800141#ifdef CACHE_FILE_DESCRIPTORS
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800142 // cache file descriptor only if path is app independent
143 if (IsAppDependentPath(path_)) {
144 // file descriptor is not cached
145 fd_.reset(-2);
146 return;
147 }
148
Yifan Hong53e0deb2019-03-22 17:01:08 -0700149 std::string tasks_path = c.GetTasksFilePath(p);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800150
151 if (access(tasks_path.c_str(), W_OK) != 0) {
152 // file is not accessible
153 fd_.reset(-1);
154 return;
155 }
156
157 unique_fd fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
158 if (fd < 0) {
159 PLOG(ERROR) << "Failed to cache fd '" << tasks_path << "'";
160 fd_.reset(-1);
161 return;
162 }
163
164 fd_ = std::move(fd);
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800165#endif
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800166}
167
168bool SetCgroupAction::AddTidToCgroup(int tid, int fd) {
169 if (tid <= 0) {
170 return true;
171 }
172
173 std::string value = std::to_string(tid);
174
175 if (TEMP_FAILURE_RETRY(write(fd, value.c_str(), value.length())) < 0) {
176 // If the thread is in the process of exiting, don't flag an error
177 if (errno != ESRCH) {
Wei Wangd71d3012019-03-07 11:59:12 -0800178 PLOG(ERROR) << "AddTidToCgroup failed to write '" << value << "'; fd=" << fd;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800179 return false;
180 }
181 }
182
183 return true;
184}
185
186bool SetCgroupAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800187#ifdef CACHE_FILE_DESCRIPTORS
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800188 if (fd_ >= 0) {
189 // fd is cached, reuse it
190 if (!AddTidToCgroup(pid, fd_)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800191 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800192 return false;
193 }
194 return true;
195 }
196
197 if (fd_ == -1) {
198 // no permissions to access the file, ignore
199 return true;
200 }
201
202 // this is app-dependent path, file descriptor is not cached
Yifan Hong53e0deb2019-03-22 17:01:08 -0700203 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800204 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(procs_path.c_str(), O_WRONLY | O_CLOEXEC)));
205 if (tmp_fd < 0) {
Elliott Hughes08b4d322019-03-14 20:06:36 -0700206 PLOG(WARNING) << "Failed to open " << procs_path;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800207 return false;
208 }
209 if (!AddTidToCgroup(pid, tmp_fd)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800210 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800211 return false;
212 }
213
214 return true;
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800215#else
Yifan Hong53e0deb2019-03-22 17:01:08 -0700216 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800217 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(procs_path.c_str(), O_WRONLY | O_CLOEXEC)));
218 if (tmp_fd < 0) {
219 // no permissions to access the file, ignore
220 return true;
221 }
222 if (!AddTidToCgroup(pid, tmp_fd)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800223 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800224 return false;
225 }
226
227 return true;
228#endif
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800229}
230
231bool SetCgroupAction::ExecuteForTask(int tid) const {
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800232#ifdef CACHE_FILE_DESCRIPTORS
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800233 if (fd_ >= 0) {
234 // fd is cached, reuse it
235 if (!AddTidToCgroup(tid, fd_)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800236 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800237 return false;
238 }
239 return true;
240 }
241
242 if (fd_ == -1) {
243 // no permissions to access the file, ignore
244 return true;
245 }
246
247 // application-dependent path can't be used with tid
Wei Wangd71d3012019-03-07 11:59:12 -0800248 LOG(ERROR) << "Application profile can't be applied to a thread";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800249 return false;
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800250#else
Yifan Hong53e0deb2019-03-22 17:01:08 -0700251 std::string tasks_path = controller()->GetTasksFilePath(path_);
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800252 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
253 if (tmp_fd < 0) {
254 // no permissions to access the file, ignore
255 return true;
256 }
257 if (!AddTidToCgroup(tid, tmp_fd)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800258 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800259 return false;
260 }
261
262 return true;
263#endif
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800264}
265
266bool TaskProfile::ExecuteForProcess(uid_t uid, pid_t pid) const {
267 for (const auto& element : elements_) {
268 if (!element->ExecuteForProcess(uid, pid)) {
269 return false;
270 }
271 }
272 return true;
273}
274
275bool TaskProfile::ExecuteForTask(int tid) const {
276 if (tid == 0) {
277 tid = GetThreadId();
278 }
279 for (const auto& element : elements_) {
280 if (!element->ExecuteForTask(tid)) {
281 return false;
282 }
283 }
284 return true;
285}
286
287TaskProfiles& TaskProfiles::GetInstance() {
Peter Collingbournedba6d442019-03-20 21:09:46 -0700288 // Deliberately leak this object to avoid a race between destruction on
289 // process exit and concurrent access from another thread.
290 static auto* instance = new TaskProfiles;
291 return *instance;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800292}
293
294TaskProfiles::TaskProfiles() {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800295 // load system task profiles
296 if (!Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_FILE)) {
297 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_FILE << " for [" << getpid() << "] failed";
298 }
299
300 // load vendor task profiles if the file exists
301 if (!access(TASK_PROFILE_DB_VENDOR_FILE, F_OK) &&
302 !Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_VENDOR_FILE)) {
303 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_VENDOR_FILE << " for [" << getpid()
304 << "] failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800305 }
306}
307
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800308bool TaskProfiles::Load(const CgroupMap& cg_map, const std::string& file_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800309 std::string json_doc;
310
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800311 if (!android::base::ReadFileToString(file_name, &json_doc)) {
312 LOG(ERROR) << "Failed to read task profiles from " << file_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800313 return false;
314 }
315
316 Json::Reader reader;
317 Json::Value root;
318 if (!reader.parse(json_doc, root)) {
319 LOG(ERROR) << "Failed to parse task profiles: " << reader.getFormattedErrorMessages();
320 return false;
321 }
322
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800323 const Json::Value& attr = root["Attributes"];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800324 for (Json::Value::ArrayIndex i = 0; i < attr.size(); ++i) {
325 std::string name = attr[i]["Name"].asString();
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800326 std::string controller_name = attr[i]["Controller"].asString();
327 std::string file_attr = attr[i]["File"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800328
329 if (attributes_.find(name) == attributes_.end()) {
Yifan Hong53e0deb2019-03-22 17:01:08 -0700330 auto controller = cg_map.FindController(controller_name);
331 if (controller.HasValue()) {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800332 attributes_[name] = std::make_unique<ProfileAttribute>(controller, file_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800333 } else {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800334 LOG(WARNING) << "Controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800335 }
336 } else {
337 LOG(WARNING) << "Attribute " << name << " is already defined";
338 }
339 }
340
341 std::map<std::string, std::string> params;
342
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800343 const Json::Value& profiles_val = root["Profiles"];
344 for (Json::Value::ArrayIndex i = 0; i < profiles_val.size(); ++i) {
345 const Json::Value& profile_val = profiles_val[i];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800346
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800347 std::string profile_name = profile_val["Name"].asString();
348 const Json::Value& actions = profile_val["Actions"];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800349 auto profile = std::make_unique<TaskProfile>();
350
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800351 for (Json::Value::ArrayIndex act_idx = 0; act_idx < actions.size(); ++act_idx) {
352 const Json::Value& action_val = actions[act_idx];
353 std::string action_name = action_val["Name"].asString();
354 const Json::Value& params_val = action_val["Params"];
355 if (action_name == "JoinCgroup") {
356 std::string controller_name = params_val["Controller"].asString();
357 std::string path = params_val["Path"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800358
Yifan Hong53e0deb2019-03-22 17:01:08 -0700359 auto controller = cg_map.FindController(controller_name);
360 if (controller.HasValue()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800361 profile->Add(std::make_unique<SetCgroupAction>(controller, path));
362 } else {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800363 LOG(WARNING) << "JoinCgroup: controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800364 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800365 } else if (action_name == "SetTimerSlack") {
366 std::string slack_value = params_val["Slack"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800367 char* end;
368 unsigned long slack;
369
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800370 slack = strtoul(slack_value.c_str(), &end, 10);
371 if (end > slack_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800372 profile->Add(std::make_unique<SetTimerSlackAction>(slack));
373 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800374 LOG(WARNING) << "SetTimerSlack: invalid parameter: " << slack_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800375 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800376 } else if (action_name == "SetAttribute") {
377 std::string attr_name = params_val["Name"].asString();
378 std::string attr_value = params_val["Value"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800379
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800380 auto iter = attributes_.find(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800381 if (iter != attributes_.end()) {
382 profile->Add(
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800383 std::make_unique<SetAttributeAction>(iter->second.get(), attr_value));
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800384 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800385 LOG(WARNING) << "SetAttribute: unknown attribute: " << attr_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800386 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800387 } else if (action_name == "SetClamps") {
388 std::string boost_value = params_val["Boost"].asString();
389 std::string clamp_value = params_val["Clamp"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800390 char* end;
391 unsigned long boost;
392
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800393 boost = strtoul(boost_value.c_str(), &end, 10);
394 if (end > boost_value.c_str()) {
395 unsigned long clamp = strtoul(clamp_value.c_str(), &end, 10);
396 if (end > clamp_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800397 profile->Add(std::make_unique<SetClampsAction>(boost, clamp));
398 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800399 LOG(WARNING) << "SetClamps: invalid parameter " << clamp_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800400 }
401 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800402 LOG(WARNING) << "SetClamps: invalid parameter: " << boost_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800403 }
404 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800405 LOG(WARNING) << "Unknown profile action: " << action_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800406 }
407 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800408 profiles_[profile_name] = std::move(profile);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800409 }
410
411 return true;
412}
413
414const TaskProfile* TaskProfiles::GetProfile(const std::string& name) const {
415 auto iter = profiles_.find(name);
416
417 if (iter != profiles_.end()) {
418 return iter->second.get();
419 }
420 return nullptr;
421}
422
423const ProfileAttribute* TaskProfiles::GetAttribute(const std::string& name) const {
424 auto iter = attributes_.find(name);
425
426 if (iter != attributes_.end()) {
427 return iter->second.get();
428 }
429 return nullptr;
430}