1 /**
2  * Copyright (c) 2020, 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 #ifndef CPP_WATCHDOG_SERVER_SRC_PROCSTAT_H_
18 #define CPP_WATCHDOG_SERVER_SRC_PROCSTAT_H_
19 
20 #include <android-base/result.h>
21 #include <utils/Mutex.h>
22 #include <utils/RefBase.h>
23 
24 #include <stdint.h>
25 
26 namespace android {
27 namespace automotive {
28 namespace watchdog {
29 
30 constexpr const char* kProcStatPath = "/proc/stat";
31 
32 struct CpuStats {
33     uint64_t userTime = 0;       // Time spent in user mode.
34     uint64_t niceTime = 0;       // Time spent in user mode with low priority (nice).
35     uint64_t sysTime = 0;        // Time spent in system mode.
36     uint64_t idleTime = 0;       // Time spent in the idle task.
37     uint64_t ioWaitTime = 0;     // Time spent on context switching/waiting due to I/O operations.
38     uint64_t irqTime = 0;        // Time servicing interrupts.
39     uint64_t softIrqTime = 0;    // Time servicing soft interrupts.
40     uint64_t stealTime = 0;      // Stolen time (Time spent in other OS in a virtualized env).
41     uint64_t guestTime = 0;      // Time spent running a virtual CPU for guest OS.
42     uint64_t guestNiceTime = 0;  // Time spent running a niced virtual CPU for guest OS.
43 
44     CpuStats& operator-=(const CpuStats& rhs) {
45         userTime -= rhs.userTime;
46         niceTime -= rhs.niceTime;
47         sysTime -= rhs.sysTime;
48         idleTime -= rhs.idleTime;
49         ioWaitTime -= rhs.ioWaitTime;
50         irqTime -= rhs.irqTime;
51         softIrqTime -= rhs.softIrqTime;
52         stealTime -= rhs.stealTime;
53         guestTime -= rhs.guestTime;
54         guestNiceTime -= rhs.guestNiceTime;
55         return *this;
56     }
57 };
58 
59 class ProcStatInfo {
60 public:
ProcStatInfo()61     ProcStatInfo() : cpuStats({}), runnableProcessCount(0), ioBlockedProcessCount(0) {}
ProcStatInfo(CpuStats stats,uint32_t runnableCnt,uint32_t ioBlockedCnt)62     ProcStatInfo(CpuStats stats, uint32_t runnableCnt, uint32_t ioBlockedCnt) :
63           cpuStats(stats),
64           runnableProcessCount(runnableCnt),
65           ioBlockedProcessCount(ioBlockedCnt) {}
66     CpuStats cpuStats;
67     uint32_t runnableProcessCount;
68     uint32_t ioBlockedProcessCount;
69 
totalCpuTime()70     uint64_t totalCpuTime() const {
71         return cpuStats.userTime + cpuStats.niceTime + cpuStats.sysTime + cpuStats.idleTime +
72                 cpuStats.ioWaitTime + cpuStats.irqTime + cpuStats.softIrqTime + cpuStats.stealTime +
73                 cpuStats.guestTime + cpuStats.guestNiceTime;
74     }
totalProcessCount()75     uint32_t totalProcessCount() const { return runnableProcessCount + ioBlockedProcessCount; }
76     bool operator==(const ProcStatInfo& info) const {
77         return memcmp(&cpuStats, &info.cpuStats, sizeof(cpuStats)) == 0 &&
78                 runnableProcessCount == info.runnableProcessCount &&
79                 ioBlockedProcessCount == info.ioBlockedProcessCount;
80     }
81     ProcStatInfo& operator-=(const ProcStatInfo& rhs) {
82         cpuStats -= rhs.cpuStats;
83         /* Don't diff *ProcessCount as they are real-time values unlike |cpuStats|, which are
84          * aggregated values since system startup.
85          */
86         return *this;
87     }
88 };
89 
90 // Collector/parser for `/proc/stat` file.
91 class ProcStat : public RefBase {
92 public:
93     explicit ProcStat(const std::string& path = kProcStatPath) :
94           mLatestStats({}),
95           kEnabled(!access(path.c_str(), R_OK)),
96           kPath(path) {}
97 
~ProcStat()98     virtual ~ProcStat() {}
99 
100     // Collects proc stat delta since the last collection.
101     virtual android::base::Result<void> collect();
102 
103     /* Returns true when the proc stat file is accessible. Otherwise, returns false.
104      * Called by WatchdogPerfService and tests.
105      */
enabled()106     virtual bool enabled() { return kEnabled; }
107 
filePath()108     virtual std::string filePath() { return kProcStatPath; }
109 
110     // Returns the latest stats.
latestStats()111     virtual const ProcStatInfo latestStats() const {
112         Mutex::Autolock lock(mMutex);
113         return mLatestStats;
114     }
115 
116     // Returns the delta of stats from the latest collection.
deltaStats()117     virtual const ProcStatInfo deltaStats() const {
118         Mutex::Autolock lock(mMutex);
119         return mDeltaStats;
120     }
121 
122 private:
123     // Reads the contents of |kPath|.
124     android::base::Result<ProcStatInfo> getProcStatLocked() const;
125 
126     // Makes sure only one collection is running at any given time.
127     mutable Mutex mMutex;
128 
129     // Latest dump of CPU stats from the file at |kPath|.
130     ProcStatInfo mLatestStats GUARDED_BY(mMutex);
131 
132     // Delta of CPU stats from the latest collection.
133     ProcStatInfo mDeltaStats GUARDED_BY(mMutex);
134 
135     // True if |kPath| is accessible.
136     const bool kEnabled;
137 
138     // Path to proc stat file. Default path is |kProcStatPath|.
139     const std::string kPath;
140 };
141 
142 }  // namespace watchdog
143 }  // namespace automotive
144 }  // namespace android
145 
146 #endif  //  CPP_WATCHDOG_SERVER_SRC_PROCSTAT_H_
147