blob: 1ebcde69300c93c8220f9262ffa3505b6ad30fb8 [file] [log] [blame]
Alexei Strots01395492023-03-20 13:59:56 -07001#include "aos/events/logging/log_backend.h"
2
Austin Schuh3ebaf782023-04-07 16:03:28 -07003#include <algorithm>
Alexei Strots01395492023-03-20 13:59:56 -07004#include <filesystem>
Austin Schuh3ebaf782023-04-07 16:03:28 -07005#include <fstream>
6#include <random>
Alexei Strots01395492023-03-20 13:59:56 -07007
Austin Schuh3ebaf782023-04-07 16:03:28 -07008#include "absl/strings/str_cat.h"
9#include "absl/strings/str_join.h"
10#include "aos/containers/resizeable_buffer.h"
Alexei Strots01395492023-03-20 13:59:56 -070011#include "aos/testing/tmpdir.h"
Austin Schuh3ebaf782023-04-07 16:03:28 -070012#include "glog/logging.h"
13#include "gmock/gmock.h"
Alexei Strots01395492023-03-20 13:59:56 -070014#include "gtest/gtest.h"
15
16namespace aos::logger::testing {
17TEST(LogBackendTest, CreateSimpleFile) {
18 const std::string logevent = aos::testing::TestTmpDir() + "/logevent/";
19 FileBackend backend(logevent);
20 auto file = backend.RequestFile("test.log");
21 ASSERT_EQ(file->OpenForWrite(), WriteCode::kOk);
22 auto result = write(file->fd(), "test", 4);
23 EXPECT_GT(result, 0);
24 EXPECT_EQ(file->Close(), WriteCode::kOk);
25 EXPECT_TRUE(std::filesystem::exists(logevent + "test.log"));
26}
27
28TEST(LogBackendTest, CreateRenamableFile) {
29 const std::string logevent = aos::testing::TestTmpDir() + "/logevent/";
30 RenamableFileBackend backend(logevent);
31 auto file = backend.RequestFile("test.log");
32 ASSERT_EQ(file->OpenForWrite(), WriteCode::kOk);
33 auto result = write(file->fd(), "testtest", 8);
34 EXPECT_GT(result, 0);
35 EXPECT_EQ(file->Close(), WriteCode::kOk);
36 EXPECT_TRUE(std::filesystem::exists(logevent + "test.log"));
37}
38
39TEST(LogBackendTest, UseTempRenamableFile) {
40 const std::string logevent = aos::testing::TestTmpDir() + "/logevent/";
41 RenamableFileBackend backend(logevent);
42 backend.EnableTempFiles();
43 auto file = backend.RequestFile("test.log");
44 ASSERT_EQ(file->OpenForWrite(), WriteCode::kOk);
45 auto result = write(file->fd(), "testtest", 8);
46 EXPECT_GT(result, 0);
47 EXPECT_TRUE(std::filesystem::exists(logevent + "test.log.tmp"));
48
49 EXPECT_EQ(file->Close(), WriteCode::kOk);
50 // Check that file is renamed.
51 EXPECT_TRUE(std::filesystem::exists(logevent + "test.log"));
52}
53
54TEST(LogBackendTest, RenameBaseAfterWrite) {
55 const std::string logevent = aos::testing::TestTmpDir() + "/logevent/";
56 RenamableFileBackend backend(logevent);
57 auto file = backend.RequestFile("test.log");
58 ASSERT_EQ(file->OpenForWrite(), WriteCode::kOk);
59 auto result = write(file->fd(), "testtest", 8);
60 EXPECT_GT(result, 0);
61 EXPECT_TRUE(std::filesystem::exists(logevent + "test.log"));
62
63 std::string renamed = aos::testing::TestTmpDir() + "/renamed/";
64 backend.RenameLogBase(renamed);
65
66 EXPECT_FALSE(std::filesystem::exists(logevent + "test.log"));
67 EXPECT_TRUE(std::filesystem::exists(renamed + "test.log"));
68
69 EXPECT_EQ(file->Close(), WriteCode::kOk);
70 // Check that file is renamed.
71 EXPECT_TRUE(std::filesystem::exists(renamed + "test.log"));
72}
73
74TEST(LogBackendTest, UseTestAndRenameBaseAfterWrite) {
75 const std::string logevent = aos::testing::TestTmpDir() + "/logevent/";
76 RenamableFileBackend backend(logevent);
77 backend.EnableTempFiles();
78 auto file = backend.RequestFile("test.log");
79 ASSERT_EQ(file->OpenForWrite(), WriteCode::kOk);
80 auto result = write(file->fd(), "testtest", 8);
81 EXPECT_GT(result, 0);
82 EXPECT_TRUE(std::filesystem::exists(logevent + "test.log.tmp"));
83
84 std::string renamed = aos::testing::TestTmpDir() + "/renamed/";
85 backend.RenameLogBase(renamed);
86
87 EXPECT_FALSE(std::filesystem::exists(logevent + "test.log.tmp"));
88 EXPECT_TRUE(std::filesystem::exists(renamed + "test.log.tmp"));
89
90 EXPECT_EQ(file->Close(), WriteCode::kOk);
91 // Check that file is renamed.
92 EXPECT_TRUE(std::filesystem::exists(renamed + "test.log"));
93}
94
Austin Schuh3ebaf782023-04-07 16:03:28 -070095// It represents calls to Write function (batching of calls and messages) where
96// int values are sizes of each message in the queue.
97using WriteRecipe = std::vector<std::vector<int>>;
98
99struct FileWriteTestBase : public ::testing::Test {
100 uint8_t NextRandom() { return distribution(engine); }
101
102 class AlignedReallocator {
103 public:
104 static void *Realloc(void *old, size_t old_size, size_t new_capacity) {
105 void *new_memory = std::aligned_alloc(512, new_capacity);
106 if (old) {
107 memcpy(new_memory, old, old_size);
108 free(old);
109 }
110 return new_memory;
111 }
112 };
113
114 AllocatorResizeableBuffer<AlignedReallocator> buffer;
115
116 void TestRecipe(const WriteRecipe &recipe) {
117 VLOG(1) << "Starting";
118 for (const std::vector<int> &r : recipe) {
119 VLOG(1) << " chunk " << absl::StrJoin(r, ", ");
120 }
121 size_t requested_size = 0;
122 for (const auto &call : recipe) {
123 for (const auto &message_size : call) {
124 requested_size += message_size;
125 }
126 }
127
128 // Grow the cached buffer if it needs to grow. Building a random buffer is
129 // the most expensive part of the test.
130 if (buffer.size() < requested_size) {
131 // Make sure it is 512 aligned... That makes sure we have the best chance
132 // of transitioning to and from being aligned.
133 buffer.resize((requested_size + FileHandler::kSector - 1) &
134 (~(FileHandler::kSector - 1)));
135 std::generate(std::begin(buffer), std::end(buffer),
136 [this]() { return NextRandom(); });
137 }
138
139 // Back align the data to the buffer so we make sure the contents of the
140 // file keep changing in case a file somehow doesn't get deleted, or
141 // collides with something else.
142 const uint8_t *adjusted_start =
143 buffer.data() + buffer.size() - requested_size;
144
145 // logevent has to end with '/' to be recognized as a folder.
146 const std::string logevent = aos::testing::TestTmpDir() + "/";
147 const auto file = std::filesystem::path(logevent) / "test.log";
148 std::filesystem::remove_all(file);
149 VLOG(1) << "Writing to " << file.c_str();
150
151 FileBackend backend(logevent);
152 auto handler = backend.RequestFile("test.log");
153 ASSERT_EQ(handler->OpenForWrite(), WriteCode::kOk);
154
155 // Build arguments for Write.
156 size_t position = 0;
157 for (const auto &call : recipe) {
158 std::vector<absl::Span<const uint8_t>> queue;
159 for (const auto &message_size : call) {
160 const uint8_t *current = adjusted_start + position;
161 queue.emplace_back(current, message_size);
162 position += message_size;
163 }
164 auto result = handler->Write(queue);
165 EXPECT_EQ(result.code, WriteCode::kOk);
166 EXPECT_EQ(result.messages_written, call.size());
167 }
168
169 ASSERT_EQ(handler->Close(), WriteCode::kOk);
170 EXPECT_TRUE(std::filesystem::exists(file));
171 EXPECT_EQ(std::filesystem::file_size(file), requested_size);
172
173 // Confirm that the contents then match the original buffer.
174 std::ifstream file_stream(file, std::ios::in | std::ios::binary);
175 std::vector<uint8_t> content((std::istreambuf_iterator<char>(file_stream)),
176 std::istreambuf_iterator<char>());
177 ASSERT_EQ(content.size(), requested_size);
178 bool matches = true;
179 for (size_t i = 0; i < content.size(); ++i) {
180 if (content[i] != adjusted_start[i]) {
181 matches = false;
182 break;
183 }
184 }
185 if (!matches) {
186 ASSERT_TRUE(false);
187 }
188 }
189
190 std::random_device random;
191 std::mt19937 engine{random()};
192 std::uniform_int_distribution<uint8_t> distribution{0, 0xFF};
193};
194
195// Tests that random sets of reads and writes always result in all the data
196// being written.
197TEST_F(FileWriteTestBase, RandomTest) {
198 std::mt19937 engine2{random()};
199 std::uniform_int_distribution<int> count_distribution{1, 5};
200
201 // Pick a bunch of lengths that will result in things that add up to multiples
202 // of 512 and end up transitioning across the aligned and unaligned boundary.
203 const std::vector<int> lengths = {
204 0x100b5, 0xff4b, 0x10000, 1024 - 7, 1024 - 6, 1024 - 5, 1024 - 4,
205 1024 - 3, 1024 - 2, 1024 - 1, 1024, 1024 + 1, 1024 + 2, 1024 + 3,
206 1024 + 4, 1024 + 5, 1024 + 6, 1024 + 7, 512 - 7, 512 - 6, 512 - 5,
207 512 - 4, 512 - 3, 512 - 2, 512 - 1, 512, 512 + 1, 512 + 2,
208 512 + 3, 512 + 4, 512 + 5, 512 + 6, 512 + 7};
209 std::uniform_int_distribution<int> lengths_distribution{
210 0, static_cast<int>(lengths.size() - 1)};
211
Austin Schuh9e8df9e2023-05-03 08:28:29 -0700212 for (int i = 0; i < 1000; ++i) {
Austin Schuh3ebaf782023-04-07 16:03:28 -0700213 WriteRecipe recipe;
214 int number_of_writes = count_distribution(engine2);
215 for (int j = 0; j < number_of_writes; ++j) {
216 int number_of_chunks = count_distribution(engine2);
217 std::vector<int> r;
218 for (int k = 0; k < number_of_chunks; ++k) {
219 r.emplace_back(lengths[lengths_distribution(engine2)]);
220 }
221 recipe.emplace_back(std::move(r));
222 }
223
224 TestRecipe(recipe);
225 }
226}
227
228// Test an aligned to unaligned transition to make sure everything works.
229TEST_F(FileWriteTestBase, AlignedToUnaligned) {
230 AllocatorResizeableBuffer<AlignedReallocator> aligned_buffer;
231 AllocatorResizeableBuffer<AlignedReallocator> unaligned_buffer;
232
233 aligned_buffer.resize(FileHandler::kSector * 4);
234 std::generate(std::begin(aligned_buffer), std::end(aligned_buffer),
235 [this]() { return NextRandom(); });
236
237 unaligned_buffer.resize(FileHandler::kSector * 4);
238 std::generate(std::begin(unaligned_buffer), std::end(unaligned_buffer),
239 [this]() { return NextRandom(); });
240
241 const size_t kOffset = 53;
242 absl::Span<const uint8_t> unaligned_span(unaligned_buffer.data() + kOffset,
243 aligned_buffer.size() - kOffset);
244
245 std::vector<absl::Span<const uint8_t>> queue;
246
247 queue.emplace_back(aligned_buffer.data(), aligned_buffer.size());
248 queue.emplace_back(unaligned_span);
249 LOG(INFO) << "Queue 0 " << queue[0].size();
250 LOG(INFO) << "Queue 1 " << queue[1].size();
251
252 const std::string logevent = aos::testing::TestTmpDir() + "/";
253 const auto file = std::filesystem::path(logevent) / "test.log";
254 std::filesystem::remove_all(file);
255 VLOG(1) << "Writing to " << file.c_str();
256
257 FileBackend backend(logevent);
258 auto handler = backend.RequestFile("test.log");
259 ASSERT_EQ(handler->OpenForWrite(), WriteCode::kOk);
260
261 auto result = handler->Write(queue);
262 EXPECT_EQ(result.code, WriteCode::kOk);
263 EXPECT_EQ(result.messages_written, queue.size());
264
265 ASSERT_EQ(handler->Close(), WriteCode::kOk);
266 EXPECT_TRUE(std::filesystem::exists(file));
267 const size_t requested_size = queue[0].size() + queue[1].size();
268 EXPECT_EQ(std::filesystem::file_size(file), requested_size);
269
270 // Confirm that the contents then match the original buffer.
271 std::ifstream file_stream(file, std::ios::in | std::ios::binary);
272 std::vector<uint8_t> content((std::istreambuf_iterator<char>(file_stream)),
273 std::istreambuf_iterator<char>());
274 ASSERT_EQ(content.size(), requested_size);
275 bool matches = true;
276 for (size_t i = 0; i < queue[0].size(); ++i) {
277 if (content[i] != aligned_buffer.data()[i]) {
278 matches = false;
279 break;
280 }
281 }
282 for (size_t i = 0; i < queue[1].size(); ++i) {
283 if (content[i + queue[0].size()] != unaligned_span.data()[i]) {
284 matches = false;
285 break;
286 }
287 }
288 if (!matches) {
289 ASSERT_TRUE(false);
290 }
291}
292
293struct FileWriteTestFixture : public ::testing::WithParamInterface<WriteRecipe>,
294 public FileWriteTestBase {};
295
296TEST_P(FileWriteTestFixture, CheckSizeOfWrittenFile) {
297 auto recipe = GetParam();
298 TestRecipe(recipe);
299}
300
301// Try out some well known failure cases transitioning across the alignment
302// boundary.
303INSTANTIATE_TEST_SUITE_P(
304 FileWriteTest, FileWriteTestFixture,
305 ::testing::Values(WriteRecipe{{0x10000}}, WriteRecipe{{0x10000, 0x1000b5}},
306 WriteRecipe{{0x10000, 0x1000b5}, {0xfff4b, 0x10000}},
307 WriteRecipe{{0x1000b5, 0xfff4b}, {0x10000}},
308 WriteRecipe{{65536, 517, 65717}},
309 WriteRecipe{{65536, 517, 518, 511},
310 {514},
311 {505, 514},
312 {505, 514, 65355, 519}},
313 WriteRecipe{{65536, 518, 511, 511},
314 {65717},
315 {65717, 65717, 518},
316 {65536, 65536, 508, 65355},
317 {515, 519}},
318 WriteRecipe{{0x1000b5, 0xfff4b, 0x100000}, {0x10000}}));
319
320} // namespace aos::logger::testing