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 
Reset(const CgroupController & controller,const std::string & file_name)47 void ProfileAttribute::Reset(const CgroupController& controller, const std::string& file_name) {
48     controller_ = controller;
49     file_name_ = file_name;
50 }
51 
GetPathForTask(int tid,std::string * path) const52 bool ProfileAttribute::GetPathForTask(int tid, std::string* path) const {
53     std::string subgroup;
54     if (!controller()->GetTaskGroup(tid, &subgroup)) {
55         return false;
56     }
57 
58     if (path == nullptr) {
59         return true;
60     }
61 
62     if (subgroup.empty()) {
63         *path = StringPrintf("%s/%s", controller()->path(), file_name_.c_str());
64     } else {
65         *path = StringPrintf("%s/%s/%s", controller()->path(), subgroup.c_str(),
66                              file_name_.c_str());
67     }
68     return true;
69 }
70 
ExecuteForProcess(uid_t,pid_t) const71 bool SetClampsAction::ExecuteForProcess(uid_t, pid_t) const {
72     // TODO: add support when kernel supports util_clamp
73     LOG(WARNING) << "SetClampsAction::ExecuteForProcess is not supported";
74     return false;
75 }
76 
ExecuteForTask(int) const77 bool SetClampsAction::ExecuteForTask(int) const {
78     // TODO: add support when kernel supports util_clamp
79     LOG(WARNING) << "SetClampsAction::ExecuteForTask is not supported";
80     return false;
81 }
82 
83 // To avoid issues in sdk_mac build
84 #if defined(__ANDROID__)
85 
IsTimerSlackSupported(int tid)86 bool SetTimerSlackAction::IsTimerSlackSupported(int tid) {
87     auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
88 
89     return (access(file.c_str(), W_OK) == 0);
90 }
91 
ExecuteForTask(int tid) const92 bool SetTimerSlackAction::ExecuteForTask(int tid) const {
93     static bool sys_supports_timerslack = IsTimerSlackSupported(tid);
94 
95     // v4.6+ kernels support the /proc/<tid>/timerslack_ns interface.
96     // TODO: once we've backported this, log if the open(2) fails.
97     if (sys_supports_timerslack) {
98         auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
99         if (!WriteStringToFile(std::to_string(slack_), file)) {
100             if (errno == ENOENT) {
101                 // This happens when process is already dead
102                 return true;
103             }
104             PLOG(ERROR) << "set_timerslack_ns write failed";
105         }
106     }
107 
108     // TODO: Remove when /proc/<tid>/timerslack_ns interface is backported.
109     if (tid == 0 || tid == GetThreadId()) {
110         if (prctl(PR_SET_TIMERSLACK, slack_) == -1) {
111             PLOG(ERROR) << "set_timerslack_ns prctl failed";
112         }
113     }
114 
115     return true;
116 }
117 
118 #endif
119 
ExecuteForProcess(uid_t,pid_t pid) const120 bool SetAttributeAction::ExecuteForProcess(uid_t, pid_t pid) const {
121     return ExecuteForTask(pid);
122 }
123 
ExecuteForTask(int tid) const124 bool SetAttributeAction::ExecuteForTask(int tid) const {
125     std::string path;
126 
127     if (!attribute_->GetPathForTask(tid, &path)) {
128         LOG(ERROR) << "Failed to find cgroup for tid " << tid;
129         return false;
130     }
131 
132     if (!WriteStringToFile(value_, path)) {
133         PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
134         return false;
135     }
136 
137     return true;
138 }
139 
IsAppDependentPath(const std::string & path)140 bool SetCgroupAction::IsAppDependentPath(const std::string& path) {
141     return path.find("<uid>", 0) != std::string::npos || path.find("<pid>", 0) != std::string::npos;
142 }
143 
SetCgroupAction(const CgroupController & c,const std::string & p)144 SetCgroupAction::SetCgroupAction(const CgroupController& c, const std::string& p)
145     : controller_(c), path_(p) {
146     // file descriptors for app-dependent paths can't be cached
147     if (IsAppDependentPath(path_)) {
148         // file descriptor is not cached
149         fd_.reset(FDS_APP_DEPENDENT);
150         return;
151     }
152 
153     // file descriptor can be cached later on request
154     fd_.reset(FDS_NOT_CACHED);
155 }
156 
EnableResourceCaching()157 void SetCgroupAction::EnableResourceCaching() {
158     std::lock_guard<std::mutex> lock(fd_mutex_);
159     if (fd_ != FDS_NOT_CACHED) {
160         return;
161     }
162 
163     std::string tasks_path = controller_.GetTasksFilePath(path_);
164 
165     if (access(tasks_path.c_str(), W_OK) != 0) {
166         // file is not accessible
167         fd_.reset(FDS_INACCESSIBLE);
168         return;
169     }
170 
171     unique_fd fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
172     if (fd < 0) {
173         PLOG(ERROR) << "Failed to cache fd '" << tasks_path << "'";
174         fd_.reset(FDS_INACCESSIBLE);
175         return;
176     }
177 
178     fd_ = std::move(fd);
179 }
180 
DropResourceCaching()181 void SetCgroupAction::DropResourceCaching() {
182     std::lock_guard<std::mutex> lock(fd_mutex_);
183     if (fd_ == FDS_NOT_CACHED) {
184         return;
185     }
186 
187     fd_.reset(FDS_NOT_CACHED);
188 }
189 
AddTidToCgroup(int tid,int fd)190 bool SetCgroupAction::AddTidToCgroup(int tid, int fd) {
191     if (tid <= 0) {
192         return true;
193     }
194 
195     std::string value = std::to_string(tid);
196 
197     if (TEMP_FAILURE_RETRY(write(fd, value.c_str(), value.length())) < 0) {
198         // If the thread is in the process of exiting, don't flag an error
199         if (errno != ESRCH) {
200             PLOG(ERROR) << "AddTidToCgroup failed to write '" << value << "'; fd=" << fd;
201             return false;
202         }
203     }
204 
205     return true;
206 }
207 
ExecuteForProcess(uid_t uid,pid_t pid) const208 bool SetCgroupAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
209     std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
210     unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(procs_path.c_str(), O_WRONLY | O_CLOEXEC)));
211     if (tmp_fd < 0) {
212         PLOG(WARNING) << "Failed to open " << procs_path;
213         return false;
214     }
215     if (!AddTidToCgroup(pid, tmp_fd)) {
216         LOG(ERROR) << "Failed to add task into cgroup";
217         return false;
218     }
219 
220     return true;
221 }
222 
ExecuteForTask(int tid) const223 bool SetCgroupAction::ExecuteForTask(int tid) const {
224     std::lock_guard<std::mutex> lock(fd_mutex_);
225     if (IsFdValid()) {
226         // fd is cached, reuse it
227         if (!AddTidToCgroup(tid, fd_)) {
228             LOG(ERROR) << "Failed to add task into cgroup";
229             return false;
230         }
231         return true;
232     }
233 
234     if (fd_ == FDS_INACCESSIBLE) {
235         // no permissions to access the file, ignore
236         return true;
237     }
238 
239     if (fd_ == FDS_APP_DEPENDENT) {
240         // application-dependent path can't be used with tid
241         PLOG(ERROR) << "Application profile can't be applied to a thread";
242         return false;
243     }
244 
245     // fd was not cached because cached fd can't be used
246     std::string tasks_path = controller()->GetTasksFilePath(path_);
247     unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
248     if (tmp_fd < 0) {
249         PLOG(WARNING) << "Failed to open " << tasks_path << ": " << strerror(errno);
250         return false;
251     }
252     if (!AddTidToCgroup(tid, tmp_fd)) {
253         LOG(ERROR) << "Failed to add task into cgroup";
254         return false;
255     }
256 
257     return true;
258 }
259 
ExecuteForProcess(uid_t uid,pid_t pid) const260 bool ApplyProfileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
261     for (const auto& profile : profiles_) {
262         if (!profile->ExecuteForProcess(uid, pid)) {
263             PLOG(WARNING) << "ExecuteForProcess failed for aggregate profile";
264         }
265     }
266     return true;
267 }
268 
ExecuteForTask(int tid) const269 bool ApplyProfileAction::ExecuteForTask(int tid) const {
270     for (const auto& profile : profiles_) {
271         if (!profile->ExecuteForTask(tid)) {
272             PLOG(WARNING) << "ExecuteForTask failed for aggregate profile";
273         }
274     }
275     return true;
276 }
277 
EnableResourceCaching()278 void ApplyProfileAction::EnableResourceCaching() {
279     for (const auto& profile : profiles_) {
280         profile->EnableResourceCaching();
281     }
282 }
283 
DropResourceCaching()284 void ApplyProfileAction::DropResourceCaching() {
285     for (const auto& profile : profiles_) {
286         profile->DropResourceCaching();
287     }
288 }
289 
MoveTo(TaskProfile * profile)290 void TaskProfile::MoveTo(TaskProfile* profile) {
291     profile->elements_ = std::move(elements_);
292     profile->res_cached_ = res_cached_;
293 }
294 
ExecuteForProcess(uid_t uid,pid_t pid) const295 bool TaskProfile::ExecuteForProcess(uid_t uid, pid_t pid) const {
296     for (const auto& element : elements_) {
297         if (!element->ExecuteForProcess(uid, pid)) {
298             return false;
299         }
300     }
301     return true;
302 }
303 
ExecuteForTask(int tid) const304 bool TaskProfile::ExecuteForTask(int tid) const {
305     if (tid == 0) {
306         tid = GetThreadId();
307     }
308     for (const auto& element : elements_) {
309         if (!element->ExecuteForTask(tid)) {
310             return false;
311         }
312     }
313     return true;
314 }
315 
EnableResourceCaching()316 void TaskProfile::EnableResourceCaching() {
317     if (res_cached_) {
318         return;
319     }
320 
321     for (auto& element : elements_) {
322         element->EnableResourceCaching();
323     }
324 
325     res_cached_ = true;
326 }
327 
DropResourceCaching()328 void TaskProfile::DropResourceCaching() {
329     if (!res_cached_) {
330         return;
331     }
332 
333     for (auto& element : elements_) {
334         element->DropResourceCaching();
335     }
336 
337     res_cached_ = false;
338 }
339 
DropResourceCaching() const340 void TaskProfiles::DropResourceCaching() const {
341     for (auto& iter : profiles_) {
342         iter.second->DropResourceCaching();
343     }
344 }
345 
GetInstance()346 TaskProfiles& TaskProfiles::GetInstance() {
347     // Deliberately leak this object to avoid a race between destruction on
348     // process exit and concurrent access from another thread.
349     static auto* instance = new TaskProfiles;
350     return *instance;
351 }
352 
TaskProfiles()353 TaskProfiles::TaskProfiles() {
354     // load system task profiles
355     if (!Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_FILE)) {
356         LOG(ERROR) << "Loading " << TASK_PROFILE_DB_FILE << " for [" << getpid() << "] failed";
357     }
358 
359     // load vendor task profiles if the file exists
360     if (!access(TASK_PROFILE_DB_VENDOR_FILE, F_OK) &&
361         !Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_VENDOR_FILE)) {
362         LOG(ERROR) << "Loading " << TASK_PROFILE_DB_VENDOR_FILE << " for [" << getpid()
363                    << "] failed";
364     }
365 }
366 
Load(const CgroupMap & cg_map,const std::string & file_name)367 bool TaskProfiles::Load(const CgroupMap& cg_map, const std::string& file_name) {
368     std::string json_doc;
369 
370     if (!android::base::ReadFileToString(file_name, &json_doc)) {
371         LOG(ERROR) << "Failed to read task profiles from " << file_name;
372         return false;
373     }
374 
375     Json::Reader reader;
376     Json::Value root;
377     if (!reader.parse(json_doc, root)) {
378         LOG(ERROR) << "Failed to parse task profiles: " << reader.getFormattedErrorMessages();
379         return false;
380     }
381 
382     const Json::Value& attr = root["Attributes"];
383     for (Json::Value::ArrayIndex i = 0; i < attr.size(); ++i) {
384         std::string name = attr[i]["Name"].asString();
385         std::string controller_name = attr[i]["Controller"].asString();
386         std::string file_attr = attr[i]["File"].asString();
387 
388         auto controller = cg_map.FindController(controller_name);
389         if (controller.HasValue()) {
390             auto iter = attributes_.find(name);
391             if (iter == attributes_.end()) {
392                 attributes_[name] = std::make_unique<ProfileAttribute>(controller, file_attr);
393             } else {
394                 iter->second->Reset(controller, file_attr);
395             }
396         } else {
397             LOG(WARNING) << "Controller " << controller_name << " is not found";
398         }
399     }
400 
401     const Json::Value& profiles_val = root["Profiles"];
402     for (Json::Value::ArrayIndex i = 0; i < profiles_val.size(); ++i) {
403         const Json::Value& profile_val = profiles_val[i];
404 
405         std::string profile_name = profile_val["Name"].asString();
406         const Json::Value& actions = profile_val["Actions"];
407         auto profile = std::make_shared<TaskProfile>();
408 
409         for (Json::Value::ArrayIndex act_idx = 0; act_idx < actions.size(); ++act_idx) {
410             const Json::Value& action_val = actions[act_idx];
411             std::string action_name = action_val["Name"].asString();
412             const Json::Value& params_val = action_val["Params"];
413             if (action_name == "JoinCgroup") {
414                 std::string controller_name = params_val["Controller"].asString();
415                 std::string path = params_val["Path"].asString();
416 
417                 auto controller = cg_map.FindController(controller_name);
418                 if (controller.HasValue()) {
419                     profile->Add(std::make_unique<SetCgroupAction>(controller, path));
420                 } else {
421                     LOG(WARNING) << "JoinCgroup: controller " << controller_name << " is not found";
422                 }
423             } else if (action_name == "SetTimerSlack") {
424                 std::string slack_value = params_val["Slack"].asString();
425                 char* end;
426                 unsigned long slack;
427 
428                 slack = strtoul(slack_value.c_str(), &end, 10);
429                 if (end > slack_value.c_str()) {
430                     profile->Add(std::make_unique<SetTimerSlackAction>(slack));
431                 } else {
432                     LOG(WARNING) << "SetTimerSlack: invalid parameter: " << slack_value;
433                 }
434             } else if (action_name == "SetAttribute") {
435                 std::string attr_name = params_val["Name"].asString();
436                 std::string attr_value = params_val["Value"].asString();
437 
438                 auto iter = attributes_.find(attr_name);
439                 if (iter != attributes_.end()) {
440                     profile->Add(
441                             std::make_unique<SetAttributeAction>(iter->second.get(), attr_value));
442                 } else {
443                     LOG(WARNING) << "SetAttribute: unknown attribute: " << attr_name;
444                 }
445             } else if (action_name == "SetClamps") {
446                 std::string boost_value = params_val["Boost"].asString();
447                 std::string clamp_value = params_val["Clamp"].asString();
448                 char* end;
449                 unsigned long boost;
450 
451                 boost = strtoul(boost_value.c_str(), &end, 10);
452                 if (end > boost_value.c_str()) {
453                     unsigned long clamp = strtoul(clamp_value.c_str(), &end, 10);
454                     if (end > clamp_value.c_str()) {
455                         profile->Add(std::make_unique<SetClampsAction>(boost, clamp));
456                     } else {
457                         LOG(WARNING) << "SetClamps: invalid parameter " << clamp_value;
458                     }
459                 } else {
460                     LOG(WARNING) << "SetClamps: invalid parameter: " << boost_value;
461                 }
462             } else {
463                 LOG(WARNING) << "Unknown profile action: " << action_name;
464             }
465         }
466         auto iter = profiles_.find(profile_name);
467         if (iter == profiles_.end()) {
468             profiles_[profile_name] = profile;
469         } else {
470             // Move the content rather that replace the profile because old profile might be
471             // referenced from an aggregate profile if vendor overrides task profiles
472             profile->MoveTo(iter->second.get());
473             profile.reset();
474         }
475     }
476 
477     const Json::Value& aggregateprofiles_val = root["AggregateProfiles"];
478     for (Json::Value::ArrayIndex i = 0; i < aggregateprofiles_val.size(); ++i) {
479         const Json::Value& aggregateprofile_val = aggregateprofiles_val[i];
480 
481         std::string aggregateprofile_name = aggregateprofile_val["Name"].asString();
482         const Json::Value& aggregateprofiles = aggregateprofile_val["Profiles"];
483         std::vector<std::shared_ptr<TaskProfile>> profiles;
484         bool ret = true;
485 
486         for (Json::Value::ArrayIndex pf_idx = 0; pf_idx < aggregateprofiles.size(); ++pf_idx) {
487             std::string profile_name = aggregateprofiles[pf_idx].asString();
488 
489             if (profile_name == aggregateprofile_name) {
490                 LOG(WARNING) << "AggregateProfiles: recursive profile name: " << profile_name;
491                 ret = false;
492                 break;
493             } else if (profiles_.find(profile_name) == profiles_.end()) {
494                 LOG(WARNING) << "AggregateProfiles: undefined profile name: " << profile_name;
495                 ret = false;
496                 break;
497             } else {
498                 profiles.push_back(profiles_[profile_name]);
499             }
500         }
501         if (ret) {
502             auto profile = std::make_shared<TaskProfile>();
503             profile->Add(std::make_unique<ApplyProfileAction>(profiles));
504             profiles_[aggregateprofile_name] = profile;
505         }
506     }
507 
508     return true;
509 }
510 
GetProfile(const std::string & name) const511 TaskProfile* TaskProfiles::GetProfile(const std::string& name) const {
512     auto iter = profiles_.find(name);
513 
514     if (iter != profiles_.end()) {
515         return iter->second.get();
516     }
517     return nullptr;
518 }
519 
GetAttribute(const std::string & name) const520 const ProfileAttribute* TaskProfiles::GetAttribute(const std::string& name) const {
521     auto iter = attributes_.find(name);
522 
523     if (iter != attributes_.end()) {
524         return iter->second.get();
525     }
526     return nullptr;
527 }
528 
SetProcessProfiles(uid_t uid,pid_t pid,const std::vector<std::string> & profiles)529 bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
530                                       const std::vector<std::string>& profiles) {
531     for (const auto& name : profiles) {
532         TaskProfile* profile = GetProfile(name);
533         if (profile != nullptr) {
534             if (!profile->ExecuteForProcess(uid, pid)) {
535                 PLOG(WARNING) << "Failed to apply " << name << " process profile";
536             }
537         } else {
538             PLOG(WARNING) << "Failed to find " << name << "process profile";
539         }
540     }
541     return true;
542 }
543 
SetTaskProfiles(int tid,const std::vector<std::string> & profiles,bool use_fd_cache)544 bool TaskProfiles::SetTaskProfiles(int tid, const std::vector<std::string>& profiles,
545                                    bool use_fd_cache) {
546     for (const auto& name : profiles) {
547         TaskProfile* profile = GetProfile(name);
548         if (profile != nullptr) {
549             if (use_fd_cache) {
550                 profile->EnableResourceCaching();
551             }
552             if (!profile->ExecuteForTask(tid)) {
553                 PLOG(WARNING) << "Failed to apply " << name << " task profile";
554             }
555         } else {
556             PLOG(WARNING) << "Failed to find " << name << "task profile";
557         }
558     }
559     return true;
560 }
561