xref: /aosp_15_r20/system/core/libprocessgroup/cgroup_map.h (revision 00c7fec1bb09f3284aad6a6f96d2f63dfc3650ad)
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 #pragma once
18 
19 #include <sys/types.h>
20 
21 #include <cstdint>
22 #include <string>
23 
24 #include <processgroup/cgroup_controller.h>
25 #include <processgroup/util.h>
26 
27 // Convenient wrapper of a CgroupController pointer.
28 class CgroupControllerWrapper {
29   public:
30     // Does not own controller
CgroupControllerWrapper(const CgroupController * controller)31     explicit CgroupControllerWrapper(const CgroupController* controller)
32         : controller_(controller) {}
33 
34     uint32_t version() const;
35     const char* name() const;
36     const char* path() const;
37 
38     bool HasValue() const;
39     bool IsUsable();
40 
41     std::string GetTasksFilePath(const std::string& path) const;
42     std::string GetProcsFilePath(const std::string& path, uid_t uid, pid_t pid) const;
43     bool GetTaskGroup(pid_t tid, std::string* group) const;
44 
45   private:
46     enum ControllerState {
47         UNKNOWN = 0,
48         USABLE = 1,
49         MISSING = 2,
50     };
51 
52     const CgroupController* controller_ = nullptr; // CgroupMap owns the object behind this pointer
53     ControllerState state_ = ControllerState::UNKNOWN;
54 };
55 
56 class CgroupMap {
57   public:
58     static CgroupMap& GetInstance();
59     CgroupControllerWrapper FindController(const std::string& name) const;
60     CgroupControllerWrapper FindControllerByPath(const std::string& path) const;
61     bool ActivateControllers(const std::string& path) const;
62 
63   private:
64     bool loaded_ = false;
65     CgroupDescriptorMap descriptors_;
66     CgroupMap();
67     bool LoadDescriptors();
68     void Print() const;
69 };
70