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 #define LOG_TAG "carwatchdogd"
18 
19 #include "ProcStatCollector.h"
20 
21 #include <android-base/file.h>
22 #include <android-base/parseint.h>
23 #include <android-base/strings.h>
24 #include <log/log.h>
25 
26 #include <string>
27 #include <vector>
28 
29 namespace android {
30 namespace automotive {
31 namespace watchdog {
32 
33 using ::android::base::Error;
34 using ::android::base::ParseInt;
35 using ::android::base::ParseUint;
36 using ::android::base::ReadFileToString;
37 using ::android::base::Result;
38 using ::android::base::Split;
39 using ::android::base::StartsWith;
40 
41 namespace {
42 
parseCpuStats(const std::string & data,int32_t millisPerClockTick,CpuStats * cpuStats)43 bool parseCpuStats(const std::string& data, int32_t millisPerClockTick, CpuStats* cpuStats) {
44     std::vector<std::string> fields = Split(data, " ");
45     if (fields.size() == 12 && fields[1].empty()) {
46         /* The first cpu line will have an extra space after the first word. This will generate an
47          * empty element when the line is split on " ". Erase the extra element.
48          */
49         fields.erase(fields.begin() + 1);
50     }
51     if (fields.size() != 11 || fields[0] != "cpu" ||
52         !ParseInt(fields[1], &cpuStats->userTimeMillis) ||
53         !ParseInt(fields[2], &cpuStats->niceTimeMillis) ||
54         !ParseInt(fields[3], &cpuStats->sysTimeMillis) ||
55         !ParseInt(fields[4], &cpuStats->idleTimeMillis) ||
56         !ParseInt(fields[5], &cpuStats->ioWaitTimeMillis) ||
57         !ParseInt(fields[6], &cpuStats->irqTimeMillis) ||
58         !ParseInt(fields[7], &cpuStats->softIrqTimeMillis) ||
59         !ParseInt(fields[8], &cpuStats->stealTimeMillis) ||
60         !ParseInt(fields[9], &cpuStats->guestTimeMillis) ||
61         !ParseInt(fields[10], &cpuStats->guestNiceTimeMillis)) {
62         ALOGW("Invalid cpu line: \"%s\"", data.c_str());
63         return false;
64     }
65     // Convert clock ticks to millis
66     cpuStats->userTimeMillis *= millisPerClockTick;
67     cpuStats->niceTimeMillis *= millisPerClockTick;
68     cpuStats->sysTimeMillis *= millisPerClockTick;
69     cpuStats->idleTimeMillis *= millisPerClockTick;
70     cpuStats->ioWaitTimeMillis *= millisPerClockTick;
71     cpuStats->irqTimeMillis *= millisPerClockTick;
72     cpuStats->softIrqTimeMillis *= millisPerClockTick;
73     cpuStats->stealTimeMillis *= millisPerClockTick;
74     cpuStats->guestTimeMillis *= millisPerClockTick;
75     cpuStats->guestNiceTimeMillis *= millisPerClockTick;
76     return true;
77 }
78 
parseContextSwitches(const std::string & data,uint64_t * out)79 bool parseContextSwitches(const std::string& data, uint64_t* out) {
80     std::vector<std::string> fields = Split(data, " ");
81     if (fields.size() != 2 || !StartsWith(fields[0], "ctxt") || !ParseUint(fields[1], out)) {
82         ALOGW("Invalid ctxt line: \"%s\"", data.c_str());
83         return false;
84     }
85     return true;
86 }
87 
parseProcsCount(const std::string & data,uint32_t * out)88 bool parseProcsCount(const std::string& data, uint32_t* out) {
89     std::vector<std::string> fields = Split(data, " ");
90     if (fields.size() != 2 || !StartsWith(fields[0], "procs_") || !ParseUint(fields[1], out)) {
91         ALOGW("Invalid procs_ line: \"%s\"", data.c_str());
92         return false;
93     }
94     return true;
95 }
96 
97 }  // namespace
98 
collect()99 Result<void> ProcStatCollector::collect() {
100     if (!mEnabled) {
101         return Error() << "Cannot access " << kPath;
102     }
103 
104     Mutex::Autolock lock(mMutex);
105     const auto& info = getProcStatLocked();
106     if (!info.ok()) {
107         return Error() << "Failed to get proc stat contents: " << info.error();
108     }
109 
110     mDeltaStats = *info;
111     mDeltaStats -= mLatestStats;
112     mLatestStats = *info;
113 
114     return {};
115 }
116 
getProcStatLocked() const117 Result<ProcStatInfo> ProcStatCollector::getProcStatLocked() const {
118     std::string buffer;
119     if (!ReadFileToString(kPath, &buffer)) {
120         return Error() << "ReadFileToString failed for " << kPath;
121     }
122 
123     std::vector<std::string> lines = Split(std::move(buffer), "\n");
124     ProcStatInfo info;
125     bool didReadContextSwitches = false;
126     bool didReadProcsRunning = false;
127     bool didReadProcsBlocked = false;
128     for (size_t i = 0; i < lines.size(); i++) {
129         if (lines[i].empty()) {
130             continue;
131         }
132         if (!lines[i].compare(0, 4, "cpu ")) {
133             if (info.totalCpuTimeMillis() != 0) {
134                 return Error() << "Duplicate `cpu .*` line in " << kPath;
135             }
136             if (!parseCpuStats(lines[i], mMillisPerClockTick, &info.cpuStats)) {
137                 return Error() << "Failed to parse `cpu .*` line in " << kPath;
138             }
139         } else if (!lines[i].compare(0, 4, "ctxt")) {
140             if (didReadContextSwitches) {
141                 return Error() << "Duplicate `ctxt .*` line in " << kPath;
142             }
143             if (!parseContextSwitches(std::move(lines[i]), &info.contextSwitchesCount)) {
144                 return Error() << "Failed to parse `ctxt .*` line in " << kPath;
145             }
146             didReadContextSwitches = true;
147         } else if (!lines[i].compare(0, 6, "procs_")) {
148             if (!lines[i].compare(0, 13, "procs_running")) {
149                 if (didReadProcsRunning) {
150                     return Error() << "Duplicate `procs_running .*` line in " << kPath;
151                 }
152                 if (!parseProcsCount(std::move(lines[i]), &info.runnableProcessCount)) {
153                     return Error() << "Failed to parse `procs_running .*` line in " << kPath;
154                 }
155                 didReadProcsRunning = true;
156                 continue;
157             } else if (!lines[i].compare(0, 13, "procs_blocked")) {
158                 if (didReadProcsBlocked) {
159                     return Error() << "Duplicate `procs_blocked .*` line in " << kPath;
160                 }
161                 if (!parseProcsCount(std::move(lines[i]), &info.ioBlockedProcessCount)) {
162                     return Error() << "Failed to parse `procs_blocked .*` line in " << kPath;
163                 }
164                 didReadProcsBlocked = true;
165                 continue;
166             }
167             return Error() << "Unknown procs_ line `" << lines[i] << "` in " << kPath;
168         }
169     }
170     if (info.totalCpuTimeMillis() == 0 || !didReadContextSwitches || !didReadProcsRunning ||
171         !didReadProcsBlocked) {
172         return Error() << kPath << " is incomplete";
173     }
174     return info;
175 }
176 
177 }  // namespace watchdog
178 }  // namespace automotive
179 }  // namespace android
180