task_profiles.cpp 14 KB

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