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 "ProcStat.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::ReadFileToString;
35 using ::android::base::Result;
36 using ::android::base::StartsWith;
37 using base::ParseUint;
38 using base::Split;
39 
40 namespace {
41 
parseCpuStats(const std::string & data,CpuStats * cpuStats)42 bool parseCpuStats(const std::string& data, CpuStats* cpuStats) {
43     std::vector<std::string> fields = Split(data, " ");
44     if (fields.size() == 12 && fields[1].empty()) {
45         /* The first cpu line will have an extra space after the first word. This will generate an
46          * empty element when the line is split on " ". Erase the extra element.
47          */
48         fields.erase(fields.begin() + 1);
49     }
50     if (fields.size() != 11 || fields[0] != "cpu" || !ParseUint(fields[1], &cpuStats->userTime) ||
51         !ParseUint(fields[2], &cpuStats->niceTime) || !ParseUint(fields[3], &cpuStats->sysTime) ||
52         !ParseUint(fields[4], &cpuStats->idleTime) ||
53         !ParseUint(fields[5], &cpuStats->ioWaitTime) || !ParseUint(fields[6], &cpuStats->irqTime) ||
54         !ParseUint(fields[7], &cpuStats->softIrqTime) ||
55         !ParseUint(fields[8], &cpuStats->stealTime) ||
56         !ParseUint(fields[9], &cpuStats->guestTime) ||
57         !ParseUint(fields[10], &cpuStats->guestNiceTime)) {
58         ALOGW("Invalid cpu line: \"%s\"", data.c_str());
59         return false;
60     }
61     return true;
62 }
63 
parseProcsCount(const std::string & data,uint32_t * out)64 bool parseProcsCount(const std::string& data, uint32_t* out) {
65     std::vector<std::string> fields = Split(data, " ");
66     if (fields.size() != 2 || !StartsWith(fields[0], "procs_") || !ParseUint(fields[1], out)) {
67         ALOGW("Invalid procs_ line: \"%s\"", data.c_str());
68         return false;
69     }
70     return true;
71 }
72 
73 }  // namespace
74 
collect()75 Result<void> ProcStat::collect() {
76     if (!kEnabled) {
77         return Error() << "Can not access " << kPath;
78     }
79 
80     Mutex::Autolock lock(mMutex);
81     const auto& info = getProcStatLocked();
82     if (!info.ok()) {
83         return Error() << "Failed to get proc stat contents: " << info.error();
84     }
85 
86     mDeltaStats = *info;
87     mDeltaStats -= mLatestStats;
88     mLatestStats = *info;
89 
90     return {};
91 }
92 
getProcStatLocked() const93 Result<ProcStatInfo> ProcStat::getProcStatLocked() const {
94     std::string buffer;
95     if (!ReadFileToString(kPath, &buffer)) {
96         return Error() << "ReadFileToString failed for " << kPath;
97     }
98 
99     std::vector<std::string> lines = Split(std::move(buffer), "\n");
100     ProcStatInfo info;
101     bool didReadProcsRunning = false;
102     bool didReadProcsBlocked = false;
103     for (size_t i = 0; i < lines.size(); i++) {
104         if (lines[i].empty()) {
105             continue;
106         }
107         if (!lines[i].compare(0, 4, "cpu ")) {
108             if (info.totalCpuTime() != 0) {
109                 return Error() << "Duplicate `cpu .*` line in " << kPath;
110             }
111             if (!parseCpuStats(std::move(lines[i]), &info.cpuStats)) {
112                 return Error() << "Failed to parse `cpu .*` line in " << kPath;
113             }
114         } else if (!lines[i].compare(0, 6, "procs_")) {
115             if (!lines[i].compare(0, 13, "procs_running")) {
116                 if (didReadProcsRunning) {
117                     return Error() << "Duplicate `procs_running .*` line in " << kPath;
118                 }
119                 if (!parseProcsCount(std::move(lines[i]), &info.runnableProcessCount)) {
120                     return Error() << "Failed to parse `procs_running .*` line in " << kPath;
121                 }
122                 didReadProcsRunning = true;
123                 continue;
124             } else if (!lines[i].compare(0, 13, "procs_blocked")) {
125                 if (didReadProcsBlocked) {
126                     return Error() << "Duplicate `procs_blocked .*` line in " << kPath;
127                 }
128                 if (!parseProcsCount(std::move(lines[i]), &info.ioBlockedProcessCount)) {
129                     return Error() << "Failed to parse `procs_blocked .*` line in " << kPath;
130                 }
131                 didReadProcsBlocked = true;
132                 continue;
133             }
134             return Error() << "Unknown procs_ line `" << lines[i] << "` in " << kPath;
135         }
136     }
137     if (info.totalCpuTime() == 0 || !didReadProcsRunning || !didReadProcsBlocked) {
138         return Error() << kPath << " is incomplete";
139     }
140     return info;
141 }
142 
143 }  // namespace watchdog
144 }  // namespace automotive
145 }  // namespace android
146