log_test.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  4. #include "db/log_reader.h"
  5. #include "db/log_writer.h"
  6. #include "leveldb/env.h"
  7. #include "util/coding.h"
  8. #include "util/crc32c.h"
  9. #include "util/random.h"
  10. #include "util/testharness.h"
  11. namespace leveldb {
  12. namespace log {
  13. // Construct a string of the specified length made out of the supplied
  14. // partial string.
  15. static std::string BigString(const std::string& partial_string, size_t n) {
  16. std::string result;
  17. while (result.size() < n) {
  18. result.append(partial_string);
  19. }
  20. result.resize(n);
  21. return result;
  22. }
  23. // Construct a string from a number
  24. static std::string NumberString(int n) {
  25. char buf[50];
  26. snprintf(buf, sizeof(buf), "%d.", n);
  27. return std::string(buf);
  28. }
  29. // Return a skewed potentially long string
  30. static std::string RandomSkewedString(int i, Random* rnd) {
  31. return BigString(NumberString(i), rnd->Skewed(17));
  32. }
  33. class LogTest {
  34. private:
  35. class StringDest : public WritableFile {
  36. public:
  37. std::string contents_;
  38. virtual Status Close() { return Status::OK(); }
  39. virtual Status Flush() { return Status::OK(); }
  40. virtual Status Sync() { return Status::OK(); }
  41. virtual Status Append(const Slice& slice) {
  42. contents_.append(slice.data(), slice.size());
  43. return Status::OK();
  44. }
  45. };
  46. class StringSource : public SequentialFile {
  47. public:
  48. Slice contents_;
  49. bool force_error_;
  50. bool returned_partial_;
  51. StringSource() : force_error_(false), returned_partial_(false) { }
  52. virtual Status Read(size_t n, Slice* result, char* scratch) {
  53. ASSERT_TRUE(!returned_partial_) << "must not Read() after eof/error";
  54. if (force_error_) {
  55. force_error_ = false;
  56. returned_partial_ = true;
  57. return Status::Corruption("read error");
  58. }
  59. if (contents_.size() < n) {
  60. n = contents_.size();
  61. returned_partial_ = true;
  62. }
  63. *result = Slice(contents_.data(), n);
  64. contents_.remove_prefix(n);
  65. return Status::OK();
  66. }
  67. virtual Status Skip(uint64_t n) {
  68. if (n > contents_.size()) {
  69. contents_.clear();
  70. return Status::NotFound("in-memory file skipepd past end");
  71. }
  72. contents_.remove_prefix(n);
  73. return Status::OK();
  74. }
  75. };
  76. class ReportCollector : public Reader::Reporter {
  77. public:
  78. size_t dropped_bytes_;
  79. std::string message_;
  80. ReportCollector() : dropped_bytes_(0) { }
  81. virtual void Corruption(size_t bytes, const Status& status) {
  82. dropped_bytes_ += bytes;
  83. message_.append(status.ToString());
  84. }
  85. };
  86. StringDest dest_;
  87. StringSource source_;
  88. ReportCollector report_;
  89. bool reading_;
  90. Writer* writer_;
  91. Reader reader_;
  92. // Record metadata for testing initial offset functionality
  93. static size_t initial_offset_record_sizes_[];
  94. static uint64_t initial_offset_last_record_offsets_[];
  95. public:
  96. LogTest() : reading_(false),
  97. writer_(new Writer(&dest_)),
  98. reader_(&source_, &report_, true/*checksum*/,
  99. 0/*initial_offset*/) {
  100. }
  101. ~LogTest() {
  102. delete writer_;
  103. }
  104. void ReopenForAppend() {
  105. delete writer_;
  106. writer_ = new Writer(&dest_, dest_.contents_.size());
  107. }
  108. void Write(const std::string& msg) {
  109. ASSERT_TRUE(!reading_) << "Write() after starting to read";
  110. writer_->AddRecord(Slice(msg));
  111. }
  112. size_t WrittenBytes() const {
  113. return dest_.contents_.size();
  114. }
  115. std::string Read() {
  116. if (!reading_) {
  117. reading_ = true;
  118. source_.contents_ = Slice(dest_.contents_);
  119. }
  120. std::string scratch;
  121. Slice record;
  122. if (reader_.ReadRecord(&record, &scratch)) {
  123. return record.ToString();
  124. } else {
  125. return "EOF";
  126. }
  127. }
  128. void IncrementByte(int offset, int delta) {
  129. dest_.contents_[offset] += delta;
  130. }
  131. void SetByte(int offset, char new_byte) {
  132. dest_.contents_[offset] = new_byte;
  133. }
  134. void ShrinkSize(int bytes) {
  135. dest_.contents_.resize(dest_.contents_.size() - bytes);
  136. }
  137. void FixChecksum(int header_offset, int len) {
  138. // Compute crc of type/len/data
  139. uint32_t crc = crc32c::Value(&dest_.contents_[header_offset+6], 1 + len);
  140. crc = crc32c::Mask(crc);
  141. EncodeFixed32(&dest_.contents_[header_offset], crc);
  142. }
  143. void ForceError() {
  144. source_.force_error_ = true;
  145. }
  146. size_t DroppedBytes() const {
  147. return report_.dropped_bytes_;
  148. }
  149. std::string ReportMessage() const {
  150. return report_.message_;
  151. }
  152. // Returns OK iff recorded error message contains "msg"
  153. std::string MatchError(const std::string& msg) const {
  154. if (report_.message_.find(msg) == std::string::npos) {
  155. return report_.message_;
  156. } else {
  157. return "OK";
  158. }
  159. }
  160. void WriteInitialOffsetLog() {
  161. for (int i = 0; i < 4; i++) {
  162. std::string record(initial_offset_record_sizes_[i],
  163. static_cast<char>('a' + i));
  164. Write(record);
  165. }
  166. }
  167. void CheckOffsetPastEndReturnsNoRecords(uint64_t offset_past_end) {
  168. WriteInitialOffsetLog();
  169. reading_ = true;
  170. source_.contents_ = Slice(dest_.contents_);
  171. Reader* offset_reader = new Reader(&source_, &report_, true/*checksum*/,
  172. WrittenBytes() + offset_past_end);
  173. Slice record;
  174. std::string scratch;
  175. ASSERT_TRUE(!offset_reader->ReadRecord(&record, &scratch));
  176. delete offset_reader;
  177. }
  178. void CheckInitialOffsetRecord(uint64_t initial_offset,
  179. int expected_record_offset) {
  180. WriteInitialOffsetLog();
  181. reading_ = true;
  182. source_.contents_ = Slice(dest_.contents_);
  183. Reader* offset_reader = new Reader(&source_, &report_, true/*checksum*/,
  184. initial_offset);
  185. Slice record;
  186. std::string scratch;
  187. ASSERT_TRUE(offset_reader->ReadRecord(&record, &scratch));
  188. ASSERT_EQ(initial_offset_record_sizes_[expected_record_offset],
  189. record.size());
  190. ASSERT_EQ(initial_offset_last_record_offsets_[expected_record_offset],
  191. offset_reader->LastRecordOffset());
  192. ASSERT_EQ((char)('a' + expected_record_offset), record.data()[0]);
  193. delete offset_reader;
  194. }
  195. };
  196. size_t LogTest::initial_offset_record_sizes_[] =
  197. {10000, // Two sizable records in first block
  198. 10000,
  199. 2 * log::kBlockSize - 1000, // Span three blocks
  200. 1};
  201. uint64_t LogTest::initial_offset_last_record_offsets_[] =
  202. {0,
  203. kHeaderSize + 10000,
  204. 2 * (kHeaderSize + 10000),
  205. 2 * (kHeaderSize + 10000) +
  206. (2 * log::kBlockSize - 1000) + 3 * kHeaderSize};
  207. TEST(LogTest, Empty) {
  208. ASSERT_EQ("EOF", Read());
  209. }
  210. TEST(LogTest, ReadWrite) {
  211. Write("foo");
  212. Write("bar");
  213. Write("");
  214. Write("xxxx");
  215. ASSERT_EQ("foo", Read());
  216. ASSERT_EQ("bar", Read());
  217. ASSERT_EQ("", Read());
  218. ASSERT_EQ("xxxx", Read());
  219. ASSERT_EQ("EOF", Read());
  220. ASSERT_EQ("EOF", Read()); // Make sure reads at eof work
  221. }
  222. TEST(LogTest, ManyBlocks) {
  223. for (int i = 0; i < 100000; i++) {
  224. Write(NumberString(i));
  225. }
  226. for (int i = 0; i < 100000; i++) {
  227. ASSERT_EQ(NumberString(i), Read());
  228. }
  229. ASSERT_EQ("EOF", Read());
  230. }
  231. TEST(LogTest, Fragmentation) {
  232. Write("small");
  233. Write(BigString("medium", 50000));
  234. Write(BigString("large", 100000));
  235. ASSERT_EQ("small", Read());
  236. ASSERT_EQ(BigString("medium", 50000), Read());
  237. ASSERT_EQ(BigString("large", 100000), Read());
  238. ASSERT_EQ("EOF", Read());
  239. }
  240. TEST(LogTest, MarginalTrailer) {
  241. // Make a trailer that is exactly the same length as an empty record.
  242. const int n = kBlockSize - 2*kHeaderSize;
  243. Write(BigString("foo", n));
  244. ASSERT_EQ(kBlockSize - kHeaderSize, WrittenBytes());
  245. Write("");
  246. Write("bar");
  247. ASSERT_EQ(BigString("foo", n), Read());
  248. ASSERT_EQ("", Read());
  249. ASSERT_EQ("bar", Read());
  250. ASSERT_EQ("EOF", Read());
  251. }
  252. TEST(LogTest, MarginalTrailer2) {
  253. // Make a trailer that is exactly the same length as an empty record.
  254. const int n = kBlockSize - 2*kHeaderSize;
  255. Write(BigString("foo", n));
  256. ASSERT_EQ(kBlockSize - kHeaderSize, WrittenBytes());
  257. Write("bar");
  258. ASSERT_EQ(BigString("foo", n), Read());
  259. ASSERT_EQ("bar", Read());
  260. ASSERT_EQ("EOF", Read());
  261. ASSERT_EQ(0, DroppedBytes());
  262. ASSERT_EQ("", ReportMessage());
  263. }
  264. TEST(LogTest, ShortTrailer) {
  265. const int n = kBlockSize - 2*kHeaderSize + 4;
  266. Write(BigString("foo", n));
  267. ASSERT_EQ(kBlockSize - kHeaderSize + 4, WrittenBytes());
  268. Write("");
  269. Write("bar");
  270. ASSERT_EQ(BigString("foo", n), Read());
  271. ASSERT_EQ("", Read());
  272. ASSERT_EQ("bar", Read());
  273. ASSERT_EQ("EOF", Read());
  274. }
  275. TEST(LogTest, AlignedEof) {
  276. const int n = kBlockSize - 2*kHeaderSize + 4;
  277. Write(BigString("foo", n));
  278. ASSERT_EQ(kBlockSize - kHeaderSize + 4, WrittenBytes());
  279. ASSERT_EQ(BigString("foo", n), Read());
  280. ASSERT_EQ("EOF", Read());
  281. }
  282. TEST(LogTest, OpenForAppend) {
  283. Write("hello");
  284. ReopenForAppend();
  285. Write("world");
  286. ASSERT_EQ("hello", Read());
  287. ASSERT_EQ("world", Read());
  288. ASSERT_EQ("EOF", Read());
  289. }
  290. TEST(LogTest, RandomRead) {
  291. const int N = 500;
  292. Random write_rnd(301);
  293. for (int i = 0; i < N; i++) {
  294. Write(RandomSkewedString(i, &write_rnd));
  295. }
  296. Random read_rnd(301);
  297. for (int i = 0; i < N; i++) {
  298. ASSERT_EQ(RandomSkewedString(i, &read_rnd), Read());
  299. }
  300. ASSERT_EQ("EOF", Read());
  301. }
  302. // Tests of all the error paths in log_reader.cc follow:
  303. TEST(LogTest, ReadError) {
  304. Write("foo");
  305. ForceError();
  306. ASSERT_EQ("EOF", Read());
  307. ASSERT_EQ(kBlockSize, DroppedBytes());
  308. ASSERT_EQ("OK", MatchError("read error"));
  309. }
  310. TEST(LogTest, BadRecordType) {
  311. Write("foo");
  312. // Type is stored in header[6]
  313. IncrementByte(6, 100);
  314. FixChecksum(0, 3);
  315. ASSERT_EQ("EOF", Read());
  316. ASSERT_EQ(3, DroppedBytes());
  317. ASSERT_EQ("OK", MatchError("unknown record type"));
  318. }
  319. TEST(LogTest, TruncatedTrailingRecordIsIgnored) {
  320. Write("foo");
  321. ShrinkSize(4); // Drop all payload as well as a header byte
  322. ASSERT_EQ("EOF", Read());
  323. // Truncated last record is ignored, not treated as an error.
  324. ASSERT_EQ(0, DroppedBytes());
  325. ASSERT_EQ("", ReportMessage());
  326. }
  327. TEST(LogTest, BadLength) {
  328. const int kPayloadSize = kBlockSize - kHeaderSize;
  329. Write(BigString("bar", kPayloadSize));
  330. Write("foo");
  331. // Least significant size byte is stored in header[4].
  332. IncrementByte(4, 1);
  333. ASSERT_EQ("foo", Read());
  334. ASSERT_EQ(kBlockSize, DroppedBytes());
  335. ASSERT_EQ("OK", MatchError("bad record length"));
  336. }
  337. TEST(LogTest, BadLengthAtEndIsIgnored) {
  338. Write("foo");
  339. ShrinkSize(1);
  340. ASSERT_EQ("EOF", Read());
  341. ASSERT_EQ(0, DroppedBytes());
  342. ASSERT_EQ("", ReportMessage());
  343. }
  344. TEST(LogTest, ChecksumMismatch) {
  345. Write("foo");
  346. IncrementByte(0, 10);
  347. ASSERT_EQ("EOF", Read());
  348. ASSERT_EQ(10, DroppedBytes());
  349. ASSERT_EQ("OK", MatchError("checksum mismatch"));
  350. }
  351. TEST(LogTest, UnexpectedMiddleType) {
  352. Write("foo");
  353. SetByte(6, kMiddleType);
  354. FixChecksum(0, 3);
  355. ASSERT_EQ("EOF", Read());
  356. ASSERT_EQ(3, DroppedBytes());
  357. ASSERT_EQ("OK", MatchError("missing start"));
  358. }
  359. TEST(LogTest, UnexpectedLastType) {
  360. Write("foo");
  361. SetByte(6, kLastType);
  362. FixChecksum(0, 3);
  363. ASSERT_EQ("EOF", Read());
  364. ASSERT_EQ(3, DroppedBytes());
  365. ASSERT_EQ("OK", MatchError("missing start"));
  366. }
  367. TEST(LogTest, UnexpectedFullType) {
  368. Write("foo");
  369. Write("bar");
  370. SetByte(6, kFirstType);
  371. FixChecksum(0, 3);
  372. ASSERT_EQ("bar", Read());
  373. ASSERT_EQ("EOF", Read());
  374. ASSERT_EQ(3, DroppedBytes());
  375. ASSERT_EQ("OK", MatchError("partial record without end"));
  376. }
  377. TEST(LogTest, UnexpectedFirstType) {
  378. Write("foo");
  379. Write(BigString("bar", 100000));
  380. SetByte(6, kFirstType);
  381. FixChecksum(0, 3);
  382. ASSERT_EQ(BigString("bar", 100000), Read());
  383. ASSERT_EQ("EOF", Read());
  384. ASSERT_EQ(3, DroppedBytes());
  385. ASSERT_EQ("OK", MatchError("partial record without end"));
  386. }
  387. TEST(LogTest, MissingLastIsIgnored) {
  388. Write(BigString("bar", kBlockSize));
  389. // Remove the LAST block, including header.
  390. ShrinkSize(14);
  391. ASSERT_EQ("EOF", Read());
  392. ASSERT_EQ("", ReportMessage());
  393. ASSERT_EQ(0, DroppedBytes());
  394. }
  395. TEST(LogTest, PartialLastIsIgnored) {
  396. Write(BigString("bar", kBlockSize));
  397. // Cause a bad record length in the LAST block.
  398. ShrinkSize(1);
  399. ASSERT_EQ("EOF", Read());
  400. ASSERT_EQ("", ReportMessage());
  401. ASSERT_EQ(0, DroppedBytes());
  402. }
  403. TEST(LogTest, ErrorJoinsRecords) {
  404. // Consider two fragmented records:
  405. // first(R1) last(R1) first(R2) last(R2)
  406. // where the middle two fragments disappear. We do not want
  407. // first(R1),last(R2) to get joined and returned as a valid record.
  408. // Write records that span two blocks
  409. Write(BigString("foo", kBlockSize));
  410. Write(BigString("bar", kBlockSize));
  411. Write("correct");
  412. // Wipe the middle block
  413. for (int offset = kBlockSize; offset < 2*kBlockSize; offset++) {
  414. SetByte(offset, 'x');
  415. }
  416. ASSERT_EQ("correct", Read());
  417. ASSERT_EQ("EOF", Read());
  418. const size_t dropped = DroppedBytes();
  419. ASSERT_LE(dropped, 2*kBlockSize + 100);
  420. ASSERT_GE(dropped, 2*kBlockSize);
  421. }
  422. TEST(LogTest, ReadStart) {
  423. CheckInitialOffsetRecord(0, 0);
  424. }
  425. TEST(LogTest, ReadSecondOneOff) {
  426. CheckInitialOffsetRecord(1, 1);
  427. }
  428. TEST(LogTest, ReadSecondTenThousand) {
  429. CheckInitialOffsetRecord(10000, 1);
  430. }
  431. TEST(LogTest, ReadSecondStart) {
  432. CheckInitialOffsetRecord(10007, 1);
  433. }
  434. TEST(LogTest, ReadThirdOneOff) {
  435. CheckInitialOffsetRecord(10008, 2);
  436. }
  437. TEST(LogTest, ReadThirdStart) {
  438. CheckInitialOffsetRecord(20014, 2);
  439. }
  440. TEST(LogTest, ReadFourthOneOff) {
  441. CheckInitialOffsetRecord(20015, 3);
  442. }
  443. TEST(LogTest, ReadFourthFirstBlockTrailer) {
  444. CheckInitialOffsetRecord(log::kBlockSize - 4, 3);
  445. }
  446. TEST(LogTest, ReadFourthMiddleBlock) {
  447. CheckInitialOffsetRecord(log::kBlockSize + 1, 3);
  448. }
  449. TEST(LogTest, ReadFourthLastBlock) {
  450. CheckInitialOffsetRecord(2 * log::kBlockSize + 1, 3);
  451. }
  452. TEST(LogTest, ReadFourthStart) {
  453. CheckInitialOffsetRecord(
  454. 2 * (kHeaderSize + 1000) + (2 * log::kBlockSize - 1000) + 3 * kHeaderSize,
  455. 3);
  456. }
  457. TEST(LogTest, ReadEnd) {
  458. CheckOffsetPastEndReturnsNoRecords(0);
  459. }
  460. TEST(LogTest, ReadPastEnd) {
  461. CheckOffsetPastEndReturnsNoRecords(5);
  462. }
  463. } // namespace log
  464. } // namespace leveldb
  465. int main(int argc, char** argv) {
  466. return leveldb::test::RunAllTests();
  467. }