blob: 9b88a223a61789bf952fddb4f7dc1e52a20c690b [file] [log] [blame]
T.J. Mercierae0b2902024-08-05 18:18:35 +00001/*
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
22namespace {
23
24const char SEP = '/';
25
26std::string DeduplicateAndTrimSeparators(const std::string& path) {
27 bool lastWasSep = false;
28 std::string ret;
29
30 std::copy_if(path.begin(), path.end(), std::back_inserter(ret), [&lastWasSep](char c) {
31 if (lastWasSep) {
32 if (c == SEP) return false;
33 lastWasSep = false;
34 } else if (c == SEP) {
35 lastWasSep = true;
36 }
37 return true;
38 });
39
40 if (ret.length() > 1 && ret.back() == SEP) ret.pop_back();
41
42 return ret;
43}
44
45} // anonymous namespace
46
47namespace util {
48
49unsigned int GetCgroupDepth(const std::string& controller_root, const std::string& cgroup_path) {
50 const std::string deduped_root = DeduplicateAndTrimSeparators(controller_root);
51 const std::string deduped_path = DeduplicateAndTrimSeparators(cgroup_path);
52
53 if (deduped_root.empty() || deduped_path.empty() || !deduped_path.starts_with(deduped_root))
54 return 0;
55
56 return std::count(deduped_path.begin() + deduped_root.size(), deduped_path.end(), SEP);
57}
58
59} // namespace util