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 "UidIoStatsCollector.h"
20 
21 #include <android-base/file.h>
22 #include <android-base/parseint.h>
23 #include <android-base/stringprintf.h>
24 #include <android-base/strings.h>
25 #include <log/log.h>
26 
27 #include <inttypes.h>
28 
29 #include <string>
30 #include <unordered_map>
31 #include <utility>
32 #include <vector>
33 
34 namespace android {
35 namespace automotive {
36 namespace watchdog {
37 
38 using ::android::base::Error;
39 using ::android::base::ParseInt;
40 using ::android::base::ParseUint;
41 using ::android::base::ReadFileToString;
42 using ::android::base::Result;
43 using ::android::base::Split;
44 using ::android::base::StringPrintf;
45 
46 namespace {
47 
parseUidIoStats(const std::string & data,UidIoStats * stats,uid_t * uid)48 bool parseUidIoStats(const std::string& data, UidIoStats* stats, uid_t* uid) {
49     std::vector<std::string> fields = Split(data, " ");
50     if (fields.size() < 11 || !ParseUint(fields[0], uid) ||
51         !ParseInt(fields[3], &stats->metrics[READ_BYTES][FOREGROUND]) ||
52         !ParseInt(fields[4], &stats->metrics[WRITE_BYTES][FOREGROUND]) ||
53         !ParseInt(fields[7], &stats->metrics[READ_BYTES][BACKGROUND]) ||
54         !ParseInt(fields[8], &stats->metrics[WRITE_BYTES][BACKGROUND]) ||
55         !ParseInt(fields[9], &stats->metrics[FSYNC_COUNT][FOREGROUND]) ||
56         !ParseInt(fields[10], &stats->metrics[FSYNC_COUNT][BACKGROUND])) {
57         ALOGW("Invalid uid I/O stats: \"%s\"", data.c_str());
58         return false;
59     }
60     return true;
61 }
62 
63 }  // namespace
64 
operator -=(const UidIoStats & rhs)65 UidIoStats& UidIoStats::operator-=(const UidIoStats& rhs) {
66     const auto diff = [](int64_t lhs, int64_t rhs) -> int64_t { return lhs > rhs ? lhs - rhs : 0; };
67     metrics[READ_BYTES][FOREGROUND] =
68             diff(metrics[READ_BYTES][FOREGROUND], rhs.metrics[READ_BYTES][FOREGROUND]);
69     metrics[READ_BYTES][BACKGROUND] =
70             diff(metrics[READ_BYTES][BACKGROUND], rhs.metrics[READ_BYTES][BACKGROUND]);
71     metrics[WRITE_BYTES][FOREGROUND] =
72             diff(metrics[WRITE_BYTES][FOREGROUND], rhs.metrics[WRITE_BYTES][FOREGROUND]);
73     metrics[WRITE_BYTES][BACKGROUND] =
74             diff(metrics[WRITE_BYTES][BACKGROUND], rhs.metrics[WRITE_BYTES][BACKGROUND]);
75     metrics[FSYNC_COUNT][FOREGROUND] =
76             diff(metrics[FSYNC_COUNT][FOREGROUND], rhs.metrics[FSYNC_COUNT][FOREGROUND]);
77     metrics[FSYNC_COUNT][BACKGROUND] =
78             diff(metrics[FSYNC_COUNT][BACKGROUND], rhs.metrics[FSYNC_COUNT][BACKGROUND]);
79     return *this;
80 }
81 
isZero() const82 bool UidIoStats::isZero() const {
83     for (int i = 0; i < METRIC_TYPES; i++) {
84         for (int j = 0; j < UID_STATES; j++) {
85             if (metrics[i][j]) {
86                 return false;
87             }
88         }
89     }
90     return true;
91 }
92 
toString() const93 std::string UidIoStats::toString() const {
94     return StringPrintf("FgRdBytes:%" PRIi64 " BgRdBytes:%" PRIi64 " FgWrBytes:%" PRIi64
95                         " BgWrBytes:%" PRIi64 " FgFsync:%" PRIi64 " BgFsync:%" PRIi64,
96                         metrics[READ_BYTES][FOREGROUND], metrics[READ_BYTES][BACKGROUND],
97                         metrics[WRITE_BYTES][FOREGROUND], metrics[WRITE_BYTES][BACKGROUND],
98                         metrics[FSYNC_COUNT][FOREGROUND], metrics[FSYNC_COUNT][BACKGROUND]);
99 }
100 
collect()101 Result<void> UidIoStatsCollector::collect() {
102     if (!mEnabled) {
103         return Error() << "Can not access " << kPath;
104     }
105 
106     Mutex::Autolock lock(mMutex);
107     const auto& uidIoStatsByUid = readUidIoStatsLocked();
108     if (!uidIoStatsByUid.ok() || uidIoStatsByUid->empty()) {
109         return Error() << "Failed to get UID IO stats: " << uidIoStatsByUid.error();
110     }
111 
112     mDeltaStats.clear();
113     for (const auto& [uid, uidIoStats] : *uidIoStatsByUid) {
114         if (uidIoStats.isZero()) {
115             continue;
116         }
117         UidIoStats deltaStats = uidIoStats;
118         if (const auto it = mLatestStats.find(uid); it != mLatestStats.end()) {
119             if (deltaStats -= it->second; deltaStats.isZero()) {
120                 continue;
121             }
122         }
123         mDeltaStats[uid] = deltaStats;
124     }
125     mLatestStats = *uidIoStatsByUid;
126     return {};
127 }
128 
readUidIoStatsLocked() const129 Result<std::unordered_map<uid_t, UidIoStats>> UidIoStatsCollector::readUidIoStatsLocked() const {
130     std::string buffer;
131     if (!ReadFileToString(kPath, &buffer)) {
132         return Error() << "ReadFileToString failed for " << kPath;
133     }
134     std::unordered_map<uid_t, UidIoStats> uidIoStatsByUid;
135     std::vector<std::string> lines = Split(std::move(buffer), "\n");
136     for (const auto& line : lines) {
137         if (line.empty() || !line.compare(0, 4, "task")) {
138             /* Skip per-task stats as CONFIG_UID_SYS_STATS_DEBUG is not set in the kernel and
139              * the collected data is aggregated only per-UID.
140              */
141             continue;
142         }
143         uid_t uid;
144         UidIoStats uidIoStats;
145         if (!parseUidIoStats(line, &uidIoStats, &uid)) {
146             return Error() << "Failed to parse the contents of " << kPath;
147         }
148         uidIoStatsByUid[uid] = uidIoStats;
149     }
150     return uidIoStatsByUid;
151 }
152 
153 }  // namespace watchdog
154 }  // namespace automotive
155 }  // namespace android
156