testutil.h 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. //
  6. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  7. // Use of this source code is governed by a BSD-style license that can be
  8. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  9. #pragma once
  10. #include <algorithm>
  11. #include <deque>
  12. #include <string>
  13. #include <vector>
  14. #include "env/composite_env_wrapper.h"
  15. #include "file/writable_file_writer.h"
  16. #include "rocksdb/compaction_filter.h"
  17. #include "rocksdb/env.h"
  18. #include "rocksdb/iterator.h"
  19. #include "rocksdb/merge_operator.h"
  20. #include "rocksdb/options.h"
  21. #include "rocksdb/slice.h"
  22. #include "rocksdb/table.h"
  23. #include "table/internal_iterator.h"
  24. #include "util/defer.h"
  25. #include "util/mutexlock.h"
  26. #ifdef ROCKSDB_UNITTESTS_WITH_CUSTOM_OBJECTS_FROM_STATIC_LIBS
  27. extern "C" {
  28. void RegisterCustomObjects(int argc, char** argv);
  29. }
  30. #else
  31. void RegisterCustomObjects(int argc, char** argv);
  32. #endif // !ROCKSDB_UNITTESTS_WITH_CUSTOM_OBJECTS_FROM_STATIC_LIBS
  33. namespace ROCKSDB_NAMESPACE {
  34. class FileSystem;
  35. class MemTableRepFactory;
  36. class ObjectLibrary;
  37. class Random;
  38. class SequentialFile;
  39. class SequentialFileReader;
  40. namespace test {
  41. extern const uint32_t kDefaultFormatVersion;
  42. extern const std::set<uint32_t> kFooterFormatVersionsToTest;
  43. // Return a random key with the specified length that may contain interesting
  44. // characters (e.g. \x00, \xff, etc.).
  45. enum RandomKeyType : char { RANDOM, LARGEST, SMALLEST, MIDDLE };
  46. std::string RandomKey(Random* rnd, int len,
  47. RandomKeyType type = RandomKeyType::RANDOM);
  48. enum class UserDefinedTimestampTestMode {
  49. // Test does not enable user-defined timestamp feature.
  50. kNone,
  51. // Test enables user-defined timestamp feature. Write/read with min timestamps
  52. kNormal,
  53. // Test enables user-defined timestamp feature. Write/read with min timestamps
  54. // Set `persist_user_defined_timestamps` to false.
  55. kStripUserDefinedTimestamp,
  56. };
  57. const std::vector<UserDefinedTimestampTestMode>& GetUDTTestModes();
  58. bool IsUDTEnabled(const UserDefinedTimestampTestMode& test_mode);
  59. bool ShouldPersistUDT(const UserDefinedTimestampTestMode& test_mode);
  60. // Store in *dst a string of length "len" that will compress to
  61. // "N*compressed_fraction" bytes and return a Slice that references
  62. // the generated data.
  63. Slice CompressibleString(Random* rnd, double compressed_to_fraction, int len,
  64. std::string* dst);
  65. inline std::string CompressibleString(Random* rnd,
  66. double compressed_to_fraction, int len) {
  67. std::string dst;
  68. CompressibleString(rnd, compressed_to_fraction, len, &dst);
  69. return dst;
  70. }
  71. #ifndef NDEBUG
  72. // An internal comparator that just forward comparing results from the
  73. // user comparator in it. Can be used to test entities that have no dependency
  74. // on internal key structure but consumes InternalKeyComparator, like
  75. // BlockBasedTable.
  76. class PlainInternalKeyComparator : public InternalKeyComparator {
  77. public:
  78. explicit PlainInternalKeyComparator(const Comparator* c)
  79. : InternalKeyComparator(c) {}
  80. virtual ~PlainInternalKeyComparator() {}
  81. int Compare(const Slice& a, const Slice& b) const override {
  82. return user_comparator()->Compare(a, b);
  83. }
  84. };
  85. #endif
  86. // A test comparator which compare two strings in this way:
  87. // (1) first compare prefix of 8 bytes in alphabet order,
  88. // (2) if two strings share the same prefix, sort the other part of the string
  89. // in the reverse alphabet order.
  90. // This helps simulate the case of compounded key of [entity][timestamp] and
  91. // latest timestamp first.
  92. class SimpleSuffixReverseComparator : public Comparator {
  93. public:
  94. SimpleSuffixReverseComparator() {}
  95. static const char* kClassName() { return "SimpleSuffixReverseComparator"; }
  96. const char* Name() const override { return kClassName(); }
  97. int Compare(const Slice& a, const Slice& b) const override {
  98. Slice prefix_a = Slice(a.data(), 8);
  99. Slice prefix_b = Slice(b.data(), 8);
  100. int prefix_comp = prefix_a.compare(prefix_b);
  101. if (prefix_comp != 0) {
  102. return prefix_comp;
  103. } else {
  104. Slice suffix_a = Slice(a.data() + 8, a.size() - 8);
  105. Slice suffix_b = Slice(b.data() + 8, b.size() - 8);
  106. return -(suffix_a.compare(suffix_b));
  107. }
  108. }
  109. void FindShortestSeparator(std::string* /*start*/,
  110. const Slice& /*limit*/) const override {}
  111. void FindShortSuccessor(std::string* /*key*/) const override {}
  112. };
  113. // Returns a user key comparator that can be used for comparing two uint64_t
  114. // slices. Instead of comparing slices byte-wise, it compares all the 8 bytes
  115. // at once. Assumes same endian-ness is used though the database's lifetime.
  116. // Symantics of comparison would differ from Bytewise comparator in little
  117. // endian machines.
  118. const Comparator* Uint64Comparator();
  119. // A wrapper api for getting the ComparatorWithU64Ts<BytewiseComparator>
  120. const Comparator* BytewiseComparatorWithU64TsWrapper();
  121. // A wrapper api for getting the ComparatorWithU64Ts<ReverseBytewiseComparator>
  122. const Comparator* ReverseBytewiseComparatorWithU64TsWrapper();
  123. class StringSink : public FSWritableFile {
  124. public:
  125. std::string contents_;
  126. explicit StringSink(Slice* reader_contents = nullptr)
  127. : FSWritableFile(),
  128. contents_(""),
  129. reader_contents_(reader_contents),
  130. last_flush_(0) {
  131. if (reader_contents_ != nullptr) {
  132. *reader_contents_ = Slice(contents_.data(), 0);
  133. }
  134. }
  135. const std::string& contents() const { return contents_; }
  136. IOStatus Truncate(uint64_t size, const IOOptions& /*opts*/,
  137. IODebugContext* /*dbg*/) override {
  138. contents_.resize(static_cast<size_t>(size));
  139. return IOStatus::OK();
  140. }
  141. IOStatus Close(const IOOptions& /*opts*/, IODebugContext* /*dbg*/) override {
  142. return IOStatus::OK();
  143. }
  144. IOStatus Flush(const IOOptions& /*opts*/, IODebugContext* /*dbg*/) override {
  145. if (reader_contents_ != nullptr) {
  146. assert(reader_contents_->size() <= last_flush_);
  147. size_t offset = last_flush_ - reader_contents_->size();
  148. *reader_contents_ =
  149. Slice(contents_.data() + offset, contents_.size() - offset);
  150. last_flush_ = contents_.size();
  151. }
  152. return IOStatus::OK();
  153. }
  154. IOStatus Sync(const IOOptions& /*opts*/, IODebugContext* /*dbg*/) override {
  155. return IOStatus::OK();
  156. }
  157. using FSWritableFile::Append;
  158. IOStatus Append(const Slice& slice, const IOOptions& /*opts*/,
  159. IODebugContext* /*dbg*/) override {
  160. contents_.append(slice.data(), slice.size());
  161. return IOStatus::OK();
  162. }
  163. void Drop(size_t bytes) {
  164. if (reader_contents_ != nullptr) {
  165. contents_.resize(contents_.size() - bytes);
  166. *reader_contents_ =
  167. Slice(reader_contents_->data(), reader_contents_->size() - bytes);
  168. last_flush_ = contents_.size();
  169. }
  170. }
  171. uint64_t GetFileSize(const IOOptions& /*options*/,
  172. IODebugContext* /*dbg*/) override {
  173. return contents_.size();
  174. }
  175. private:
  176. Slice* reader_contents_;
  177. size_t last_flush_;
  178. };
  179. // A wrapper around a StringSink to give it a RandomRWFile interface
  180. class RandomRWStringSink : public FSRandomRWFile {
  181. public:
  182. explicit RandomRWStringSink(StringSink* ss) : ss_(ss) {}
  183. IOStatus Write(uint64_t offset, const Slice& data, const IOOptions& /*opts*/,
  184. IODebugContext* /*dbg*/) override {
  185. if (offset + data.size() > ss_->contents_.size()) {
  186. ss_->contents_.resize(static_cast<size_t>(offset) + data.size(), '\0');
  187. }
  188. char* pos = const_cast<char*>(ss_->contents_.data() + offset);
  189. memcpy(pos, data.data(), data.size());
  190. return IOStatus::OK();
  191. }
  192. IOStatus Read(uint64_t offset, size_t n, const IOOptions& /*opts*/,
  193. Slice* result, char* /*scratch*/,
  194. IODebugContext* /*dbg*/) const override {
  195. *result = Slice(nullptr, 0);
  196. if (offset < ss_->contents_.size()) {
  197. size_t str_res_sz =
  198. std::min(static_cast<size_t>(ss_->contents_.size() - offset), n);
  199. *result = Slice(ss_->contents_.data() + offset, str_res_sz);
  200. }
  201. return IOStatus::OK();
  202. }
  203. IOStatus Flush(const IOOptions& /*opts*/, IODebugContext* /*dbg*/) override {
  204. return IOStatus::OK();
  205. }
  206. IOStatus Sync(const IOOptions& /*opts*/, IODebugContext* /*dbg*/) override {
  207. return IOStatus::OK();
  208. }
  209. IOStatus Close(const IOOptions& /*opts*/, IODebugContext* /*dbg*/) override {
  210. return IOStatus::OK();
  211. }
  212. const std::string& contents() const { return ss_->contents(); }
  213. private:
  214. StringSink* ss_;
  215. };
  216. // Like StringSink, this writes into a string. Unlink StringSink, it
  217. // has some initial content and overwrites it, just like a recycled
  218. // log file.
  219. class OverwritingStringSink : public FSWritableFile {
  220. public:
  221. explicit OverwritingStringSink(Slice* reader_contents)
  222. : FSWritableFile(),
  223. contents_(""),
  224. reader_contents_(reader_contents),
  225. last_flush_(0) {}
  226. const std::string& contents() const { return contents_; }
  227. IOStatus Truncate(uint64_t size, const IOOptions& /*opts*/,
  228. IODebugContext* /*dbg*/) override {
  229. contents_.resize(static_cast<size_t>(size));
  230. return IOStatus::OK();
  231. }
  232. IOStatus Close(const IOOptions& /*opts*/, IODebugContext* /*dbg*/) override {
  233. return IOStatus::OK();
  234. }
  235. IOStatus Flush(const IOOptions& /*opts*/, IODebugContext* /*dbg*/) override {
  236. if (last_flush_ < contents_.size()) {
  237. assert(reader_contents_->size() >= contents_.size());
  238. memcpy((char*)reader_contents_->data() + last_flush_,
  239. contents_.data() + last_flush_, contents_.size() - last_flush_);
  240. last_flush_ = contents_.size();
  241. }
  242. return IOStatus::OK();
  243. }
  244. IOStatus Sync(const IOOptions& /*opts*/, IODebugContext* /*dbg*/) override {
  245. return IOStatus::OK();
  246. }
  247. using FSWritableFile::Append;
  248. IOStatus Append(const Slice& slice, const IOOptions& /*opts*/,
  249. IODebugContext* /*dbg*/) override {
  250. contents_.append(slice.data(), slice.size());
  251. return IOStatus::OK();
  252. }
  253. void Drop(size_t bytes) {
  254. contents_.resize(contents_.size() - bytes);
  255. if (last_flush_ > contents_.size()) last_flush_ = contents_.size();
  256. }
  257. uint64_t GetFileSize(const IOOptions& /*options*/,
  258. IODebugContext* /*dbg*/) override {
  259. return contents_.size();
  260. }
  261. private:
  262. std::string contents_;
  263. Slice* reader_contents_;
  264. size_t last_flush_;
  265. };
  266. class StringSource : public FSRandomAccessFile {
  267. public:
  268. explicit StringSource(const Slice& contents, uint64_t uniq_id = 0,
  269. bool mmap = false)
  270. : contents_(contents.data(), contents.size()),
  271. uniq_id_(uniq_id),
  272. mmap_(mmap),
  273. total_reads_(0) {}
  274. virtual ~StringSource() {}
  275. uint64_t Size() const { return contents_.size(); }
  276. IOStatus Prefetch(uint64_t /*offset*/, size_t /*n*/,
  277. const IOOptions& /*options*/,
  278. IODebugContext* /*dbg*/) override {
  279. // If we are using mmap_, it is equivalent to performing a prefetch
  280. if (mmap_) {
  281. return IOStatus::OK();
  282. } else {
  283. return IOStatus::NotSupported("Prefetch not supported");
  284. }
  285. }
  286. IOStatus Read(uint64_t offset, size_t n, const IOOptions& /*opts*/,
  287. Slice* result, char* scratch,
  288. IODebugContext* /*dbg*/) const override {
  289. total_reads_++;
  290. if (offset > contents_.size()) {
  291. return IOStatus::InvalidArgument("invalid Read offset");
  292. }
  293. if (offset + n > contents_.size()) {
  294. n = contents_.size() - static_cast<size_t>(offset);
  295. }
  296. if (!mmap_) {
  297. memcpy(scratch, &contents_[static_cast<size_t>(offset)], n);
  298. *result = Slice(scratch, n);
  299. } else {
  300. *result = Slice(&contents_[static_cast<size_t>(offset)], n);
  301. }
  302. return IOStatus::OK();
  303. }
  304. size_t GetUniqueId(char* id, size_t max_size) const override {
  305. if (max_size < 20) {
  306. return 0;
  307. }
  308. char* rid = id;
  309. rid = EncodeVarint64(rid, uniq_id_);
  310. rid = EncodeVarint64(rid, 0);
  311. return static_cast<size_t>(rid - id);
  312. }
  313. int total_reads() const { return total_reads_; }
  314. void set_total_reads(int tr) { total_reads_ = tr; }
  315. IOStatus GetFileSize(uint64_t* file_size) override {
  316. *file_size = contents_.size();
  317. return IOStatus::OK();
  318. }
  319. private:
  320. std::string contents_;
  321. uint64_t uniq_id_;
  322. bool mmap_;
  323. mutable int total_reads_;
  324. };
  325. class NullLogger : public Logger {
  326. public:
  327. using Logger::Logv;
  328. void Logv(const char* /*format*/, va_list /*ap*/) override {}
  329. size_t GetLogFileSize() const override { return 0; }
  330. };
  331. // Corrupts key by changing the type
  332. void CorruptKeyType(InternalKey* ikey);
  333. std::string KeyStr(const std::string& user_key, const SequenceNumber& seq,
  334. const ValueType& t, bool corrupt = false);
  335. std::string KeyStr(uint64_t ts, const std::string& user_key,
  336. const SequenceNumber& seq, const ValueType& t,
  337. bool corrupt = false);
  338. class SleepingBackgroundTask {
  339. public:
  340. SleepingBackgroundTask()
  341. : bg_cv_(&mutex_),
  342. should_sleep_(true),
  343. done_with_sleep_(false),
  344. sleeping_(false) {}
  345. ~SleepingBackgroundTask() {
  346. MutexLock l(&mutex_);
  347. should_sleep_ = false;
  348. while (sleeping_) {
  349. assert(!should_sleep_);
  350. bg_cv_.SignalAll();
  351. bg_cv_.Wait();
  352. }
  353. }
  354. bool IsSleeping() {
  355. MutexLock l(&mutex_);
  356. return sleeping_;
  357. }
  358. void DoSleep() {
  359. MutexLock l(&mutex_);
  360. sleeping_ = true;
  361. bg_cv_.SignalAll();
  362. while (should_sleep_) {
  363. bg_cv_.Wait();
  364. }
  365. sleeping_ = false;
  366. done_with_sleep_ = true;
  367. bg_cv_.SignalAll();
  368. }
  369. void WaitUntilSleeping() {
  370. MutexLock l(&mutex_);
  371. while (!sleeping_ || !should_sleep_) {
  372. bg_cv_.Wait();
  373. }
  374. }
  375. // Waits for the status to change to sleeping,
  376. // otherwise times out.
  377. // wait_time is in microseconds.
  378. // Returns true when times out, false otherwise.
  379. bool TimedWaitUntilSleeping(uint64_t wait_time);
  380. void WakeUp() {
  381. MutexLock l(&mutex_);
  382. should_sleep_ = false;
  383. bg_cv_.SignalAll();
  384. }
  385. void WaitUntilDone() {
  386. MutexLock l(&mutex_);
  387. while (!done_with_sleep_) {
  388. bg_cv_.Wait();
  389. }
  390. }
  391. // Similar to TimedWaitUntilSleeping.
  392. // Waits until the task is done.
  393. bool TimedWaitUntilDone(uint64_t wait_time);
  394. bool WokenUp() {
  395. MutexLock l(&mutex_);
  396. return should_sleep_ == false;
  397. }
  398. void Reset() {
  399. MutexLock l(&mutex_);
  400. should_sleep_ = true;
  401. done_with_sleep_ = false;
  402. }
  403. static void DoSleepTask(void* arg) {
  404. static_cast<SleepingBackgroundTask*>(arg)->DoSleep();
  405. }
  406. private:
  407. port::Mutex mutex_;
  408. port::CondVar bg_cv_; // Signalled when background work finishes
  409. bool should_sleep_;
  410. bool done_with_sleep_;
  411. bool sleeping_;
  412. };
  413. // Filters merge operands and values that are equal to `num`.
  414. class FilterNumber : public CompactionFilter {
  415. public:
  416. explicit FilterNumber(uint64_t num) : num_(num) {}
  417. std::string last_merge_operand_key() { return last_merge_operand_key_; }
  418. bool Filter(int /*level*/, const ROCKSDB_NAMESPACE::Slice& /*key*/,
  419. const ROCKSDB_NAMESPACE::Slice& value, std::string* /*new_value*/,
  420. bool* /*value_changed*/) const override {
  421. if (value.size() == sizeof(uint64_t)) {
  422. return num_ == DecodeFixed64(value.data());
  423. }
  424. return true;
  425. }
  426. bool FilterMergeOperand(
  427. int /*level*/, const ROCKSDB_NAMESPACE::Slice& key,
  428. const ROCKSDB_NAMESPACE::Slice& value) const override {
  429. last_merge_operand_key_ = key.ToString();
  430. if (value.size() == sizeof(uint64_t)) {
  431. return num_ == DecodeFixed64(value.data());
  432. }
  433. return true;
  434. }
  435. const char* Name() const override { return "FilterBadMergeOperand"; }
  436. private:
  437. mutable std::string last_merge_operand_key_;
  438. uint64_t num_;
  439. };
  440. inline std::string EncodeInt(uint64_t x) {
  441. std::string result;
  442. PutFixed64(&result, x);
  443. return result;
  444. }
  445. class SeqStringSource : public FSSequentialFile {
  446. public:
  447. SeqStringSource(const std::string& data, std::atomic<int>* read_count)
  448. : data_(data), offset_(0), read_count_(read_count) {}
  449. ~SeqStringSource() override {}
  450. IOStatus Read(size_t n, const IOOptions& /*opts*/, Slice* result,
  451. char* scratch, IODebugContext* /*dbg*/) override {
  452. std::string output;
  453. if (offset_ < data_.size()) {
  454. n = std::min(data_.size() - offset_, n);
  455. memcpy(scratch, data_.data() + offset_, n);
  456. offset_ += n;
  457. *result = Slice(scratch, n);
  458. } else {
  459. return IOStatus::InvalidArgument(
  460. "Attempt to read when it already reached eof.");
  461. }
  462. (*read_count_)++;
  463. return IOStatus::OK();
  464. }
  465. IOStatus Skip(uint64_t n) override {
  466. if (offset_ >= data_.size()) {
  467. return IOStatus::InvalidArgument(
  468. "Attempt to read when it already reached eof.");
  469. }
  470. // TODO(yhchiang): Currently doesn't handle the overflow case.
  471. offset_ += static_cast<size_t>(n);
  472. return IOStatus::OK();
  473. }
  474. private:
  475. std::string data_;
  476. size_t offset_;
  477. std::atomic<int>* read_count_;
  478. };
  479. class StringFS : public FileSystemWrapper {
  480. public:
  481. class StringSink : public FSWritableFile {
  482. public:
  483. explicit StringSink(std::string* contents)
  484. : FSWritableFile(), contents_(contents) {}
  485. IOStatus Truncate(uint64_t size, const IOOptions& /*opts*/,
  486. IODebugContext* /*dbg*/) override {
  487. contents_->resize(static_cast<size_t>(size));
  488. return IOStatus::OK();
  489. }
  490. IOStatus Close(const IOOptions& /*opts*/,
  491. IODebugContext* /*dbg*/) override {
  492. return IOStatus::OK();
  493. }
  494. IOStatus Flush(const IOOptions& /*opts*/,
  495. IODebugContext* /*dbg*/) override {
  496. return IOStatus::OK();
  497. }
  498. IOStatus Sync(const IOOptions& /*opts*/, IODebugContext* /*dbg*/) override {
  499. return IOStatus::OK();
  500. }
  501. using FSWritableFile::Append;
  502. IOStatus Append(const Slice& slice, const IOOptions& /*opts*/,
  503. IODebugContext* /*dbg*/) override {
  504. contents_->append(slice.data(), slice.size());
  505. return IOStatus::OK();
  506. }
  507. uint64_t GetFileSize(const IOOptions& /*options*/,
  508. IODebugContext* /*dbg*/) override {
  509. if (contents_ != nullptr) {
  510. return contents_->size();
  511. }
  512. return 0;
  513. }
  514. private:
  515. std::string* contents_;
  516. };
  517. explicit StringFS(const std::shared_ptr<FileSystem>& t)
  518. : FileSystemWrapper(t) {}
  519. ~StringFS() override {}
  520. static const char* kClassName() { return "StringFS"; }
  521. const char* Name() const override { return kClassName(); }
  522. const std::string& GetContent(const std::string& f) { return files_[f]; }
  523. const IOStatus WriteToNewFile(const std::string& file_name,
  524. const std::string& content) {
  525. std::unique_ptr<FSWritableFile> r;
  526. FileOptions file_opts;
  527. IOOptions io_opts;
  528. auto s = NewWritableFile(file_name, file_opts, &r, nullptr);
  529. if (s.ok()) {
  530. s = r->Append(content, io_opts, nullptr);
  531. }
  532. if (s.ok()) {
  533. s = r->Flush(io_opts, nullptr);
  534. }
  535. if (s.ok()) {
  536. s = r->Close(io_opts, nullptr);
  537. }
  538. assert(!s.ok() || files_[file_name] == content);
  539. return s;
  540. }
  541. // The following text is boilerplate that forwards all methods to target()
  542. IOStatus NewSequentialFile(const std::string& f,
  543. const FileOptions& /*options*/,
  544. std::unique_ptr<FSSequentialFile>* r,
  545. IODebugContext* /*dbg*/) override {
  546. auto iter = files_.find(f);
  547. if (iter == files_.end()) {
  548. return IOStatus::NotFound("The specified file does not exist", f);
  549. }
  550. r->reset(new SeqStringSource(iter->second, &num_seq_file_read_));
  551. return IOStatus::OK();
  552. }
  553. IOStatus NewRandomAccessFile(const std::string& /*f*/,
  554. const FileOptions& /*options*/,
  555. std::unique_ptr<FSRandomAccessFile>* /*r*/,
  556. IODebugContext* /*dbg*/) override {
  557. return IOStatus::NotSupported();
  558. }
  559. IOStatus NewWritableFile(const std::string& f, const FileOptions& /*options*/,
  560. std::unique_ptr<FSWritableFile>* r,
  561. IODebugContext* /*dbg*/) override {
  562. auto iter = files_.find(f);
  563. if (iter != files_.end()) {
  564. return IOStatus::IOError("The specified file already exists", f);
  565. }
  566. r->reset(new StringSink(&files_[f]));
  567. return IOStatus::OK();
  568. }
  569. IOStatus NewDirectory(const std::string& /*name*/,
  570. const IOOptions& /*options*/,
  571. std::unique_ptr<FSDirectory>* /*result*/,
  572. IODebugContext* /*dbg*/) override {
  573. return IOStatus::NotSupported();
  574. }
  575. IOStatus FileExists(const std::string& f, const IOOptions& /*options*/,
  576. IODebugContext* /*dbg*/) override {
  577. if (files_.find(f) == files_.end()) {
  578. return IOStatus::NotFound();
  579. }
  580. return IOStatus::OK();
  581. }
  582. IOStatus GetChildren(const std::string& /*dir*/, const IOOptions& /*options*/,
  583. std::vector<std::string>* /*r*/,
  584. IODebugContext* /*dbg*/) override {
  585. return IOStatus::NotSupported();
  586. }
  587. IOStatus DeleteFile(const std::string& f, const IOOptions& /*options*/,
  588. IODebugContext* /*dbg*/) override {
  589. files_.erase(f);
  590. return IOStatus::OK();
  591. }
  592. IOStatus CreateDir(const std::string& /*d*/, const IOOptions& /*options*/,
  593. IODebugContext* /*dbg*/) override {
  594. return IOStatus::NotSupported();
  595. }
  596. IOStatus CreateDirIfMissing(const std::string& /*d*/,
  597. const IOOptions& /*options*/,
  598. IODebugContext* /*dbg*/) override {
  599. return IOStatus::NotSupported();
  600. }
  601. IOStatus DeleteDir(const std::string& /*d*/, const IOOptions& /*options*/,
  602. IODebugContext* /*dbg*/) override {
  603. return IOStatus::NotSupported();
  604. }
  605. IOStatus GetFileSize(const std::string& f, const IOOptions& /*options*/,
  606. uint64_t* s, IODebugContext* /*dbg*/) override {
  607. auto iter = files_.find(f);
  608. if (iter == files_.end()) {
  609. return IOStatus::NotFound("The specified file does not exist:", f);
  610. }
  611. *s = iter->second.size();
  612. return IOStatus::OK();
  613. }
  614. IOStatus GetFileModificationTime(const std::string& /*fname*/,
  615. const IOOptions& /*options*/,
  616. uint64_t* /*file_mtime*/,
  617. IODebugContext* /*dbg*/) override {
  618. return IOStatus::NotSupported();
  619. }
  620. IOStatus RenameFile(const std::string& /*s*/, const std::string& /*t*/,
  621. const IOOptions& /*options*/,
  622. IODebugContext* /*dbg*/) override {
  623. return IOStatus::NotSupported();
  624. }
  625. IOStatus LinkFile(const std::string& /*s*/, const std::string& /*t*/,
  626. const IOOptions& /*options*/,
  627. IODebugContext* /*dbg*/) override {
  628. return IOStatus::NotSupported();
  629. }
  630. IOStatus LockFile(const std::string& /*f*/, const IOOptions& /*options*/,
  631. FileLock** /*l*/, IODebugContext* /*dbg*/) override {
  632. return IOStatus::NotSupported();
  633. }
  634. IOStatus UnlockFile(FileLock* /*l*/, const IOOptions& /*options*/,
  635. IODebugContext* /*dbg*/) override {
  636. return IOStatus::NotSupported();
  637. }
  638. std::atomic<int> num_seq_file_read_;
  639. protected:
  640. std::unordered_map<std::string, std::string> files_;
  641. };
  642. // A compressor that essentially implements a custom compression algorithm
  643. // by leveraging an existing compression algorithm and putting a custom header
  644. // on it to detect any attempts to decompress it with the wrong compression
  645. // type or dictionary.
  646. template <CompressionType kCompression>
  647. struct CompressorCustomAlg : public CompressorWrapper {
  648. static bool Supported() { return LZ4_Supported(); }
  649. explicit CompressorCustomAlg(
  650. std::unique_ptr<Compressor> wrapped =
  651. GetBuiltinV2CompressionManager()->GetCompressor({}, kLZ4Compression))
  652. : CompressorWrapper(std::move(wrapped)),
  653. dictionary_hash_(GetSliceHash(wrapped_->GetSerializedDict())) {
  654. static_assert(kCompression > kLastBuiltinCompression);
  655. }
  656. const char* Name() const override { return "CompressorCustomAlg"; }
  657. CompressionType GetPreferredCompressionType() const override {
  658. return kCompression;
  659. }
  660. Status CompressBlock(Slice uncompressed_data, char* compressed_output,
  661. size_t* compressed_output_size,
  662. CompressionType* out_compression_type,
  663. ManagedWorkingArea* working_area) override {
  664. size_t allowed_output_size = *compressed_output_size;
  665. Status s = wrapped_->CompressBlock(uncompressed_data, compressed_output,
  666. compressed_output_size,
  667. out_compression_type, working_area);
  668. if (s.ok() && *out_compression_type != kNoCompression) {
  669. assert(*out_compression_type == kLZ4Compression);
  670. if (*compressed_output_size + 5 > allowed_output_size) {
  671. *out_compression_type = kNoCompression;
  672. return Status::OK();
  673. }
  674. // Generate & insert header
  675. std::memmove(compressed_output + 5, compressed_output,
  676. *compressed_output_size);
  677. compressed_output[0] = lossless_cast<char>(kCompression);
  678. EncodeFixed32(&compressed_output[1], dictionary_hash_);
  679. *compressed_output_size += 5;
  680. *out_compression_type = kCompression;
  681. }
  682. return s;
  683. }
  684. std::unique_ptr<Compressor> MaybeCloneSpecialized(
  685. CacheEntryRole block_type, DictSampleArgs&& dict_samples) override {
  686. auto clone =
  687. wrapped_->MaybeCloneSpecialized(block_type, std::move(dict_samples));
  688. return std::make_unique<CompressorCustomAlg>(std::move(clone));
  689. }
  690. protected:
  691. uint32_t dictionary_hash_;
  692. };
  693. // A decompressor suitable for all the instantiable CompressorCustomAlg
  694. // implementations. Can be configured to check that it is only used to
  695. // decompress certain types using SetAllowedTypes().
  696. struct DecompressorCustomAlg : public DecompressorWrapper {
  697. using TypeSet = SmallEnumSet<CompressionType, kDisableCompressionOption>;
  698. DecompressorCustomAlg(std::shared_ptr<Decompressor> wrapped =
  699. GetBuiltinV2CompressionManager()->GetDecompressor())
  700. : DecompressorWrapper(std::move(wrapped)),
  701. dictionary_hash_(GetSliceHash(wrapped_->GetSerializedDict())),
  702. allowed_types_(TypeSet::All()) {}
  703. const char* Name() const override { return "DecompressorCustomAlg"; }
  704. Status MaybeCloneForDict(const Slice& serialized_dict,
  705. std::unique_ptr<Decompressor>* out) override {
  706. Status s = wrapped_->MaybeCloneForDict(serialized_dict, out);
  707. if (s.ok()) {
  708. assert(*out != nullptr);
  709. auto clone = std::make_unique<DecompressorCustomAlg>(std::move(*out));
  710. clone->SetAllowedTypes(allowed_types_);
  711. *out = std::move(clone);
  712. assert(out->get()->GetSerializedDict() == serialized_dict);
  713. } else {
  714. assert(*out == nullptr);
  715. }
  716. return s;
  717. }
  718. Status ExtractUncompressedSize(Args& args) override {
  719. if (args.compression_type >= kFirstCustomCompression &&
  720. args.compression_type <= kLastCustomCompression) {
  721. assert(args.compressed_data.size() > 0);
  722. assert(args.compressed_data[0] ==
  723. lossless_cast<char>(args.compression_type));
  724. assert(DecodeFixed32(args.compressed_data.data() + 1) ==
  725. dictionary_hash_);
  726. // Strip off our header because ExtractUncompressedSize() is also going
  727. // to strip off the uncompressed size data.
  728. args.compressed_data.remove_prefix(5);
  729. // It's ok to modify other parts of args if we restore to original
  730. SaveAndRestore<CompressionType> save_compression_type(
  731. &args.compression_type, kLZ4Compression);
  732. return wrapped_->ExtractUncompressedSize(args);
  733. } else {
  734. // Also support built-in compressions
  735. return wrapped_->ExtractUncompressedSize(args);
  736. }
  737. }
  738. Status DecompressBlock(const Args& args, char* uncompressed_output) override {
  739. if (args.compression_type >= kFirstCustomCompression &&
  740. args.compression_type <= kLastCustomCompression) {
  741. // Also allowed to copy args and modify
  742. Args modified_args = args;
  743. modified_args.compression_type = kLZ4Compression;
  744. return wrapped_->DecompressBlock(modified_args, uncompressed_output);
  745. } else {
  746. // Also support built-in compressions
  747. return wrapped_->DecompressBlock(args, uncompressed_output);
  748. }
  749. }
  750. void SetAllowedTypes(const CompressionType* types_begin,
  751. const CompressionType* types_end) {
  752. TypeSet allowed_types;
  753. for (auto type = types_begin; type != types_end; ++type) {
  754. allowed_types.Add(*type);
  755. }
  756. allowed_types_ = std::move(allowed_types);
  757. }
  758. void SetAllowedTypes(TypeSet allowed_types) {
  759. allowed_types_ = std::move(allowed_types);
  760. }
  761. protected:
  762. uint32_t dictionary_hash_;
  763. SmallEnumSet<CompressionType, kDisableCompressionOption> allowed_types_;
  764. };
  765. // Randomly initialize the given DBOptions
  766. void RandomInitDBOptions(DBOptions* db_opt, Random* rnd);
  767. // Randomly initialize the given ColumnFamilyOptions
  768. // Note that the caller is responsible for releasing non-null
  769. // cf_opt->compaction_filter.
  770. void RandomInitCFOptions(ColumnFamilyOptions* cf_opt, DBOptions&, Random* rnd);
  771. // A dummy merge operator which can change its name
  772. class ChanglingMergeOperator : public MergeOperator {
  773. public:
  774. explicit ChanglingMergeOperator(const std::string& name)
  775. : name_(name + "MergeOperator") {}
  776. ~ChanglingMergeOperator() {}
  777. void SetName(const std::string& name) { name_ = name; }
  778. bool FullMergeV2(const MergeOperationInput& /*merge_in*/,
  779. MergeOperationOutput* /*merge_out*/) const override {
  780. return false;
  781. }
  782. bool PartialMergeMulti(const Slice& /*key*/,
  783. const std::deque<Slice>& /*operand_list*/,
  784. std::string* /*new_value*/,
  785. Logger* /*logger*/) const override {
  786. return false;
  787. }
  788. static const char* kClassName() { return "ChanglingMergeOperator"; }
  789. const char* NickName() const override { return kNickName(); }
  790. static const char* kNickName() { return "Changling"; }
  791. bool IsInstanceOf(const std::string& id) const override {
  792. if (id == kClassName()) {
  793. return true;
  794. } else {
  795. return MergeOperator::IsInstanceOf(id);
  796. }
  797. }
  798. const char* Name() const override { return name_.c_str(); }
  799. protected:
  800. std::string name_;
  801. };
  802. // Returns a dummy merge operator with random name.
  803. MergeOperator* RandomMergeOperator(Random* rnd);
  804. // A dummy compaction filter which can change its name
  805. class ChanglingCompactionFilter : public CompactionFilter {
  806. public:
  807. explicit ChanglingCompactionFilter(const std::string& name)
  808. : name_(name + "CompactionFilter") {}
  809. ~ChanglingCompactionFilter() {}
  810. void SetName(const std::string& name) { name_ = name; }
  811. bool Filter(int /*level*/, const Slice& /*key*/,
  812. const Slice& /*existing_value*/, std::string* /*new_value*/,
  813. bool* /*value_changed*/) const override {
  814. return false;
  815. }
  816. static const char* kClassName() { return "ChanglingCompactionFilter"; }
  817. const char* NickName() const override { return kNickName(); }
  818. static const char* kNickName() { return "Changling"; }
  819. bool IsInstanceOf(const std::string& id) const override {
  820. if (id == kClassName()) {
  821. return true;
  822. } else {
  823. return CompactionFilter::IsInstanceOf(id);
  824. }
  825. }
  826. const char* Name() const override { return name_.c_str(); }
  827. private:
  828. std::string name_;
  829. };
  830. // Returns a dummy compaction filter with a random name.
  831. CompactionFilter* RandomCompactionFilter(Random* rnd);
  832. // A dummy compaction filter factory which can change its name
  833. class ChanglingCompactionFilterFactory : public CompactionFilterFactory {
  834. public:
  835. explicit ChanglingCompactionFilterFactory(const std::string& name)
  836. : name_(name + "CompactionFilterFactory") {}
  837. ~ChanglingCompactionFilterFactory() {}
  838. void SetName(const std::string& name) { name_ = name; }
  839. std::unique_ptr<CompactionFilter> CreateCompactionFilter(
  840. const CompactionFilter::Context& /*context*/) override {
  841. return std::unique_ptr<CompactionFilter>();
  842. }
  843. // Returns a name that identifies this compaction filter factory.
  844. const char* Name() const override { return name_.c_str(); }
  845. static const char* kClassName() { return "ChanglingCompactionFilterFactory"; }
  846. const char* NickName() const override { return kNickName(); }
  847. static const char* kNickName() { return "Changling"; }
  848. bool IsInstanceOf(const std::string& id) const override {
  849. if (id == kClassName()) {
  850. return true;
  851. } else {
  852. return CompactionFilterFactory::IsInstanceOf(id);
  853. }
  854. }
  855. protected:
  856. std::string name_;
  857. };
  858. // The factory for the hacky skip list mem table that triggers flush after
  859. // number of entries exceeds a threshold.
  860. MemTableRepFactory* NewSpecialSkipListFactory(int num_entries_per_flush);
  861. CompressionType RandomCompressionType(Random* rnd);
  862. void RandomCompressionTypeVector(const size_t count,
  863. std::vector<CompressionType>* types,
  864. Random* rnd);
  865. CompactionFilterFactory* RandomCompactionFilterFactory(Random* rnd);
  866. const SliceTransform* RandomSliceTransform(Random* rnd, int pre_defined = -1);
  867. TableFactory* RandomTableFactory(Random* rnd, int pre_defined = -1);
  868. std::string RandomName(Random* rnd, const size_t len);
  869. bool IsDirectIOSupported(Env* env, const std::string& dir);
  870. bool IsPrefetchSupported(const std::shared_ptr<FileSystem>& fs,
  871. const std::string& dir);
  872. // Return the number of lines where a given pattern was found in a file.
  873. size_t GetLinesCount(const std::string& fname, const std::string& pattern);
  874. Status CorruptFile(Env* env, const std::string& fname, int offset,
  875. int bytes_to_corrupt, bool verify_checksum = true);
  876. Status TruncateFile(Env* env, const std::string& fname, uint64_t length);
  877. // Try and delete a directory if it exists
  878. Status TryDeleteDir(Env* env, const std::string& dirname);
  879. // Delete a directory if it exists
  880. void DeleteDir(Env* env, const std::string& dirname);
  881. // Find the FileType from the file path
  882. FileType GetFileType(const std::string& path);
  883. // Get the file number given the file path
  884. uint64_t GetFileNumber(const std::string& path);
  885. // Creates an Env from the system environment by looking at the system
  886. // environment variables.
  887. Status CreateEnvFromSystem(const ConfigOptions& options, Env** result,
  888. std::shared_ptr<Env>* guard);
  889. // Registers the testutil classes with the ObjectLibrary
  890. int RegisterTestObjects(ObjectLibrary& library, const std::string& /*arg*/);
  891. // Register the testutil classes with the default ObjectRegistry/Library
  892. void RegisterTestLibrary(const std::string& arg = "");
  893. struct ReadOptionsNoIo : public ReadOptions {
  894. ReadOptionsNoIo() { read_tier = ReadTier::kBlockCacheTier; }
  895. };
  896. extern const ReadOptionsNoIo kReadOptionsNoIo;
  897. extern const std::string kUnitTestDbId;
  898. } // namespace test
  899. } // namespace ROCKSDB_NAMESPACE