1 /*
2 * Copyright (C) 2019 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 "perfstatsd_io"
18
19 #include "io_usage.h"
20 #include <android-base/parseint.h>
21 #include <android-base/stringprintf.h>
22 #include <android-base/strings.h>
23 #include <cutils/android_filesystem_config.h>
24 #include <inttypes.h>
25 #include <pwd.h>
26
27 using namespace android::pixel::perfstatsd;
28 static constexpr const char *UID_IO_STATS_PATH = "/proc/uid_io/stats";
29 static constexpr char FMT_STR_TOTAL_USAGE[] =
30 "[IO_TOTAL: %lld.%03llds] RD:%s WR:%s fsync:%" PRIu64 "\n";
31 static constexpr char STR_TOP_HEADER[] =
32 "[IO_TOP ] fg bytes, bg bytes,fgsyn,bgsyn : UID PKG_NAME\n";
33 static constexpr char FMT_STR_TOP_WRITE_USAGE[] =
34 "[W%d:%6.2f%%]%12" PRIu64 ",%12" PRIu64 ",%5" PRIu64 ",%5" PRIu64 " :%6u %s\n";
35 static constexpr char FMT_STR_TOP_READ_USAGE[] =
36 "[R%d:%6.2f%%]%12" PRIu64 ",%12" PRIu64 ",%5" PRIu64 ",%5" PRIu64 " :%6u %s\n";
37 static constexpr char FMT_STR_SKIP_TOP_READ[] = "(< %" PRIu64 "MB)skip RD";
38 static constexpr char FMT_STR_SKIP_TOP_WRITE[] = "(< %" PRIu64 "MB)skip WR";
39
40 static bool sOptDebug = false;
41
42 /* format number with comma
43 * Ex: 10000 => 10,000
44 */
formatNum(uint64_t x,char * str,int size)45 static bool formatNum(uint64_t x, char *str, int size) {
46 int len = snprintf(str, size, "%" PRIu64, x);
47 if (len + 1 > size) {
48 return false;
49 }
50 int extr = ((len - 1) / 3);
51 int endpos = len + extr;
52 if (endpos > size) {
53 return false;
54 }
55 uint32_t d = 0;
56 str[endpos] = 0;
57 for (int i = 0, j = endpos - 1; i < len; i++) {
58 d = x % 10;
59 x = x / 10;
60 str[j--] = '0' + d;
61 if (i % 3 == 2) {
62 if (j >= 0)
63 str[j--] = ',';
64 }
65 }
66 return true;
67 }
68
isAppUid(uint32_t uid)69 static bool isAppUid(uint32_t uid) {
70 if (uid >= AID_APP_START) {
71 return true;
72 }
73 return false;
74 }
75
getNewPids()76 std::vector<uint32_t> ProcPidIoStats::getNewPids() {
77 std::vector<uint32_t> newpids;
78 // Not exists in Previous
79 for (int i = 0, len = mCurrPids.size(); i < len; i++) {
80 if (std::find(mPrevPids.begin(), mPrevPids.end(), mCurrPids[i]) == mPrevPids.end()) {
81 newpids.push_back(mCurrPids[i]);
82 }
83 }
84 return newpids;
85 }
86
update(bool forceAll)87 void ProcPidIoStats::update(bool forceAll) {
88 ScopeTimer _debugTimer("update: /proc/pid/status for UID/Name mapping");
89 _debugTimer.setEnabled(sOptDebug);
90 if (forceAll) {
91 mPrevPids.clear();
92 } else {
93 mPrevPids = mCurrPids;
94 }
95 // Get current pid list
96 mCurrPids.clear();
97 DIR *dir;
98 struct dirent *ent;
99 if ((dir = opendir("/proc/")) == NULL) {
100 LOG(ERROR) << "failed on opendir '/proc/'";
101 return;
102 }
103 while ((ent = readdir(dir)) != NULL) {
104 if (ent->d_type == DT_DIR) {
105 uint32_t pid;
106 if (android::base::ParseUint(ent->d_name, &pid)) {
107 mCurrPids.push_back(pid);
108 }
109 }
110 }
111 std::vector<uint32_t> newpids = getNewPids();
112 // update mUidNameMapping only for new pids
113 for (int i = 0, len = newpids.size(); i < len; i++) {
114 uint32_t pid = newpids[i];
115 std::string buffer;
116 if (!android::base::ReadFileToString("/proc/" + std::to_string(pid) + "/status", &buffer)) {
117 if (sOptDebug)
118 LOG(INFO) << "/proc/" << std::to_string(pid) << "/status"
119 << ": ReadFileToString failed (process died?)";
120 continue;
121 }
122 // --- Find Name ---
123 size_t s = buffer.find("Name:");
124 if (s == std::string::npos) {
125 continue;
126 }
127 s += std::strlen("Name:");
128 // find the pos of next word
129 while (buffer[s] && isspace(buffer[s])) s++;
130 if (buffer[s] == 0) {
131 continue;
132 }
133 size_t e = s;
134 // find the end pos of the word
135 while (buffer[e] && !std::isspace(buffer[e])) e++;
136 std::string pname(buffer, s, e - s);
137
138 // --- Find Uid ---
139 s = buffer.find("\nUid:", e);
140 if (s == std::string::npos) {
141 continue;
142 }
143 s += std::strlen("\nUid:");
144 // find the pos of next word
145 while (buffer[s] && isspace(buffer[s])) s++;
146 if (buffer[s] == 0) {
147 continue;
148 }
149 e = s;
150 // find the end pos of the word
151 while (buffer[e] && !std::isspace(buffer[e])) e++;
152 std::string strUid(buffer, s, e - s);
153
154 uint32_t uid = (uint32_t)std::stoi(strUid);
155 mUidNameMapping[uid] = pname;
156 }
157 }
158
getNameForUid(uint32_t uid,std::string * name)159 bool ProcPidIoStats::getNameForUid(uint32_t uid, std::string *name) {
160 if (mUidNameMapping.find(uid) != mUidNameMapping.end()) {
161 *name = mUidNameMapping[uid];
162 return true;
163 }
164 return false;
165 }
166
updateTopRead(UserIo usage)167 void IoStats::updateTopRead(UserIo usage) {
168 UserIo tmp;
169 for (int i = 0, len = IO_TOP_MAX; i < len; i++) {
170 if (usage.sumRead() > mReadTop[i].sumRead()) {
171 // if new read > old read, then swap values
172 tmp = mReadTop[i];
173 mReadTop[i] = usage;
174 usage = tmp;
175 }
176 }
177 }
178
updateTopWrite(UserIo usage)179 void IoStats::updateTopWrite(UserIo usage) {
180 UserIo tmp;
181 for (int i = 0, len = IO_TOP_MAX; i < len; i++) {
182 if (usage.sumWrite() > mWriteTop[i].sumWrite()) {
183 // if new write > old write, then swap values
184 tmp = mWriteTop[i];
185 mWriteTop[i] = usage;
186 usage = tmp;
187 }
188 }
189 }
190
updateUnknownUidList()191 void IoStats::updateUnknownUidList() {
192 if (!mUnknownUidList.size()) {
193 return;
194 }
195 ScopeTimer _debugTimer("update overall UID/Name");
196 _debugTimer.setEnabled(sOptDebug);
197 mProcIoStats.update(false);
198 for (uint32_t i = 0, len = mUnknownUidList.size(); i < len; i++) {
199 uint32_t uid = mUnknownUidList[i];
200 if (isAppUid(uid)) {
201 // Get IO throughput for App processes
202 std::string pname;
203 if (!mProcIoStats.getNameForUid(uid, &pname)) {
204 if (sOptDebug)
205 LOG(WARNING) << "unable to find App uid:" << uid;
206 continue;
207 }
208 mUidNameMap[uid] = pname;
209 } else {
210 // Get IO throughput for system/native processes
211 passwd *usrpwd = getpwuid(uid);
212 if (!usrpwd) {
213 if (sOptDebug)
214 LOG(WARNING) << "unable to find uid:" << uid << " by getpwuid";
215 continue;
216 }
217 mUidNameMap[uid] = std::string(usrpwd->pw_name);
218 if (std::find(mUnknownUidList.begin(), mUnknownUidList.end(), uid) !=
219 mUnknownUidList.end()) {
220 }
221 }
222 mUnknownUidList.erase(std::remove(mUnknownUidList.begin(), mUnknownUidList.end(), uid),
223 mUnknownUidList.end());
224 }
225
226 if (sOptDebug && mUnknownUidList.size() > 0) {
227 std::stringstream msg;
228 msg << "Some UID/Name can't be retrieved: ";
229 for (const auto &i : mUnknownUidList) {
230 msg << i << ", ";
231 }
232 LOG(WARNING) << msg.str();
233 }
234 mUnknownUidList.clear();
235 }
236
calcIncrement(const std::unordered_map<uint32_t,UserIo> & data)237 std::unordered_map<uint32_t, UserIo> IoStats::calcIncrement(
238 const std::unordered_map<uint32_t, UserIo> &data) {
239 std::unordered_map<uint32_t, UserIo> diffs;
240 for (const auto &it : data) {
241 const UserIo &d = it.second;
242 // If data not existed, copy one, else calculate the increment.
243 if (mPrevious.find(d.uid) == mPrevious.end()) {
244 diffs[d.uid] = d;
245 } else {
246 diffs[d.uid] = d - mPrevious[d.uid];
247 }
248 // If uid not existed in UidNameMap, then add into unknown list
249 if ((diffs[d.uid].sumRead() || diffs[d.uid].sumWrite()) &&
250 mUidNameMap.find(d.uid) == mUidNameMap.end()) {
251 mUnknownUidList.push_back(d.uid);
252 }
253 }
254 // update Uid/Name mapping for dump()
255 updateUnknownUidList();
256 return diffs;
257 }
258
calcAll(std::unordered_map<uint32_t,UserIo> && data)259 void IoStats::calcAll(std::unordered_map<uint32_t, UserIo> &&data) {
260 // if mList == mNow, it's in init state.
261 if (mLast == mNow) {
262 mPrevious = std::move(data);
263 mLast = mNow;
264 mNow = std::chrono::system_clock::now();
265 mProcIoStats.update(true);
266 for (const auto &d : data) {
267 mUnknownUidList.push_back(d.first);
268 }
269 updateUnknownUidList();
270 return;
271 }
272 mLast = mNow;
273 mNow = std::chrono::system_clock::now();
274
275 // calculate incremental IO throughput
276 std::unordered_map<uint32_t, UserIo> amounts = calcIncrement(data);
277 // assign current data to Previous for next calculating
278 mPrevious = std::move(data);
279 // Reset Total and Tops
280 mTotal.reset();
281 for (int i = 0, len = IO_TOP_MAX; i < len; i++) {
282 mReadTop[i].reset();
283 mWriteTop[i].reset();
284 }
285 for (const auto &it : amounts) {
286 const UserIo &d = it.second;
287 // Add into total
288 mTotal = mTotal + d;
289 // Check if it's top
290 updateTopRead(d);
291 updateTopWrite(d);
292 }
293 }
294
295 /* Dump IO usage (Sample Log)
296 *
297 * [IO_TOTAL: 10.160s] RD:371,703,808 WR:15,929,344 fsync:567
298 * [TOP Usage ] fg bytes, bg bytes,fgsyn,bgsyn : UID NAME
299 * [R1: 33.99%] 0, 73240576, 0, 240 : 10016 .android.gms.ui
300 * [R2: 28.34%] 16039936, 45027328, 1, 21 : 10082 -
301 * [R3: 16.54%] 11243520, 24395776, 0, 25 : 10055 -
302 * [R4: 10.93%] 22241280, 1318912, 0, 1 : 10123 oid.apps.photos
303 * [R5: 10.19%] 21528576, 421888, 23, 20 : 10061 android.vending
304 * [W1: 58.19%] 0, 7655424, 0, 240 : 10016 .android.gms.ui
305 * [W2: 17.03%] 1265664, 974848, 38, 45 : 10069 -
306 * [W3: 11.30%] 1486848, 0, 58, 0 : 1000 system
307 * [W4: 8.13%] 667648, 401408, 23, 20 : 10061 android.vending
308 * [W5: 5.35%] 0, 704512, 0, 25 : 10055 -
309 *
310 */
dump(std::stringstream * output)311 bool IoStats::dump(std::stringstream *output) {
312 std::stringstream &out = (*output);
313
314 auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(mNow - mLast);
315 char readTotal[32];
316 char writeTotal[32];
317 if (!formatNum(mTotal.sumRead(), readTotal, 32)) {
318 LOG(ERROR) << "formatNum buffer size is too small for read: " << mTotal.sumRead();
319 }
320 if (!formatNum(mTotal.sumWrite(), writeTotal, 32)) {
321 LOG(ERROR) << "formatNum buffer size is too small for write: " << mTotal.sumWrite();
322 }
323
324 out << android::base::StringPrintf(FMT_STR_TOTAL_USAGE, ms.count() / 1000, ms.count() % 1000,
325 readTotal, writeTotal, mTotal.fgFsync + mTotal.bgFsync);
326
327 if (mTotal.sumRead() >= mMinSizeOfTotalRead || mTotal.sumWrite() >= mMinSizeOfTotalWrite) {
328 out << STR_TOP_HEADER;
329 }
330 // Dump READ TOP
331 if (mTotal.sumRead() < mMinSizeOfTotalRead) {
332 out << android::base::StringPrintf(FMT_STR_SKIP_TOP_READ, mMinSizeOfTotalRead / 1000000)
333 << std::endl;
334 } else {
335 for (int i = 0, len = IO_TOP_MAX; i < len; i++) {
336 UserIo &target = mReadTop[i];
337 if (target.sumRead() == 0) {
338 break;
339 }
340 float percent = 100.0f * target.sumRead() / mTotal.sumRead();
341 const char *package = mUidNameMap.find(target.uid) == mUidNameMap.end()
342 ? "-"
343 : mUidNameMap[target.uid].c_str();
344 out << android::base::StringPrintf(FMT_STR_TOP_READ_USAGE, i + 1, percent,
345 target.fgRead, target.bgRead, target.fgFsync,
346 target.bgFsync, target.uid, package);
347 }
348 }
349
350 // Dump WRITE TOP
351 if (mTotal.sumWrite() < mMinSizeOfTotalWrite) {
352 out << android::base::StringPrintf(FMT_STR_SKIP_TOP_WRITE, mMinSizeOfTotalWrite / 1000000)
353 << std::endl;
354 } else {
355 for (int i = 0, len = IO_TOP_MAX; i < len; i++) {
356 UserIo &target = mWriteTop[i];
357 if (target.sumWrite() == 0) {
358 break;
359 }
360 float percent = 100.0f * target.sumWrite() / mTotal.sumWrite();
361 const char *package = mUidNameMap.find(target.uid) == mUidNameMap.end()
362 ? "-"
363 : mUidNameMap[target.uid].c_str();
364 out << android::base::StringPrintf(FMT_STR_TOP_WRITE_USAGE, i + 1, percent,
365 target.fgWrite, target.bgWrite, target.fgFsync,
366 target.bgFsync, target.uid, package);
367 }
368 }
369 return true;
370 }
371
loadDataFromLine(std::string && line,UserIo & data)372 static bool loadDataFromLine(std::string &&line, UserIo &data) {
373 std::vector<std::string> fields = android::base::Split(line, " ");
374 if (fields.size() < 11 || !android::base::ParseUint(fields[0], &data.uid) ||
375 !android::base::ParseUint(fields[3], &data.fgRead) ||
376 !android::base::ParseUint(fields[4], &data.fgWrite) ||
377 !android::base::ParseUint(fields[7], &data.bgRead) ||
378 !android::base::ParseUint(fields[8], &data.bgWrite) ||
379 !android::base::ParseUint(fields[9], &data.fgFsync) ||
380 !android::base::ParseUint(fields[10], &data.bgFsync)) {
381 LOG(WARNING) << "Invalid uid I/O stats: \"" << line << "\"";
382 return false;
383 }
384 return true;
385 }
386
dump(std::string * outAppend)387 void ScopeTimer::dump(std::string *outAppend) {
388 auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
389 std::chrono::system_clock::now() - mStart);
390 outAppend->append("duration (");
391 outAppend->append(mName);
392 outAppend->append("): ");
393 outAppend->append(std::to_string(ms.count()));
394 outAppend->append("ms");
395 }
396
397 /*
398 * setOptions - IoUsage supports following options
399 * iostats.min : skip dump when R/W amount is lower than the value
400 * iostats.read.min : skip dump when READ amount is lower than the value
401 * iostats.write.min : skip dump when WRITE amount is lower than the value
402 * iostats.debug : 1 - to enable debug log; 0 - disabled
403 */
setOptions(const std::string & key,const std::string & value)404 void IoUsage::setOptions(const std::string &key, const std::string &value) {
405 std::stringstream out;
406 out << "set IO options: " << key << " , " << value;
407 if (key == "iostats.min" || key == "iostats.read.min" || key == "iostats.write.min" ||
408 key == "iostats.debug") {
409 uint64_t val = 0;
410 if (!android::base::ParseUint(value, &val)) {
411 out << "!!!! unable to parse value to uint64";
412 LOG(ERROR) << out.str();
413 return;
414 }
415 if (key == "iostats.min") {
416 mStats.setDumpThresholdSizeForRead(val);
417 mStats.setDumpThresholdSizeForWrite(val);
418 } else if (key == "iostats.disabled") {
419 mDisabled = (val != 0);
420 } else if (key == "iostats.read.min") {
421 mStats.setDumpThresholdSizeForRead(val);
422 } else if (key == "iostats.write.min") {
423 mStats.setDumpThresholdSizeForWrite(val);
424 } else if (key == "iostats.debug") {
425 sOptDebug = (val != 0);
426 }
427 LOG(INFO) << out.str() << ": Success";
428 }
429 }
430
refresh(void)431 void IoUsage::refresh(void) {
432 if (mDisabled)
433 return;
434 ScopeTimer _debugTimer("refresh");
435 _debugTimer.setEnabled(sOptDebug);
436 std::string buffer;
437 if (!android::base::ReadFileToString(UID_IO_STATS_PATH, &buffer)) {
438 LOG(ERROR) << UID_IO_STATS_PATH << ": ReadFileToString failed";
439 }
440 if (sOptDebug)
441 LOG(INFO) << "read " << UID_IO_STATS_PATH << " OK.";
442 std::vector<std::string> lines = android::base::Split(std::move(buffer), "\n");
443 std::unordered_map<uint32_t, UserIo> datas;
444 for (uint32_t i = 0; i < lines.size(); i++) {
445 if (lines[i].empty()) {
446 continue;
447 }
448 UserIo data;
449 if (!loadDataFromLine(std::move(lines[i]), data))
450 continue;
451 datas[data.uid] = data;
452 }
453 mStats.calcAll(std::move(datas));
454 std::stringstream out;
455 mStats.dump(&out);
456 const std::string &str = out.str();
457 if (sOptDebug) {
458 LOG(INFO) << str;
459 LOG(INFO) << "output append length:" << str.length();
460 }
461 append((std::string &)str);
462 }
463