1 /*
2  * Copyright (C) 2016 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 "boot_event_record_store.h"
18 
19 #include <dirent.h>
20 #include <fcntl.h>
21 #include <sys/stat.h>
22 #include <sys/time.h>
23 #include <unistd.h>
24 
25 #include <chrono>
26 #include <cstdint>
27 #include <cstdlib>
28 
29 #include <android-base/chrono_utils.h>
30 #include <android-base/file.h>
31 #include <android-base/logging.h>
32 #include <android-base/unique_fd.h>
33 #include <gmock/gmock.h>
34 #include <gtest/gtest.h>
35 
36 using testing::UnorderedElementsAreArray;
37 
38 namespace {
39 
40 // Creates a fake boot event record file at |record_path| containing the boot
41 // record |value|. This method is necessary as truncating a
42 // BootEventRecordStore-created file would modify the mtime, which would alter
43 // the value of the record.
CreateEmptyBootEventRecord(const std::string & record_path,int32_t value)44 bool CreateEmptyBootEventRecord(const std::string& record_path, int32_t value) {
45   android::base::unique_fd record_fd(creat(record_path.c_str(), S_IRUSR | S_IWUSR));
46   if (record_fd == -1) {
47     return false;
48   }
49 
50   // Set the |mtime| of the file to store the value of the boot event while
51   // preserving the |atime|.
52   struct timeval atime = {/* tv_sec */ 0, /* tv_usec */ 0};
53   struct timeval mtime = {/* tv_sec */ value, /* tv_usec */ 0};
54   const struct timeval times[] = {atime, mtime};
55   if (utimes(record_path.c_str(), times) != 0) {
56     return false;
57   }
58 
59   return true;
60 }
61 
62 // Returns true if the time difference between |a| and |b| is no larger
63 // than 10 seconds.  This allow for a relatively large fuzz when comparing
64 // two timestamps taken back-to-back.
FuzzUptimeEquals(int32_t a,int32_t b)65 bool FuzzUptimeEquals(int32_t a, int32_t b) {
66   const int32_t FUZZ_SECONDS = 10;
67   return (abs(a - b) <= FUZZ_SECONDS);
68 }
69 
70 // Recursively deletes the directory at |path|.
DeleteDirectory(const std::string & path)71 void DeleteDirectory(const std::string& path) {
72   typedef std::unique_ptr<DIR, decltype(&closedir)> ScopedDIR;
73   ScopedDIR dir(opendir(path.c_str()), closedir);
74   ASSERT_NE(nullptr, dir.get());
75 
76   struct dirent* entry;
77   while ((entry = readdir(dir.get())) != NULL) {
78     const std::string entry_name(entry->d_name);
79     if (entry_name == "." || entry_name == "..") {
80       continue;
81     }
82 
83     const std::string entry_path = path + "/" + entry_name;
84     if (entry->d_type == DT_DIR) {
85       DeleteDirectory(entry_path);
86     } else {
87       unlink(entry_path.c_str());
88     }
89   }
90 
91   rmdir(path.c_str());
92 }
93 
94 // Returns the time in seconds since boot.
GetUptimeSeconds()95 time_t GetUptimeSeconds() {
96   return std::chrono::duration_cast<std::chrono::seconds>(
97              android::base::boot_clock::now().time_since_epoch())
98       .count();
99 }
100 
101 class BootEventRecordStoreTest : public ::testing::Test {
102  public:
BootEventRecordStoreTest()103   BootEventRecordStoreTest() { store_path_ = std::string(store_dir_.path) + "/"; }
104 
GetStorePathForTesting() const105   const std::string& GetStorePathForTesting() const { return store_path_; }
106 
107  private:
TearDown()108   void TearDown() {
109     // This removes the record store temporary directory even though
110     // TemporaryDir should already take care of it, but this method cleans up
111     // the test files added to the directory which prevent TemporaryDir from
112     // being able to remove the directory.
113     DeleteDirectory(store_path_);
114   }
115 
116   // A scoped temporary directory. Using this abstraction provides creation of
117   // the directory and the path to the directory, which is stored in
118   // |store_path_|.
119   TemporaryDir store_dir_;
120 
121   // The path to the temporary directory used by the BootEventRecordStore to
122   // persist records.  The directory is created and destroyed for each test.
123   std::string store_path_;
124 
125   DISALLOW_COPY_AND_ASSIGN(BootEventRecordStoreTest);
126 };
127 
128 }  // namespace
129 
TEST_F(BootEventRecordStoreTest,AddSingleBootEvent)130 TEST_F(BootEventRecordStoreTest, AddSingleBootEvent) {
131   BootEventRecordStore store;
132   store.SetStorePath(GetStorePathForTesting());
133 
134   time_t uptime = GetUptimeSeconds();
135   ASSERT_NE(-1, uptime);
136 
137   store.AddBootEvent("cenozoic");
138 
139   auto events = store.GetAllBootEvents();
140   ASSERT_EQ(1U, events.size());
141   EXPECT_EQ("cenozoic", events[0].first);
142   EXPECT_TRUE(FuzzUptimeEquals(uptime, events[0].second));
143 }
144 
TEST_F(BootEventRecordStoreTest,AddMultipleBootEvents)145 TEST_F(BootEventRecordStoreTest, AddMultipleBootEvents) {
146   BootEventRecordStore store;
147   store.SetStorePath(GetStorePathForTesting());
148 
149   time_t uptime = GetUptimeSeconds();
150   ASSERT_NE(-1, uptime);
151 
152   store.AddBootEvent("cretaceous");
153   store.AddBootEvent("jurassic");
154   store.AddBootEvent("triassic");
155 
156   const std::string EXPECTED_NAMES[] = {
157       "cretaceous", "jurassic", "triassic",
158   };
159 
160   auto events = store.GetAllBootEvents();
161   ASSERT_EQ(3U, events.size());
162 
163   std::vector<std::string> names;
164   std::vector<int32_t> timestamps;
165   for (auto i = events.begin(); i != events.end(); ++i) {
166     names.push_back(i->first);
167     timestamps.push_back(i->second);
168   }
169 
170   EXPECT_THAT(names, UnorderedElementsAreArray(EXPECTED_NAMES));
171 
172   for (auto i = timestamps.cbegin(); i != timestamps.cend(); ++i) {
173     EXPECT_TRUE(FuzzUptimeEquals(uptime, *i));
174   }
175 }
176 
TEST_F(BootEventRecordStoreTest,AddBootEventWithValue)177 TEST_F(BootEventRecordStoreTest, AddBootEventWithValue) {
178   BootEventRecordStore store;
179   store.SetStorePath(GetStorePathForTesting());
180 
181   store.AddBootEventWithValue("permian", 42);
182 
183   auto events = store.GetAllBootEvents();
184   ASSERT_EQ(1U, events.size());
185   EXPECT_EQ("permian", events[0].first);
186   EXPECT_EQ(42, events[0].second);
187 }
188 
TEST_F(BootEventRecordStoreTest,GetBootEvent)189 TEST_F(BootEventRecordStoreTest, GetBootEvent) {
190   BootEventRecordStore store;
191   store.SetStorePath(GetStorePathForTesting());
192 
193   // Event does not exist.
194   BootEventRecordStore::BootEventRecord record;
195   bool result = store.GetBootEvent("nonexistent", &record);
196   EXPECT_EQ(false, result);
197 
198   // Empty path.
199   EXPECT_DEATH(store.GetBootEvent(std::string(), &record), std::string());
200 
201   // Success case.
202   store.AddBootEventWithValue("carboniferous", 314);
203   result = store.GetBootEvent("carboniferous", &record);
204   EXPECT_EQ(true, result);
205   EXPECT_EQ("carboniferous", record.first);
206   EXPECT_EQ(314, record.second);
207 
208   // Null |record|.
209   EXPECT_DEATH(store.GetBootEvent("carboniferous", nullptr), std::string());
210 }
211 
212 // Tests that the BootEventRecordStore is capable of handling an older record
213 // protocol which does not contain file contents.
TEST_F(BootEventRecordStoreTest,GetBootEventNoFileContent)214 TEST_F(BootEventRecordStoreTest, GetBootEventNoFileContent) {
215   BootEventRecordStore store;
216   store.SetStorePath(GetStorePathForTesting());
217 
218   EXPECT_TRUE(CreateEmptyBootEventRecord(store.GetBootEventPath("devonian"), 2718));
219 
220   BootEventRecordStore::BootEventRecord record;
221   bool result = store.GetBootEvent("devonian", &record);
222   EXPECT_EQ(true, result);
223   EXPECT_EQ("devonian", record.first);
224   EXPECT_EQ(2718, record.second);
225 }
226