1 /*
2  * Copyright (c) 2021, 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 <android-base/result.h>
20 #include <android-base/stringprintf.h>
21 #include <android-base/strings.h>
22 #include <utils/Mutex.h>
23 #include <utils/RefBase.h>
24 
25 #include <string>
26 #include <unordered_set>
27 #include <vector>
28 
29 namespace android {
30 namespace automotive {
31 namespace watchdog {
32 
33 constexpr const char* kProcDiskStatsPath = "/proc/diskstats";
34 
recordStatsForDevice(const std::string & deviceName)35 inline constexpr bool recordStatsForDevice(const std::string& deviceName) {
36     for (const auto& prefix : {"zram", "ram"}) {
37         if (android::base::StartsWith(deviceName, prefix)) {
38             return false;
39         }
40     }
41     return true;
42 }
43 
44 // Struct that represents the stats from |kUidIoStatsPath|.
45 struct DiskStats {
46     int major = 0;
47     int minor = 0;
48     std::string deviceName;
49     uint64_t numReadsCompleted = 0;
50     uint64_t numReadsMerged = 0;
51     uint64_t numKibRead = 0;
52     uint64_t readTimeInMillis = 0;
53     uint64_t numWritesCompleted = 0;
54     uint64_t numWritesMerged = 0;
55     uint64_t numKibWritten = 0;
56     uint64_t writeTimeInMillis = 0;
57     uint64_t totalIoTimeInMillis = 0;
58     uint64_t weightedTotalIoTimeInMillis = 0;
59     uint64_t numFlushCompleted = 0;
60     uint64_t flushTimeInMillis = 0;
61 
62     DiskStats& operator-=(const DiskStats& rhs);
63     DiskStats& operator+=(const DiskStats& rhs);
64     struct HashByPartition {
65         size_t operator()(const DiskStats& stats) const;
66     };
67     struct EqualByPartition {
68         bool operator()(const DiskStats& lhs, const DiskStats& rhs) const;
69     };
70 };
71 
72 /*
73  * Contains methods that should be implemented by the /proc/diskstats reader or any mock reader
74  * used in tests.
75  */
76 class ProcDiskStatsCollectorInterface : virtual public android::RefBase {
77 public:
78     using PerPartitionDiskStats = ::std::unordered_set<DiskStats, DiskStats::HashByPartition,
79                                                        DiskStats::EqualByPartition>;
80     // Initializes the collector.
81     virtual void init() = 0;
82 
83     // Collects the system-wide block devices statistics.
84     virtual android::base::Result<void> collect() = 0;
85 
86     // Returns the latest per-disk stats.
87     virtual PerPartitionDiskStats latestPerPartitionDiskStats() const = 0;
88 
89     // Returns the aggregated delta stats since the last before collection.
90     virtual DiskStats deltaSystemWideDiskStats() const = 0;
91 
92     // Returns true when the proc diskstats file is accessible. Otherwise, returns false.
93     virtual bool enabled() const = 0;
94 
95     // Path to the disk stats file.
96     virtual std::string filePath() const = 0;
97 };
98 
99 class ProcDiskStatsCollector final : public ProcDiskStatsCollectorInterface {
100 public:
kPath(path)101     explicit ProcDiskStatsCollector(const std::string& path = kProcDiskStatsPath) : kPath(path) {}
102 
~ProcDiskStatsCollector()103     ~ProcDiskStatsCollector() {}
104 
init()105     void init() {
106         Mutex::Autolock lock(mMutex);
107         // Note: Verify proc file access outside the constructor. Otherwise, the unittests of
108         // dependent classes would call the constructor before mocking and get killed due to
109         // sepolicy violation.
110         mEnabled = access(kPath.c_str(), R_OK) == 0;
111     }
112 
113     android::base::Result<void> collect();
114 
latestPerPartitionDiskStats()115     PerPartitionDiskStats latestPerPartitionDiskStats() const {
116         Mutex::Autolock lock(mMutex);
117         return mLatestPerPartitionDiskStats;
118     }
119 
deltaSystemWideDiskStats()120     DiskStats deltaSystemWideDiskStats() const {
121         Mutex::Autolock lock(mMutex);
122         return mDeltaSystemWideDiskStats;
123     }
124 
enabled()125     bool enabled() const {
126         Mutex::Autolock lock(mMutex);
127         return mEnabled;
128     }
129 
filePath()130     std::string filePath() const { return kPath; }
131 
132 private:
133     // Path to disk stats file.
134     const std::string kPath;
135 
136     // Makes sure only one collection is running at any given time.
137     mutable Mutex mMutex;
138 
139     // True if |kPath| is accessible.
140     bool mEnabled GUARDED_BY(mMutex);
141 
142     // Delta of per-UID I/O usage since last before collection.
143     DiskStats mDeltaSystemWideDiskStats GUARDED_BY(mMutex);
144 
145     /*
146      * Latest per-disk stats from the file at |kPath|. Per-disk stats is required for calculating
147      * per-disk delta since last collection. Because the stats reported in |kPath| may overflow,
148      * storing the stats per-disk helps to deal with this issue.
149      */
150     PerPartitionDiskStats mLatestPerPartitionDiskStats GUARDED_BY(mMutex);
151 };
152 
153 }  // namespace watchdog
154 }  // namespace automotive
155 }  // namespace android
156