• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2024 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 #include <processgroup/util.h>
18 
19 #include <algorithm>
20 #include <iterator>
21 #include <optional>
22 #include <string_view>
23 
24 #include <mntent.h>
25 
26 #include <android-base/file.h>
27 #include <android-base/logging.h>
28 #include <android-base/properties.h>
29 #include <android-base/stringprintf.h>
30 #include <json/reader.h>
31 #include <json/value.h>
32 
33 #include "../build_flags.h"
34 #include "../internal.h"
35 
36 using android::base::GetUintProperty;
37 
38 namespace {
39 
40 constexpr const char* CGROUPS_DESC_FILE = "/etc/cgroups.json";
41 constexpr const char* CGROUPS_DESC_VENDOR_FILE = "/vendor/etc/cgroups.json";
42 constexpr const char* TEMPLATE_CGROUPS_DESC_API_FILE = "/etc/task_profiles/cgroups_%u.json";
43 
44 // This should match the publicly declared value in processgroup.h,
45 // but we don't want this library to depend on libprocessgroup.
46 constexpr std::string CGROUPV2_HIERARCHY_NAME_INTERNAL = "cgroup2";
47 
48 const char SEP = '/';
49 
DeduplicateAndTrimSeparators(const std::string & path)50 std::string DeduplicateAndTrimSeparators(const std::string& path) {
51     bool lastWasSep = false;
52     std::string ret;
53 
54     std::copy_if(path.begin(), path.end(), std::back_inserter(ret), [&lastWasSep](char c) {
55         if (lastWasSep) {
56             if (c == SEP) return false;
57             lastWasSep = false;
58         } else if (c == SEP) {
59             lastWasSep = true;
60         }
61         return true;
62     });
63 
64     if (ret.length() > 1 && ret.back() == SEP) ret.pop_back();
65 
66     return ret;
67 }
68 
MergeCgroupToDescriptors(CgroupDescriptorMap * descriptors,const Json::Value & cgroup,const std::string & name,const std::string & root_path,int cgroups_version)69 void MergeCgroupToDescriptors(CgroupDescriptorMap* descriptors, const Json::Value& cgroup,
70                               const std::string& name, const std::string& root_path,
71                               int cgroups_version) {
72     const std::string cgroup_path = cgroup["Path"].asString();
73     std::string path;
74 
75     if (!root_path.empty()) {
76         path = root_path;
77         if (cgroup_path != ".") {
78             path += "/";
79             path += cgroup_path;
80         }
81     } else {
82         path = cgroup_path;
83     }
84 
85     uint32_t controller_flags = 0;
86 
87     if (cgroup["NeedsActivation"].isBool() && cgroup["NeedsActivation"].asBool()) {
88         controller_flags |= CGROUPRC_CONTROLLER_FLAG_NEEDS_ACTIVATION;
89     }
90 
91     if (cgroup["Optional"].isBool() && cgroup["Optional"].asBool()) {
92         controller_flags |= CGROUPRC_CONTROLLER_FLAG_OPTIONAL;
93     }
94 
95     uint32_t max_activation_depth = UINT32_MAX;
96     if (cgroup.isMember("MaxActivationDepth")) {
97         max_activation_depth = cgroup["MaxActivationDepth"].asUInt();
98     }
99 
100     CgroupDescriptor descriptor(
101             cgroups_version, name, path, std::strtoul(cgroup["Mode"].asString().c_str(), 0, 8),
102             cgroup["UID"].asString(), cgroup["GID"].asString(), controller_flags,
103             max_activation_depth);
104 
105     auto iter = descriptors->find(name);
106     if (iter == descriptors->end()) {
107         descriptors->emplace(name, descriptor);
108     } else {
109         iter->second = descriptor;
110     }
111 }
112 
ReadDescriptorsFromFile(const std::string & file_name,CgroupDescriptorMap * descriptors)113 bool ReadDescriptorsFromFile(const std::string& file_name, CgroupDescriptorMap* descriptors) {
114     std::vector<CgroupDescriptor> result;
115     std::string json_doc;
116 
117     if (!android::base::ReadFileToString(file_name, &json_doc)) {
118         PLOG(ERROR) << "Failed to read task profiles from " << file_name;
119         return false;
120     }
121 
122     Json::CharReaderBuilder builder;
123     std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
124     Json::Value root;
125     std::string errorMessage;
126     if (!reader->parse(&*json_doc.begin(), &*json_doc.end(), &root, &errorMessage)) {
127         LOG(ERROR) << "Failed to parse cgroups description: " << errorMessage;
128         return false;
129     }
130 
131     if (root.isMember("Cgroups")) {
132         const Json::Value& cgroups = root["Cgroups"];
133         for (Json::Value::ArrayIndex i = 0; i < cgroups.size(); ++i) {
134             std::string name = cgroups[i]["Controller"].asString();
135             MergeCgroupToDescriptors(descriptors, cgroups[i], name, "", 1);
136         }
137     }
138 
139     std::string root_path;
140     if (root.isMember("Cgroups2")) {
141         const Json::Value& cgroups2 = root["Cgroups2"];
142         root_path = cgroups2["Path"].asString();
143         MergeCgroupToDescriptors(descriptors, cgroups2, CGROUPV2_HIERARCHY_NAME_INTERNAL, "", 2);
144 
145         const Json::Value& childGroups = cgroups2["Controllers"];
146         for (Json::Value::ArrayIndex i = 0; i < childGroups.size(); ++i) {
147             std::string name = childGroups[i]["Controller"].asString();
148             MergeCgroupToDescriptors(descriptors, childGroups[i], name, root_path, 2);
149         }
150     }
151 
152     return true;
153 }
154 
155 using MountDir = std::string;
156 using MountOpts = std::string;
ReadCgroupV1Mounts()157 static std::optional<std::map<MountDir, MountOpts>> ReadCgroupV1Mounts() {
158     FILE* fp = setmntent("/proc/mounts", "r");
159     if (fp == nullptr) {
160         PLOG(ERROR) << "Failed to read mounts";
161         return std::nullopt;
162     }
163 
164     std::map<MountDir, MountOpts> mounts;
165     const std::string_view CGROUP_V1_TYPE = "cgroup";
166     for (mntent* mentry = getmntent(fp); mentry != nullptr; mentry = getmntent(fp)) {
167         if (mentry->mnt_type && CGROUP_V1_TYPE == mentry->mnt_type &&
168             mentry->mnt_dir && mentry->mnt_opts) {
169             mounts[mentry->mnt_dir] = mentry->mnt_opts;
170         }
171     }
172     endmntent(fp);
173 
174     return mounts;
175 }
176 
177 }  // anonymous namespace
178 
179 
GetCgroupDepth(const std::string & controller_root,const std::string & cgroup_path)180 unsigned int GetCgroupDepth(const std::string& controller_root, const std::string& cgroup_path) {
181     const std::string deduped_root = DeduplicateAndTrimSeparators(controller_root);
182     const std::string deduped_path = DeduplicateAndTrimSeparators(cgroup_path);
183 
184     if (deduped_root.empty() || deduped_path.empty() || !deduped_path.starts_with(deduped_root))
185         return 0;
186 
187     return std::count(deduped_path.begin() + deduped_root.size(), deduped_path.end(), SEP);
188 }
189 
ReadDescriptors(CgroupDescriptorMap * descriptors)190 bool ReadDescriptors(CgroupDescriptorMap* descriptors) {
191     // load system cgroup descriptors
192     if (!ReadDescriptorsFromFile(CGROUPS_DESC_FILE, descriptors)) {
193         return false;
194     }
195 
196     // load API-level specific system cgroups descriptors if available
197     unsigned int api_level = GetUintProperty<unsigned int>("ro.product.first_api_level", 0);
198     if (api_level > 0) {
199         std::string api_cgroups_path =
200                 android::base::StringPrintf(TEMPLATE_CGROUPS_DESC_API_FILE, api_level);
201         if (!access(api_cgroups_path.c_str(), F_OK) || errno != ENOENT) {
202             if (!ReadDescriptorsFromFile(api_cgroups_path, descriptors)) {
203                 return false;
204             }
205         }
206     }
207 
208     // load vendor cgroup descriptors if the file exists
209     if (!access(CGROUPS_DESC_VENDOR_FILE, F_OK) &&
210         !ReadDescriptorsFromFile(CGROUPS_DESC_VENDOR_FILE, descriptors)) {
211         return false;
212     }
213 
214     // check for v1 mount/usability status
215     std::optional<std::map<MountDir, MountOpts>> v1Mounts;
216     for (auto& [name, descriptor] : *descriptors) {
217         const CgroupController* const controller = descriptor.controller();
218 
219         if (controller->version() != 1) continue;
220 
221         // Read only once, and only if we have at least one v1 controller
222         if (!v1Mounts) {
223             v1Mounts = ReadCgroupV1Mounts();
224             if (!v1Mounts) return false;
225         }
226 
227         if (const auto it = v1Mounts->find(controller->path()); it != v1Mounts->end()) {
228             if (it->second.contains(controller->name())) descriptor.set_mounted(true);
229         }
230     }
231 
232     return true;
233 }
234 
ActivateControllers(const std::string & path,const CgroupDescriptorMap & descriptors)235 bool ActivateControllers(const std::string& path, const CgroupDescriptorMap& descriptors) {
236     for (const auto& [name, descriptor] : descriptors) {
237         const uint32_t flags = descriptor.controller()->flags();
238         const uint32_t max_activation_depth = descriptor.controller()->max_activation_depth();
239         const unsigned int depth = GetCgroupDepth(descriptor.controller()->path(), path);
240 
241         if (flags & CGROUPRC_CONTROLLER_FLAG_NEEDS_ACTIVATION && depth < max_activation_depth) {
242             std::string str("+");
243             str.append(descriptor.controller()->name());
244             if (!android::base::WriteStringToFile(str, path + "/cgroup.subtree_control")) {
245                 if (flags & CGROUPRC_CONTROLLER_FLAG_OPTIONAL) {
246                     PLOG(WARNING) << "Activation of cgroup controller " << str
247                                   << " failed in path " << path;
248                 } else {
249                     return false;
250                 }
251             }
252         }
253     }
254     return true;
255 }
256 
257