作者: 韩晨旭 10225101440 李畅 10225102463
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

548 行
14 KiB

Release 1.18 Changes are: * Update version number to 1.18 * Replace the basic fprintf call with a call to fwrite in order to work around the apparent compiler optimization/rewrite failure that we are seeing with the new toolchain/iOS SDKs provided with Xcode6 and iOS8. * Fix ALL the header guards. * Createed a README.md with the LevelDB project description. * A new CONTRIBUTING file. * Don't implicitly convert uint64_t to size_t or int. Either preserve it as uint64_t, or explicitly cast. This fixes MSVC warnings about possible value truncation when compiling this code in Chromium. * Added a DumpFile() library function that encapsulates the guts of the "leveldbutil dump" command. This will allow clients to dump data to their log files instead of stdout. It will also allow clients to supply their own environment. * leveldb: Remove unused function 'ConsumeChar'. * leveldbutil: Remove unused member variables from WriteBatchItemPrinter. * OpenBSD, NetBSD and DragonflyBSD have _LITTLE_ENDIAN, so define PLATFORM_IS_LITTLE_ENDIAN like on FreeBSD. This fixes: * issue #143 * issue #198 * issue #249 * Switch from <cstdatomic> to <atomic>. The former never made it into the standard and doesn't exist in modern gcc versions at all. The later contains everything that leveldb was using from the former. This problem was noticed when porting to Portable Native Client where no memory barrier is defined. The fact that <cstdatomic> is missing normally goes unnoticed since memory barriers are defined for most architectures. * Make Hash() treat its input as unsigned. Before this change LevelDB files from platforms with different signedness of char were not compatible. This change fixes: issue #243 * Verify checksums of index/meta/filter blocks when paranoid_checks set. * Invoke all tools for iOS with xcrun. (This was causing problems with the new XCode 5.1.1 image on pulse.) * include <sys/stat.h> only once, and fix the following linter warning: "Found C system header after C++ system header" * When encountering a corrupted table file, return Status::Corruption instead of Status::InvalidArgument. * Support cygwin as build platform, patch is from https://code.google.com/p/leveldb/issues/detail?id=188 * Fix typo, merge patch from https://code.google.com/p/leveldb/issues/detail?id=159 * Fix typos and comments, and address the following two issues: * issue #166 * issue #241 * Add missing db synchronize after "fillseq" in the benchmark. * Removed unused variable in SeekRandom: value (issue #201)
10年前
  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. }