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 #include "ProcDiskStatsCollector.h"
18 
19 #include <android-base/file.h>
20 #include <android-base/strings.h>
21 #include <gmock/gmock.h>
22 
23 #include <inttypes.h>
24 
25 namespace android {
26 namespace automotive {
27 namespace watchdog {
28 
29 using ::android::base::StartsWith;
30 using ::android::base::StringAppendF;
31 using ::android::base::WriteStringToFile;
32 
33 namespace {
34 
getDiskStatsLine(const DiskStats & stats)35 std::string getDiskStatsLine(const DiskStats& stats) {
36     /**
37      * /proc/diskstats lines doesn't contain tab spaces instead they have whitespace.
38      * Thus write the output in the same format as /proc/diskstats so the tests can reproduce the
39      * on device file format.
40      */
41     std::string buffer;
42     StringAppendF(&buffer, "   %d       %d %s", stats.major, stats.minor, stats.deviceName.c_str());
43     StringAppendF(&buffer, " %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, stats.numReadsCompleted,
44                   stats.numReadsMerged, stats.numKibRead * 2, stats.readTimeInMillis);
45     StringAppendF(&buffer, " %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64,
46                   stats.numWritesCompleted, stats.numWritesMerged, stats.numKibWritten * 2,
47                   stats.writeTimeInMillis);
48     StringAppendF(&buffer, " 0 %" PRIu64 " %" PRIu64 " 0 0 0 0 %" PRIu64 " %" PRIu64 "\n",
49                   stats.totalIoTimeInMillis, stats.weightedTotalIoTimeInMillis,
50                   stats.numFlushCompleted, stats.flushTimeInMillis);
51     return buffer;
52 }
53 
getDiskStatsFile(const ProcDiskStatsCollectorInterface::PerPartitionDiskStats & allStats)54 std::string getDiskStatsFile(
55         const ProcDiskStatsCollectorInterface::PerPartitionDiskStats& allStats) {
56     std::string buffer;
57     for (const auto& stats : allStats) {
58         StringAppendF(&buffer, "%s", getDiskStatsLine(stats).c_str());
59     }
60     return buffer;
61 }
62 
aggregateSystemWideDiskStats(const ProcDiskStatsCollectorInterface::PerPartitionDiskStats & perPartitionDiskStats)63 DiskStats aggregateSystemWideDiskStats(
64         const ProcDiskStatsCollectorInterface::PerPartitionDiskStats& perPartitionDiskStats) {
65     DiskStats systemWideStats;
66     for (const auto& stats : perPartitionDiskStats) {
67         if (recordStatsForDevice(stats.deviceName)) {
68             systemWideStats += stats;
69         }
70     }
71     return systemWideStats;
72 }
73 
isEquals(const DiskStats & lhs,const DiskStats & rhs)74 bool isEquals(const DiskStats& lhs, const DiskStats& rhs) {
75     auto tieStats = [](const DiskStats& stats) {
76         return std::tie(stats.major, stats.minor, stats.deviceName, stats.numReadsCompleted,
77                         stats.numReadsMerged, stats.numKibRead, stats.readTimeInMillis,
78                         stats.numWritesCompleted, stats.numWritesMerged, stats.numKibWritten,
79                         stats.writeTimeInMillis, stats.totalIoTimeInMillis,
80                         stats.weightedTotalIoTimeInMillis, stats.numFlushCompleted,
81                         stats.flushTimeInMillis);
82     };
83     return tieStats(lhs) == tieStats(rhs);
84 }
85 
86 }  // namespace
87 
TEST(ProcDiskStatsCollectorTest,TestValidStatsFile)88 TEST(ProcDiskStatsCollectorTest, TestValidStatsFile) {
89     ProcDiskStatsCollectorInterface::PerPartitionDiskStats latestDiskStats =
90             {{252, 32, "vdc", 120000, 760, 2000, 17190, 15000, 305000, 560000, 190000, 186140,
91               213482, 64709, 4505},
92              {251, 0, "zram0", 21959, 0, 175672, 868, 113635, 0, 909080, 9320, 25940, 10188, 0, 0},
93              {254, 0, "dm-0", 340000, 0, 4000, 104264, 0, 0, 0, 0, 85768, 104264, 0, 0}};
94     TemporaryFile tf;
95     ASSERT_NE(tf.fd, -1);
96     ASSERT_TRUE(WriteStringToFile(getDiskStatsFile(latestDiskStats), tf.path));
97 
98     DiskStats expectedDiskStats = aggregateSystemWideDiskStats(latestDiskStats);
99 
100     ProcDiskStatsCollector collector(tf.path);
101     collector.init();
102 
103     ASSERT_TRUE(collector.enabled()) << "Temporary file is inaccessible";
104     ASSERT_RESULT_OK(collector.collect());
105 
106     auto actualDiskStats = collector.deltaSystemWideDiskStats();
107 
108     ASSERT_TRUE(isEquals(expectedDiskStats, actualDiskStats))
109             << "Expected 1st collection: '" << getDiskStatsLine(expectedDiskStats) << "'\nActual: '"
110             << getDiskStatsLine(actualDiskStats) << "'";
111 
112     uint64_t maxUint64 = std::numeric_limits<uint64_t>::max();
113     latestDiskStats = {{252, 32, "vdc", maxUint64, 130000, 100, maxUint64, 30000, 1305000, 1560000,
114                         800, 386140, 313482, 164709, 14505},
115                        {251, 0, "zram0", 21959, 0, 175672, 868, 113635, 0, 909080, 9320, 25940,
116                         10188, 0, 0},
117                        {254, 0, "dm-0", 3400, 0, 5000, 1104264, 0, 0, 0, 0, 185768, 1104264, 0, 0}};
118     ASSERT_TRUE(WriteStringToFile(getDiskStatsFile(latestDiskStats), tf.path));
119 
120     expectedDiskStats =
121             {0,     0,       "",      maxUint64,          129240, maxUint64 - 900, maxUint64,
122              15000, 1000000, 1000000, maxUint64 - 189200, 300000, 1100000,         100000,
123              10000};
124 
125     ASSERT_RESULT_OK(collector.collect());
126 
127     actualDiskStats = collector.deltaSystemWideDiskStats();
128 
129     ASSERT_TRUE(isEquals(expectedDiskStats, actualDiskStats))
130             << "Expected 2nd collection: '" << getDiskStatsLine(expectedDiskStats) << "'\nActual: '"
131             << getDiskStatsLine(actualDiskStats) << "'";
132 }
133 
TEST(ProcDiskStatsCollectorTest,TestErrorOnInvalidStatsFile)134 TEST(ProcDiskStatsCollectorTest, TestErrorOnInvalidStatsFile) {
135     constexpr char contents[] = "252 0 disk 1200 300 0 CORRUPTED DATA\n";
136     TemporaryFile tf;
137     ASSERT_NE(tf.fd, -1);
138     ASSERT_TRUE(WriteStringToFile(contents, tf.path));
139 
140     ProcDiskStatsCollector collector(tf.path);
141     collector.init();
142 
143     ASSERT_TRUE(collector.enabled()) << "Temporary file is inaccessible";
144     EXPECT_FALSE(collector.collect().ok()) << "No error returned for invalid file";
145 }
146 
147 }  // namespace watchdog
148 }  // namespace automotive
149 }  // namespace android
150