• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "SerializedFlushToState.h"
18 
19 #include <map>
20 
21 #include <android-base/logging.h>
22 #include <android-base/stringprintf.h>
23 #include <android-base/strings.h>
24 #include <gtest/gtest.h>
25 
26 using android::base::Join;
27 using android::base::StringPrintf;
28 
29 constexpr size_t kChunkSize = 3 * 4096;
30 
31 class SerializedFlushToStateTest : public testing::Test {
32   protected:
SetUp()33     void SetUp() override {
34         // This test spams many unneeded INFO logs, so we suppress them.
35         old_log_severity_ = android::base::SetMinimumLogSeverity(android::base::WARNING);
36     }
TearDown()37     void TearDown() override { android::base::SetMinimumLogSeverity(old_log_severity_); }
38 
TestReport(const std::vector<uint64_t> & expected,const std::vector<uint64_t> & read)39     std::string TestReport(const std::vector<uint64_t>& expected, const std::vector<uint64_t>& read)
40             REQUIRES(logd_lock) {
41         auto sequence_to_log_id = [&](uint64_t sequence) -> int {
42             for (const auto& [log_id, sequences] : sequence_numbers_per_buffer_) {
43                 if (std::find(sequences.begin(), sequences.end(), sequence) != sequences.end()) {
44                     return log_id;
45                 }
46             }
47             return -1;
48         };
49 
50         std::map<int, std::vector<uint64_t>> missing_sequences;
51         std::vector<uint64_t> missing_expected;
52         std::set_difference(expected.begin(), expected.end(), read.begin(), read.end(),
53                             std::back_inserter(missing_expected));
54         for (uint64_t sequence : missing_expected) {
55             int log_id = sequence_to_log_id(sequence);
56             missing_sequences[log_id].emplace_back(sequence);
57         }
58 
59         std::map<int, std::vector<uint64_t>> extra_sequences;
60         std::vector<uint64_t> extra_read;
61         std::set_difference(read.begin(), read.end(), expected.begin(), expected.end(),
62                             std::back_inserter(extra_read));
63         for (uint64_t sequence : extra_read) {
64             int log_id = sequence_to_log_id(sequence);
65             extra_sequences[log_id].emplace_back(sequence);
66         }
67 
68         std::vector<std::string> errors;
69         for (const auto& [log_id, sequences] : missing_sequences) {
70             errors.emplace_back(
71                     StringPrintf("Log id %d missing %zu sequences", log_id, sequences.size()));
72         }
73 
74         for (const auto& [log_id, sequences] : extra_sequences) {
75             errors.emplace_back(
76                     StringPrintf("Log id %d has extra %zu sequences", log_id, sequences.size()));
77         }
78 
79         return Join(errors, ", ");
80     }
81 
82     // Read sequence numbers in order from SerializedFlushToState for every mask combination and all
83     // sequence numbers from 0 through the highest logged sequence number + 1.
84     // This assumes that all of the logs have already been written.
TestAllReading()85     void TestAllReading() REQUIRES(logd_lock) {
86         uint64_t max_sequence = sequence_ + 1;
87         uint32_t max_mask = (1 << LOG_ID_MAX) - 1;
88         for (uint64_t sequence = 0; sequence < max_sequence; ++sequence) {
89             for (uint32_t mask = 0; mask < max_mask; ++mask) {
90                 auto state = SerializedFlushToState{sequence, mask, log_chunks_};
91                 TestReading(sequence, mask, state);
92             }
93         }
94     }
95 
96     // Similar to TestAllReading() except that it doesn't assume any logs are in the buffer, instead
97     // it calls write_logs() in a loop for sequence/mask combination.  It clears log_chunks_ and
98     // sequence_numbers_per_buffer_ between calls, such that only the sequence numbers written in
99     // the previous call to write_logs() are expected.
TestAllReadingWithFutureMessages(const std::function<bool (int)> & write_logs)100     void TestAllReadingWithFutureMessages(const std::function<bool(int)>& write_logs)
101             REQUIRES(logd_lock) {
102         uint64_t max_sequence = sequence_ + 1;
103         uint32_t max_mask = (1 << LOG_ID_MAX) - 1;
104         for (uint64_t sequence = 1; sequence < max_sequence; ++sequence) {
105             for (uint32_t mask = 1; mask < max_mask; ++mask) {
106                 log_id_for_each(i) { log_chunks_[i].clear(); }
107                 auto state = SerializedFlushToState{sequence, mask, log_chunks_};
108                 int loop_count = 0;
109                 while (write_logs(loop_count++)) {
110                     TestReading(sequence, mask, state);
111                     sequence_numbers_per_buffer_.clear();
112                 }
113             }
114         }
115     }
116 
TestReading(uint64_t start,LogMask log_mask,SerializedFlushToState & state)117     void TestReading(uint64_t start, LogMask log_mask, SerializedFlushToState& state)
118             REQUIRES(logd_lock) {
119         std::vector<uint64_t> expected_sequence;
120         log_id_for_each(i) {
121             if (((1 << i) & log_mask) == 0) {
122                 continue;
123             }
124             for (const auto& sequence : sequence_numbers_per_buffer_[i]) {
125                 if (sequence >= start) {
126                     expected_sequence.emplace_back(sequence);
127                 }
128             }
129         }
130         std::sort(expected_sequence.begin(), expected_sequence.end());
131 
132         std::vector<uint64_t> read_sequence;
133 
134         while (state.HasUnreadLogs()) {
135             auto top = state.PopNextUnreadLog();
136             read_sequence.emplace_back(top.entry->sequence());
137         }
138 
139         EXPECT_TRUE(std::is_sorted(read_sequence.begin(), read_sequence.end()));
140 
141         EXPECT_EQ(expected_sequence.size(), read_sequence.size());
142 
143         EXPECT_EQ(expected_sequence, read_sequence)
144                 << "start: " << start << " log_mask: " << log_mask << " "
145                 << TestReport(expected_sequence, read_sequence);
146     }
147 
148     // Add a chunk with the given messages to the a given log buffer.  Keep track of the sequence
149     // numbers for future validation.  Optionally mark the block as having finished writing.
AddChunkWithMessages(bool finish_writing,int buffer,const std::vector<std::string> & messages)150     void AddChunkWithMessages(bool finish_writing, int buffer,
151                               const std::vector<std::string>& messages) REQUIRES(logd_lock) {
152         auto chunk = SerializedLogChunk{kChunkSize};
153         for (const auto& message : messages) {
154             auto sequence = sequence_++;
155             sequence_numbers_per_buffer_[buffer].emplace_back(sequence);
156             ASSERT_TRUE(chunk.CanLog(message.size() + 1));
157             chunk.Log(sequence, log_time(), 0, 1, 1, message.c_str(), message.size() + 1);
158         }
159         if (finish_writing) {
160             chunk.FinishWriting();
161         }
162         log_chunks_[buffer].emplace_back(std::move(chunk));
163     }
164 
165     android::base::LogSeverity old_log_severity_;
166     std::map<int, std::vector<uint64_t>> sequence_numbers_per_buffer_;
167     std::list<SerializedLogChunk> log_chunks_[LOG_ID_MAX];
168     uint64_t sequence_ = 1;
169 };
170 
171 // 0: multiple chunks, with variable number of entries, with/without finishing writing
172 // 1: 1 chunk with 1 log and finished writing
173 // 2: 1 chunk with 1 log and not finished writing
174 // 3: 1 chunk with 0 logs and not finished writing
175 // 4: 1 chunk with 0 logs and finished writing (impossible, but SerializedFlushToState handles it)
176 // 5-7: 0 chunks
TEST_F(SerializedFlushToStateTest,smoke)177 TEST_F(SerializedFlushToStateTest, smoke) {
178     auto lock = std::lock_guard{logd_lock};
179     AddChunkWithMessages(true, 0, {"1st", "2nd"});
180     AddChunkWithMessages(true, 1, {"3rd"});
181     AddChunkWithMessages(false, 0, {"4th"});
182     AddChunkWithMessages(true, 0, {"4th", "5th", "more", "even", "more", "go", "here"});
183     AddChunkWithMessages(false, 2, {"6th"});
184     AddChunkWithMessages(true, 0, {"7th"});
185     AddChunkWithMessages(false, 3, {});
186     AddChunkWithMessages(true, 4, {});
187 
188     TestAllReading();
189 }
190 
TEST_F(SerializedFlushToStateTest,random)191 TEST_F(SerializedFlushToStateTest, random) {
192     auto lock = std::lock_guard{logd_lock};
193     srand(1);
194     for (int count = 0; count < 20; ++count) {
195         unsigned int num_messages = 1 + rand() % 15;
196         auto messages = std::vector<std::string>{num_messages, "same message"};
197 
198         bool compress = rand() % 2;
199         int buf = rand() % LOG_ID_MAX;
200 
201         AddChunkWithMessages(compress, buf, messages);
202     }
203 
204     TestAllReading();
205 }
206 
207 // Same start as smoke, but we selectively write logs to the buffers and ensure they're read.
TEST_F(SerializedFlushToStateTest,future_writes)208 TEST_F(SerializedFlushToStateTest, future_writes) {
209     auto lock = std::lock_guard{logd_lock};
210     auto write_logs = [&](int loop_count) REQUIRES(logd_lock) {
211         switch (loop_count) {
212             case 0:
213                 // Initial writes.
214                 AddChunkWithMessages(true, 0, {"1st", "2nd"});
215                 AddChunkWithMessages(true, 1, {"3rd"});
216                 AddChunkWithMessages(false, 0, {"4th"});
217                 AddChunkWithMessages(true, 0, {"4th", "5th", "more", "even", "more", "go", "here"});
218                 AddChunkWithMessages(false, 2, {"6th"});
219                 AddChunkWithMessages(true, 0, {"7th"});
220                 AddChunkWithMessages(false, 3, {});
221                 AddChunkWithMessages(true, 4, {});
222                 break;
223             case 1:
224                 // Smoke test, add a simple chunk.
225                 AddChunkWithMessages(true, 0, {"1st", "2nd"});
226                 break;
227             case 2:
228                 // Add chunks to all but one of the logs.
229                 AddChunkWithMessages(true, 0, {"1st", "2nd"});
230                 AddChunkWithMessages(true, 1, {"1st", "2nd"});
231                 AddChunkWithMessages(true, 2, {"1st", "2nd"});
232                 AddChunkWithMessages(true, 3, {"1st", "2nd"});
233                 AddChunkWithMessages(true, 4, {"1st", "2nd"});
234                 AddChunkWithMessages(true, 5, {"1st", "2nd"});
235                 AddChunkWithMessages(true, 6, {"1st", "2nd"});
236                 break;
237             case 3:
238                 // Finally add chunks to all logs.
239                 AddChunkWithMessages(true, 0, {"1st", "2nd"});
240                 AddChunkWithMessages(true, 1, {"1st", "2nd"});
241                 AddChunkWithMessages(true, 2, {"1st", "2nd"});
242                 AddChunkWithMessages(true, 3, {"1st", "2nd"});
243                 AddChunkWithMessages(true, 4, {"1st", "2nd"});
244                 AddChunkWithMessages(true, 5, {"1st", "2nd"});
245                 AddChunkWithMessages(true, 6, {"1st", "2nd"});
246                 AddChunkWithMessages(true, 7, {"1st", "2nd"});
247                 break;
248             default:
249                 return false;
250         }
251         return true;
252     };
253 
254     TestAllReadingWithFutureMessages(write_logs);
255 }
256 
TEST_F(SerializedFlushToStateTest,no_dangling_references)257 TEST_F(SerializedFlushToStateTest, no_dangling_references) {
258     auto lock = std::lock_guard{logd_lock};
259     AddChunkWithMessages(true, 0, {"1st", "2nd"});
260     AddChunkWithMessages(true, 0, {"3rd", "4th"});
261 
262     auto state = SerializedFlushToState{1, kLogMaskAll, log_chunks_};
263 
264     ASSERT_EQ(log_chunks_[0].size(), 2U);
265     auto first_chunk = log_chunks_[0].begin();
266     auto second_chunk = std::next(first_chunk);
267 
268     ASSERT_TRUE(state.HasUnreadLogs());
269     auto first_log = state.PopNextUnreadLog();
270     EXPECT_STREQ(first_log.entry->msg(), "1st");
271     EXPECT_EQ(first_chunk->reader_ref_count(), 1U);
272     EXPECT_EQ(second_chunk->reader_ref_count(), 0U);
273 
274     ASSERT_TRUE(state.HasUnreadLogs());
275     auto second_log = state.PopNextUnreadLog();
276     EXPECT_STREQ(second_log.entry->msg(), "2nd");
277     EXPECT_EQ(first_chunk->reader_ref_count(), 1U);
278     EXPECT_EQ(second_chunk->reader_ref_count(), 0U);
279 
280     ASSERT_TRUE(state.HasUnreadLogs());
281     auto third_log = state.PopNextUnreadLog();
282     EXPECT_STREQ(third_log.entry->msg(), "3rd");
283     EXPECT_EQ(first_chunk->reader_ref_count(), 0U);
284     EXPECT_EQ(second_chunk->reader_ref_count(), 1U);
285 
286     ASSERT_TRUE(state.HasUnreadLogs());
287     auto fourth_log = state.PopNextUnreadLog();
288     EXPECT_STREQ(fourth_log.entry->msg(), "4th");
289     EXPECT_EQ(first_chunk->reader_ref_count(), 0U);
290     EXPECT_EQ(second_chunk->reader_ref_count(), 1U);
291 
292     EXPECT_FALSE(state.HasUnreadLogs());
293 }
294 
TEST(SerializedFlushToState,Prune)295 TEST(SerializedFlushToState, Prune) {
296     auto lock = std::lock_guard{logd_lock};
297     auto chunk = SerializedLogChunk{kChunkSize};
298     chunk.Log(1, log_time(), 0, 1, 1, "abc", 3);
299     chunk.Log(2, log_time(), 0, 1, 1, "abc", 3);
300     chunk.Log(3, log_time(), 0, 1, 1, "abc", 3);
301     chunk.FinishWriting();
302 
303     std::list<SerializedLogChunk> log_chunks[LOG_ID_MAX];
304     log_chunks[LOG_ID_MAIN].emplace_back(std::move(chunk));
305 
306     auto state = SerializedFlushToState{1, kLogMaskAll, log_chunks};
307     ASSERT_TRUE(state.HasUnreadLogs());
308 
309     state.Prune(LOG_ID_MAIN);
310 }
311