xref: /aosp_15_r20/system/core/libprocessgroup/util/util.cpp (revision 00c7fec1bb09f3284aad6a6f96d2f63dfc3650ad)
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     static constexpr bool force_memcg_v2 = android::libprocessgroup_flags::force_memcg_v2();
115     std::vector<CgroupDescriptor> result;
116     std::string json_doc;
117 
118     if (!android::base::ReadFileToString(file_name, &json_doc)) {
119         PLOG(ERROR) << "Failed to read task profiles from " << file_name;
120         return false;
121     }
122 
123     Json::CharReaderBuilder builder;
124     std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
125     Json::Value root;
126     std::string errorMessage;
127     if (!reader->parse(&*json_doc.begin(), &*json_doc.end(), &root, &errorMessage)) {
128         LOG(ERROR) << "Failed to parse cgroups description: " << errorMessage;
129         return false;
130     }
131 
132     if (root.isMember("Cgroups")) {
133         const Json::Value& cgroups = root["Cgroups"];
134         for (Json::Value::ArrayIndex i = 0; i < cgroups.size(); ++i) {
135             std::string name = cgroups[i]["Controller"].asString();
136 
137             if (force_memcg_v2 && name == "memory") continue;
138 
139             MergeCgroupToDescriptors(descriptors, cgroups[i], name, "", 1);
140         }
141     }
142 
143     bool memcgv2_present = false;
144     std::string root_path;
145     if (root.isMember("Cgroups2")) {
146         const Json::Value& cgroups2 = root["Cgroups2"];
147         root_path = cgroups2["Path"].asString();
148         MergeCgroupToDescriptors(descriptors, cgroups2, CGROUPV2_HIERARCHY_NAME_INTERNAL, "", 2);
149 
150         const Json::Value& childGroups = cgroups2["Controllers"];
151         for (Json::Value::ArrayIndex i = 0; i < childGroups.size(); ++i) {
152             std::string name = childGroups[i]["Controller"].asString();
153 
154             if (force_memcg_v2 && name == "memory") memcgv2_present = true;
155 
156             MergeCgroupToDescriptors(descriptors, childGroups[i], name, root_path, 2);
157         }
158     }
159 
160     if (force_memcg_v2 && !memcgv2_present) {
161         LOG(INFO) << "Forcing memcg to v2 hierarchy";
162         Json::Value memcgv2;
163         memcgv2["Controller"] = "memory";
164         memcgv2["NeedsActivation"] = true;
165         memcgv2["Path"] = ".";
166         memcgv2["Optional"] = true;  // In case of cgroup_disabled=memory, so we can still boot
167         MergeCgroupToDescriptors(descriptors, memcgv2, "memory",
168                                  root_path.empty() ? CGROUP_V2_ROOT_DEFAULT : root_path, 2);
169     }
170 
171     return true;
172 }
173 
174 using MountDir = std::string;
175 using MountOpts = std::string;
ReadCgroupV1Mounts()176 static std::optional<std::map<MountDir, MountOpts>> ReadCgroupV1Mounts() {
177     FILE* fp = setmntent("/proc/mounts", "r");
178     if (fp == nullptr) {
179         PLOG(ERROR) << "Failed to read mounts";
180         return std::nullopt;
181     }
182 
183     std::map<MountDir, MountOpts> mounts;
184     const std::string_view CGROUP_V1_TYPE = "cgroup";
185     for (mntent* mentry = getmntent(fp); mentry != nullptr; mentry = getmntent(fp)) {
186         if (mentry->mnt_type && CGROUP_V1_TYPE == mentry->mnt_type &&
187             mentry->mnt_dir && mentry->mnt_opts) {
188             mounts[mentry->mnt_dir] = mentry->mnt_opts;
189         }
190     }
191     endmntent(fp);
192 
193     return mounts;
194 }
195 
196 }  // anonymous namespace
197 
198 
GetCgroupDepth(const std::string & controller_root,const std::string & cgroup_path)199 unsigned int GetCgroupDepth(const std::string& controller_root, const std::string& cgroup_path) {
200     const std::string deduped_root = DeduplicateAndTrimSeparators(controller_root);
201     const std::string deduped_path = DeduplicateAndTrimSeparators(cgroup_path);
202 
203     if (deduped_root.empty() || deduped_path.empty() || !deduped_path.starts_with(deduped_root))
204         return 0;
205 
206     return std::count(deduped_path.begin() + deduped_root.size(), deduped_path.end(), SEP);
207 }
208 
ReadDescriptors(CgroupDescriptorMap * descriptors)209 bool ReadDescriptors(CgroupDescriptorMap* descriptors) {
210     // load system cgroup descriptors
211     if (!ReadDescriptorsFromFile(CGROUPS_DESC_FILE, descriptors)) {
212         return false;
213     }
214 
215     // load API-level specific system cgroups descriptors if available
216     unsigned int api_level = GetUintProperty<unsigned int>("ro.product.first_api_level", 0);
217     if (api_level > 0) {
218         std::string api_cgroups_path =
219                 android::base::StringPrintf(TEMPLATE_CGROUPS_DESC_API_FILE, api_level);
220         if (!access(api_cgroups_path.c_str(), F_OK) || errno != ENOENT) {
221             if (!ReadDescriptorsFromFile(api_cgroups_path, descriptors)) {
222                 return false;
223             }
224         }
225     }
226 
227     // load vendor cgroup descriptors if the file exists
228     if (!access(CGROUPS_DESC_VENDOR_FILE, F_OK) &&
229         !ReadDescriptorsFromFile(CGROUPS_DESC_VENDOR_FILE, descriptors)) {
230         return false;
231     }
232 
233     // check for v1 mount/usability status
234     std::optional<std::map<MountDir, MountOpts>> v1Mounts;
235     for (auto& [name, descriptor] : *descriptors) {
236         const CgroupController* const controller = descriptor.controller();
237 
238         if (controller->version() != 1) continue;
239 
240         // Read only once, and only if we have at least one v1 controller
241         if (!v1Mounts) {
242             v1Mounts = ReadCgroupV1Mounts();
243             if (!v1Mounts) return false;
244         }
245 
246         if (const auto it = v1Mounts->find(controller->path()); it != v1Mounts->end()) {
247             if (it->second.contains(controller->name())) descriptor.set_mounted(true);
248         }
249     }
250 
251     return true;
252 }
253 
ActivateControllers(const std::string & path,const CgroupDescriptorMap & descriptors)254 bool ActivateControllers(const std::string& path, const CgroupDescriptorMap& descriptors) {
255     for (const auto& [name, descriptor] : descriptors) {
256         const uint32_t flags = descriptor.controller()->flags();
257         const uint32_t max_activation_depth = descriptor.controller()->max_activation_depth();
258         const unsigned int depth = GetCgroupDepth(descriptor.controller()->path(), path);
259 
260         if (flags & CGROUPRC_CONTROLLER_FLAG_NEEDS_ACTIVATION && depth < max_activation_depth) {
261             std::string str("+");
262             str.append(descriptor.controller()->name());
263             if (!android::base::WriteStringToFile(str, path + "/cgroup.subtree_control")) {
264                 if (flags & CGROUPRC_CONTROLLER_FLAG_OPTIONAL) {
265                     PLOG(WARNING) << "Activation of cgroup controller " << str
266                                   << " failed in path " << path;
267                 } else {
268                     return false;
269                 }
270             }
271         }
272     }
273     return true;
274 }
275 
276