• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 <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 
34 // To avoid issues in sdk_mac build
35 #if defined(__ANDROID__)
36 #include <sys/prctl.h>
37 #endif
38 
39 using android::base::GetThreadId;
40 using android::base::StringPrintf;
41 using android::base::unique_fd;
42 using android::base::WriteStringToFile;
43 
44 #define TASK_PROFILE_DB_FILE "/etc/task_profiles.json"
45 #define TASK_PROFILE_DB_VENDOR_FILE "/vendor/etc/task_profiles.json"
46 
GetPathForTask(int tid,std::string * path) const47 bool 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(),
61                              file_name_.c_str());
62     }
63     return true;
64 }
65 
ExecuteForProcess(uid_t,pid_t) const66 bool 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 
ExecuteForTask(int) const72 bool 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 
78 // To avoid issues in sdk_mac build
79 #if defined(__ANDROID__)
80 
IsTimerSlackSupported(int tid)81 bool 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 
ExecuteForTask(int tid) const87 bool 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)) {
95             if (errno == ENOENT) {
96                 // This happens when process is already dead
97                 return true;
98             }
99             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 
113 #endif
114 
ExecuteForProcess(uid_t,pid_t pid) const115 bool SetAttributeAction::ExecuteForProcess(uid_t, pid_t pid) const {
116     return ExecuteForTask(pid);
117 }
118 
ExecuteForTask(int tid) const119 bool SetAttributeAction::ExecuteForTask(int tid) const {
120     std::string path;
121 
122     if (!attribute_->GetPathForTask(tid, &path)) {
123         LOG(ERROR) << "Failed to find cgroup for tid " << tid;
124         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 
IsAppDependentPath(const std::string & path)135 bool SetCgroupAction::IsAppDependentPath(const std::string& path) {
136     return path.find("<uid>", 0) != std::string::npos || path.find("<pid>", 0) != std::string::npos;
137 }
138 
SetCgroupAction(const CgroupController & c,const std::string & p)139 SetCgroupAction::SetCgroupAction(const CgroupController& c, const std::string& p)
140     : controller_(c), path_(p) {
141     // file descriptors for app-dependent paths can't be cached
142     if (IsAppDependentPath(path_)) {
143         // file descriptor is not cached
144         fd_.reset(FDS_APP_DEPENDENT);
145         return;
146     }
147 
148     // file descriptor can be cached later on request
149     fd_.reset(FDS_NOT_CACHED);
150 }
151 
EnableResourceCaching()152 void SetCgroupAction::EnableResourceCaching() {
153     std::lock_guard<std::mutex> lock(fd_mutex_);
154     if (fd_ != FDS_NOT_CACHED) {
155         return;
156     }
157 
158     std::string tasks_path = controller_.GetTasksFilePath(path_);
159 
160     if (access(tasks_path.c_str(), W_OK) != 0) {
161         // file is not accessible
162         fd_.reset(FDS_INACCESSIBLE);
163         return;
164     }
165 
166     unique_fd fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
167     if (fd < 0) {
168         PLOG(ERROR) << "Failed to cache fd '" << tasks_path << "'";
169         fd_.reset(FDS_INACCESSIBLE);
170         return;
171     }
172 
173     fd_ = std::move(fd);
174 }
175 
AddTidToCgroup(int tid,int fd)176 bool SetCgroupAction::AddTidToCgroup(int tid, int fd) {
177     if (tid <= 0) {
178         return true;
179     }
180 
181     std::string value = std::to_string(tid);
182 
183     if (TEMP_FAILURE_RETRY(write(fd, value.c_str(), value.length())) < 0) {
184         // If the thread is in the process of exiting, don't flag an error
185         if (errno != ESRCH) {
186             PLOG(ERROR) << "AddTidToCgroup failed to write '" << value << "'; fd=" << fd;
187             return false;
188         }
189     }
190 
191     return true;
192 }
193 
ExecuteForProcess(uid_t uid,pid_t pid) const194 bool SetCgroupAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
195     std::lock_guard<std::mutex> lock(fd_mutex_);
196     if (IsFdValid()) {
197         // fd is cached, reuse it
198         if (!AddTidToCgroup(pid, fd_)) {
199             LOG(ERROR) << "Failed to add task into cgroup";
200             return false;
201         }
202         return true;
203     }
204 
205     if (fd_ == FDS_INACCESSIBLE) {
206         // no permissions to access the file, ignore
207         return true;
208     }
209 
210     // this is app-dependent path and fd is not cached or cached fd can't be used
211     std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
212     unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(procs_path.c_str(), O_WRONLY | O_CLOEXEC)));
213     if (tmp_fd < 0) {
214         PLOG(WARNING) << "Failed to open " << procs_path;
215         return false;
216     }
217     if (!AddTidToCgroup(pid, tmp_fd)) {
218         LOG(ERROR) << "Failed to add task into cgroup";
219         return false;
220     }
221 
222     return true;
223 }
224 
ExecuteForTask(int tid) const225 bool SetCgroupAction::ExecuteForTask(int tid) const {
226     std::lock_guard<std::mutex> lock(fd_mutex_);
227     if (IsFdValid()) {
228         // fd is cached, reuse it
229         if (!AddTidToCgroup(tid, fd_)) {
230             LOG(ERROR) << "Failed to add task into cgroup";
231             return false;
232         }
233         return true;
234     }
235 
236     if (fd_ == FDS_INACCESSIBLE) {
237         // no permissions to access the file, ignore
238         return true;
239     }
240 
241     if (fd_ == FDS_APP_DEPENDENT) {
242         // application-dependent path can't be used with tid
243         PLOG(ERROR) << "Application profile can't be applied to a thread";
244         return false;
245     }
246 
247     // fd was not cached because cached fd can't be used
248     std::string tasks_path = controller()->GetTasksFilePath(path_);
249     unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
250     if (tmp_fd < 0) {
251         PLOG(WARNING) << "Failed to open " << tasks_path << ": " << strerror(errno);
252         return false;
253     }
254     if (!AddTidToCgroup(tid, tmp_fd)) {
255         LOG(ERROR) << "Failed to add task into cgroup";
256         return false;
257     }
258 
259     return true;
260 }
261 
ExecuteForProcess(uid_t uid,pid_t pid) const262 bool TaskProfile::ExecuteForProcess(uid_t uid, pid_t pid) const {
263     for (const auto& element : elements_) {
264         if (!element->ExecuteForProcess(uid, pid)) {
265             return false;
266         }
267     }
268     return true;
269 }
270 
ExecuteForTask(int tid) const271 bool TaskProfile::ExecuteForTask(int tid) const {
272     if (tid == 0) {
273         tid = GetThreadId();
274     }
275     for (const auto& element : elements_) {
276         if (!element->ExecuteForTask(tid)) {
277             return false;
278         }
279     }
280     return true;
281 }
282 
EnableResourceCaching()283 void TaskProfile::EnableResourceCaching() {
284     if (res_cached_) {
285         return;
286     }
287 
288     for (auto& element : elements_) {
289         element->EnableResourceCaching();
290     }
291 
292     res_cached_ = true;
293 }
294 
GetInstance()295 TaskProfiles& TaskProfiles::GetInstance() {
296     // Deliberately leak this object to avoid a race between destruction on
297     // process exit and concurrent access from another thread.
298     static auto* instance = new TaskProfiles;
299     return *instance;
300 }
301 
TaskProfiles()302 TaskProfiles::TaskProfiles() {
303     // load system task profiles
304     if (!Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_FILE)) {
305         LOG(ERROR) << "Loading " << TASK_PROFILE_DB_FILE << " for [" << getpid() << "] failed";
306     }
307 
308     // load vendor task profiles if the file exists
309     if (!access(TASK_PROFILE_DB_VENDOR_FILE, F_OK) &&
310         !Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_VENDOR_FILE)) {
311         LOG(ERROR) << "Loading " << TASK_PROFILE_DB_VENDOR_FILE << " for [" << getpid()
312                    << "] failed";
313     }
314 }
315 
Load(const CgroupMap & cg_map,const std::string & file_name)316 bool TaskProfiles::Load(const CgroupMap& cg_map, const std::string& file_name) {
317     std::string json_doc;
318 
319     if (!android::base::ReadFileToString(file_name, &json_doc)) {
320         LOG(ERROR) << "Failed to read task profiles from " << file_name;
321         return false;
322     }
323 
324     Json::Reader reader;
325     Json::Value root;
326     if (!reader.parse(json_doc, root)) {
327         LOG(ERROR) << "Failed to parse task profiles: " << reader.getFormattedErrorMessages();
328         return false;
329     }
330 
331     const Json::Value& attr = root["Attributes"];
332     for (Json::Value::ArrayIndex i = 0; i < attr.size(); ++i) {
333         std::string name = attr[i]["Name"].asString();
334         std::string controller_name = attr[i]["Controller"].asString();
335         std::string file_attr = attr[i]["File"].asString();
336 
337         if (attributes_.find(name) == attributes_.end()) {
338             auto controller = cg_map.FindController(controller_name);
339             if (controller.HasValue()) {
340                 attributes_[name] = std::make_unique<ProfileAttribute>(controller, file_attr);
341             } else {
342                 LOG(WARNING) << "Controller " << controller_name << " is not found";
343             }
344         } else {
345             LOG(WARNING) << "Attribute " << name << " is already defined";
346         }
347     }
348 
349     std::map<std::string, std::string> params;
350 
351     const Json::Value& profiles_val = root["Profiles"];
352     for (Json::Value::ArrayIndex i = 0; i < profiles_val.size(); ++i) {
353         const Json::Value& profile_val = profiles_val[i];
354 
355         std::string profile_name = profile_val["Name"].asString();
356         const Json::Value& actions = profile_val["Actions"];
357         auto profile = std::make_unique<TaskProfile>();
358 
359         for (Json::Value::ArrayIndex act_idx = 0; act_idx < actions.size(); ++act_idx) {
360             const Json::Value& action_val = actions[act_idx];
361             std::string action_name = action_val["Name"].asString();
362             const Json::Value& params_val = action_val["Params"];
363             if (action_name == "JoinCgroup") {
364                 std::string controller_name = params_val["Controller"].asString();
365                 std::string path = params_val["Path"].asString();
366 
367                 auto controller = cg_map.FindController(controller_name);
368                 if (controller.HasValue()) {
369                     profile->Add(std::make_unique<SetCgroupAction>(controller, path));
370                 } else {
371                     LOG(WARNING) << "JoinCgroup: controller " << controller_name << " is not found";
372                 }
373             } else if (action_name == "SetTimerSlack") {
374                 std::string slack_value = params_val["Slack"].asString();
375                 char* end;
376                 unsigned long slack;
377 
378                 slack = strtoul(slack_value.c_str(), &end, 10);
379                 if (end > slack_value.c_str()) {
380                     profile->Add(std::make_unique<SetTimerSlackAction>(slack));
381                 } else {
382                     LOG(WARNING) << "SetTimerSlack: invalid parameter: " << slack_value;
383                 }
384             } else if (action_name == "SetAttribute") {
385                 std::string attr_name = params_val["Name"].asString();
386                 std::string attr_value = params_val["Value"].asString();
387 
388                 auto iter = attributes_.find(attr_name);
389                 if (iter != attributes_.end()) {
390                     profile->Add(
391                             std::make_unique<SetAttributeAction>(iter->second.get(), attr_value));
392                 } else {
393                     LOG(WARNING) << "SetAttribute: unknown attribute: " << attr_name;
394                 }
395             } else if (action_name == "SetClamps") {
396                 std::string boost_value = params_val["Boost"].asString();
397                 std::string clamp_value = params_val["Clamp"].asString();
398                 char* end;
399                 unsigned long boost;
400 
401                 boost = strtoul(boost_value.c_str(), &end, 10);
402                 if (end > boost_value.c_str()) {
403                     unsigned long clamp = strtoul(clamp_value.c_str(), &end, 10);
404                     if (end > clamp_value.c_str()) {
405                         profile->Add(std::make_unique<SetClampsAction>(boost, clamp));
406                     } else {
407                         LOG(WARNING) << "SetClamps: invalid parameter " << clamp_value;
408                     }
409                 } else {
410                     LOG(WARNING) << "SetClamps: invalid parameter: " << boost_value;
411                 }
412             } else {
413                 LOG(WARNING) << "Unknown profile action: " << action_name;
414             }
415         }
416         profiles_[profile_name] = std::move(profile);
417     }
418 
419     return true;
420 }
421 
GetProfile(const std::string & name) const422 TaskProfile* TaskProfiles::GetProfile(const std::string& name) const {
423     auto iter = profiles_.find(name);
424 
425     if (iter != profiles_.end()) {
426         return iter->second.get();
427     }
428     return nullptr;
429 }
430 
GetAttribute(const std::string & name) const431 const ProfileAttribute* TaskProfiles::GetAttribute(const std::string& name) const {
432     auto iter = attributes_.find(name);
433 
434     if (iter != attributes_.end()) {
435         return iter->second.get();
436     }
437     return nullptr;
438 }
439