db_secondary_test.cc 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837
  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. #include "db/db_impl/db_impl_secondary.h"
  10. #include "db/db_test_util.h"
  11. #include "db/db_with_timestamp_test_util.h"
  12. #include "port/stack_trace.h"
  13. #include "rocksdb/utilities/transaction_db.h"
  14. #include "test_util/sync_point.h"
  15. #include "test_util/testutil.h"
  16. #include "utilities/merge_operators/string_append/stringappend2.h"
  17. namespace ROCKSDB_NAMESPACE {
  18. class DBSecondaryTestBase : public DBBasicTestWithTimestampBase {
  19. public:
  20. explicit DBSecondaryTestBase(const std::string& dbname)
  21. : DBBasicTestWithTimestampBase(dbname),
  22. secondary_path_(),
  23. handles_secondary_(),
  24. db_secondary_(nullptr) {
  25. secondary_path_ =
  26. test::PerThreadDBPath(env_, "/db_secondary_test_secondary");
  27. }
  28. ~DBSecondaryTestBase() override {
  29. CloseSecondary();
  30. if (getenv("KEEP_DB") != nullptr) {
  31. fprintf(stdout, "Secondary DB is still at %s\n", secondary_path_.c_str());
  32. } else {
  33. Options options;
  34. options.env = env_;
  35. EXPECT_OK(DestroyDB(secondary_path_, options));
  36. }
  37. }
  38. protected:
  39. Status ReopenAsSecondary(const Options& options) {
  40. return DB::OpenAsSecondary(options, dbname_, secondary_path_, &db_);
  41. }
  42. void OpenSecondary(const Options& options);
  43. Status TryOpenSecondary(const Options& options);
  44. void OpenSecondaryWithColumnFamilies(
  45. const std::vector<std::string>& column_families, const Options& options);
  46. void CloseSecondary() {
  47. for (auto h : handles_secondary_) {
  48. ASSERT_OK(db_secondary_->DestroyColumnFamilyHandle(h));
  49. }
  50. handles_secondary_.clear();
  51. delete db_secondary_;
  52. db_secondary_ = nullptr;
  53. }
  54. DBImplSecondary* db_secondary_full() {
  55. return static_cast<DBImplSecondary*>(db_secondary_);
  56. }
  57. void CheckFileTypeCounts(const std::string& dir, int expected_log,
  58. int expected_sst, int expected_manifest) const;
  59. std::string secondary_path_;
  60. std::vector<ColumnFamilyHandle*> handles_secondary_;
  61. DB* db_secondary_;
  62. };
  63. void DBSecondaryTestBase::OpenSecondary(const Options& options) {
  64. ASSERT_OK(TryOpenSecondary(options));
  65. }
  66. Status DBSecondaryTestBase::TryOpenSecondary(const Options& options) {
  67. Status s =
  68. DB::OpenAsSecondary(options, dbname_, secondary_path_, &db_secondary_);
  69. return s;
  70. }
  71. void DBSecondaryTestBase::OpenSecondaryWithColumnFamilies(
  72. const std::vector<std::string>& column_families, const Options& options) {
  73. std::vector<ColumnFamilyDescriptor> cf_descs;
  74. cf_descs.emplace_back(kDefaultColumnFamilyName, options);
  75. for (const auto& cf_name : column_families) {
  76. cf_descs.emplace_back(cf_name, options);
  77. }
  78. Status s = DB::OpenAsSecondary(options, dbname_, secondary_path_, cf_descs,
  79. &handles_secondary_, &db_secondary_);
  80. ASSERT_OK(s);
  81. }
  82. void DBSecondaryTestBase::CheckFileTypeCounts(const std::string& dir,
  83. int expected_log,
  84. int expected_sst,
  85. int expected_manifest) const {
  86. std::vector<std::string> filenames;
  87. ASSERT_OK(env_->GetChildren(dir, &filenames));
  88. int log_cnt = 0, sst_cnt = 0, manifest_cnt = 0;
  89. for (const auto& file : filenames) {
  90. uint64_t number;
  91. FileType type;
  92. if (ParseFileName(file, &number, &type)) {
  93. log_cnt += (type == kWalFile);
  94. sst_cnt += (type == kTableFile);
  95. manifest_cnt += (type == kDescriptorFile);
  96. }
  97. }
  98. ASSERT_EQ(expected_log, log_cnt);
  99. ASSERT_EQ(expected_sst, sst_cnt);
  100. ASSERT_EQ(expected_manifest, manifest_cnt);
  101. }
  102. class DBSecondaryTest : public DBSecondaryTestBase {
  103. public:
  104. explicit DBSecondaryTest() : DBSecondaryTestBase("db_secondary_test") {}
  105. };
  106. TEST_F(DBSecondaryTest, FailOpenIfLoggerCreationFail) {
  107. Options options = GetDefaultOptions();
  108. options.create_if_missing = true;
  109. Reopen(options);
  110. SyncPoint::GetInstance()->DisableProcessing();
  111. SyncPoint::GetInstance()->ClearAllCallBacks();
  112. SyncPoint::GetInstance()->SetCallBack(
  113. "rocksdb::CreateLoggerFromOptions:AfterGetPath", [&](void* arg) {
  114. auto* s = static_cast<Status*>(arg);
  115. assert(s);
  116. *s = Status::IOError("Injected");
  117. });
  118. SyncPoint::GetInstance()->EnableProcessing();
  119. options.max_open_files = -1;
  120. Status s = TryOpenSecondary(options);
  121. ASSERT_EQ(nullptr, options.info_log);
  122. ASSERT_TRUE(s.IsIOError());
  123. SyncPoint::GetInstance()->DisableProcessing();
  124. SyncPoint::GetInstance()->ClearAllCallBacks();
  125. }
  126. TEST_F(DBSecondaryTest, NonExistingDb) {
  127. Destroy(last_options_);
  128. Options options = GetDefaultOptions();
  129. options.env = env_;
  130. options.max_open_files = -1;
  131. const std::string dbname = "/doesnt/exist";
  132. Status s =
  133. DB::OpenAsSecondary(options, dbname, secondary_path_, &db_secondary_);
  134. ASSERT_TRUE(s.IsIOError());
  135. }
  136. TEST_F(DBSecondaryTest, ReopenAsSecondary) {
  137. Options options;
  138. options.env = env_;
  139. options.preserve_internal_time_seconds = 300;
  140. Reopen(options);
  141. ASSERT_OK(Put("foo", "foo_value"));
  142. ASSERT_OK(Put("bar", "bar_value"));
  143. WideColumns columns{{kDefaultWideColumnName, "attr_default_val"},
  144. {"attr_name1", "attr_value_1"},
  145. {"attr_name2", "attr_value_2"}};
  146. ASSERT_OK(db_->PutEntity(WriteOptions(), db_->DefaultColumnFamily(), "baz",
  147. columns));
  148. ASSERT_OK(dbfull()->Flush(FlushOptions()));
  149. Close();
  150. ASSERT_OK(ReopenAsSecondary(options));
  151. ASSERT_EQ("foo_value", Get("foo"));
  152. ASSERT_EQ("bar_value", Get("bar"));
  153. PinnableWideColumns result;
  154. ASSERT_OK(db_->GetEntity(ReadOptions(), db_->DefaultColumnFamily(), "baz",
  155. &result));
  156. ASSERT_EQ(result.columns(), columns);
  157. ReadOptions ropts;
  158. ropts.verify_checksums = true;
  159. auto db1 = static_cast<DBImplSecondary*>(db_);
  160. ASSERT_NE(nullptr, db1);
  161. Iterator* iter = db1->NewIterator(ropts);
  162. ASSERT_NE(nullptr, iter);
  163. size_t count = 0;
  164. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  165. if (0 == count) {
  166. ASSERT_EQ("bar", iter->key().ToString());
  167. ASSERT_EQ("bar_value", iter->value().ToString());
  168. } else if (1 == count) {
  169. ASSERT_EQ("baz", iter->key().ToString());
  170. ASSERT_EQ(columns, iter->columns());
  171. } else if (2 == count) {
  172. ASSERT_EQ("foo", iter->key().ToString());
  173. ASSERT_EQ("foo_value", iter->value().ToString());
  174. }
  175. ++count;
  176. }
  177. ASSERT_OK(iter->status());
  178. delete iter;
  179. ASSERT_EQ(3, count);
  180. }
  181. TEST_F(DBSecondaryTest, SimpleInternalCompaction) {
  182. Options options;
  183. options.env = env_;
  184. Reopen(options);
  185. for (int i = 0; i < 3; ++i) {
  186. ASSERT_OK(Put("foo", "foo_value" + std::to_string(i)));
  187. ASSERT_OK(Put("bar", "bar_value" + std::to_string(i)));
  188. ASSERT_OK(Flush());
  189. }
  190. CompactionServiceInput input;
  191. ColumnFamilyMetaData meta;
  192. db_->GetColumnFamilyMetaData(&meta);
  193. for (auto& file : meta.levels[0].files) {
  194. ASSERT_EQ(0, meta.levels[0].level);
  195. input.input_files.push_back(file.name);
  196. }
  197. ASSERT_EQ(input.input_files.size(), 3);
  198. input.output_level = 1;
  199. ASSERT_OK(db_->GetDbIdentity(input.db_id));
  200. Close();
  201. options.max_open_files = -1;
  202. OpenSecondary(options);
  203. auto cfh = db_secondary_->DefaultColumnFamily();
  204. CompactionServiceResult result;
  205. ASSERT_OK(db_secondary_full()->TEST_CompactWithoutInstallation(
  206. OpenAndCompactOptions(), cfh, input, &result));
  207. ASSERT_EQ(result.output_files.size(), 1);
  208. InternalKey smallest, largest;
  209. smallest.DecodeFrom(result.output_files[0].smallest_internal_key);
  210. largest.DecodeFrom(result.output_files[0].largest_internal_key);
  211. ASSERT_EQ(smallest.user_key().ToString(), "bar");
  212. ASSERT_EQ(largest.user_key().ToString(), "foo");
  213. ASSERT_EQ(result.output_level, 1);
  214. ASSERT_EQ(result.output_path, this->secondary_path_);
  215. ASSERT_EQ(result.stats.num_output_records, 2);
  216. ASSERT_GT(result.bytes_written, 0);
  217. ASSERT_OK(result.status);
  218. }
  219. TEST_F(DBSecondaryTest, InternalCompactionMultiLevels) {
  220. Options options;
  221. options.env = env_;
  222. options.disable_auto_compactions = true;
  223. Reopen(options);
  224. const int kRangeL2 = 10;
  225. const int kRangeL1 = 30;
  226. for (int i = 0; i < 10; i++) {
  227. ASSERT_OK(Put(Key(i * kRangeL2), "value" + std::to_string(i)));
  228. ASSERT_OK(Put(Key((i + 1) * kRangeL2 - 1), "value" + std::to_string(i)));
  229. ASSERT_OK(Flush());
  230. }
  231. MoveFilesToLevel(2);
  232. for (int i = 0; i < 5; i++) {
  233. ASSERT_OK(Put(Key(i * kRangeL1), "value" + std::to_string(i)));
  234. ASSERT_OK(Put(Key((i + 1) * kRangeL1 - 1), "value" + std::to_string(i)));
  235. ASSERT_OK(Flush());
  236. }
  237. MoveFilesToLevel(1);
  238. for (int i = 0; i < 4; i++) {
  239. ASSERT_OK(Put(Key(i * 30), "value" + std::to_string(i)));
  240. ASSERT_OK(Put(Key(i * 30 + 50), "value" + std::to_string(i)));
  241. ASSERT_OK(Flush());
  242. }
  243. ColumnFamilyMetaData meta;
  244. db_->GetColumnFamilyMetaData(&meta);
  245. // pick 2 files on level 0 for compaction, which has 3 overlap files on L1
  246. CompactionServiceInput input1;
  247. input1.input_files.push_back(meta.levels[0].files[2].name);
  248. input1.input_files.push_back(meta.levels[0].files[3].name);
  249. input1.input_files.push_back(meta.levels[1].files[0].name);
  250. input1.input_files.push_back(meta.levels[1].files[1].name);
  251. input1.input_files.push_back(meta.levels[1].files[2].name);
  252. input1.output_level = 1;
  253. ASSERT_OK(db_->GetDbIdentity(input1.db_id));
  254. options.max_open_files = -1;
  255. Close();
  256. OpenSecondary(options);
  257. auto cfh = db_secondary_->DefaultColumnFamily();
  258. CompactionServiceResult result;
  259. ASSERT_OK(db_secondary_full()->TEST_CompactWithoutInstallation(
  260. OpenAndCompactOptions(), cfh, input1, &result));
  261. ASSERT_OK(result.status);
  262. // pick 2 files on level 1 for compaction, which has 6 overlap files on L2
  263. CompactionServiceInput input2;
  264. input2.input_files.push_back(meta.levels[1].files[1].name);
  265. input2.input_files.push_back(meta.levels[1].files[2].name);
  266. for (int i = 3; i < 9; i++) {
  267. input2.input_files.push_back(meta.levels[2].files[i].name);
  268. }
  269. input2.output_level = 2;
  270. input2.db_id = input1.db_id;
  271. ASSERT_OK(db_secondary_full()->TEST_CompactWithoutInstallation(
  272. OpenAndCompactOptions(), cfh, input2, &result));
  273. ASSERT_OK(result.status);
  274. CloseSecondary();
  275. // delete all l2 files, without update manifest
  276. for (auto& file : meta.levels[2].files) {
  277. ASSERT_OK(env_->DeleteFile(dbname_ + file.name));
  278. }
  279. OpenSecondary(options);
  280. cfh = db_secondary_->DefaultColumnFamily();
  281. Status s = db_secondary_full()->TEST_CompactWithoutInstallation(
  282. OpenAndCompactOptions(), cfh, input2, &result);
  283. ASSERT_TRUE(s.IsInvalidArgument());
  284. ASSERT_OK(result.status);
  285. // TODO: L0 -> L1 compaction should success, currently version is not built
  286. // if files is missing.
  287. // ASSERT_OK(db_secondary_full()->TEST_CompactWithoutInstallation(OpenAndCompactOptions(),
  288. // cfh, input1, &result));
  289. }
  290. TEST_F(DBSecondaryTest, GetMergeOperands) {
  291. Options options;
  292. options.merge_operator = MergeOperators::CreateStringAppendOperator();
  293. options.env = env_;
  294. Reopen(options);
  295. ASSERT_OK(Merge("k1", "v1"));
  296. ASSERT_OK(Merge("k1", "v2"));
  297. ASSERT_OK(Merge("k1", "v3"));
  298. ASSERT_OK(Merge("k1", "v4"));
  299. options.max_open_files = -1;
  300. OpenSecondary(options);
  301. ASSERT_OK(db_secondary_->TryCatchUpWithPrimary());
  302. int num_records = 4;
  303. int number_of_operands = 0;
  304. std::vector<PinnableSlice> values(num_records);
  305. GetMergeOperandsOptions merge_operands_info;
  306. merge_operands_info.expected_max_number_of_operands = num_records;
  307. auto cfh = db_secondary_->DefaultColumnFamily();
  308. const Status s = db_secondary_->GetMergeOperands(
  309. ReadOptions(), cfh, "k1", values.data(), &merge_operands_info,
  310. &number_of_operands);
  311. ASSERT_NOK(s);
  312. ASSERT_TRUE(s.IsMergeInProgress());
  313. ASSERT_EQ(number_of_operands, 4);
  314. ASSERT_EQ(values[0].ToString(), "v1");
  315. ASSERT_EQ(values[1].ToString(), "v2");
  316. ASSERT_EQ(values[2].ToString(), "v3");
  317. ASSERT_EQ(values[3].ToString(), "v4");
  318. }
  319. TEST_F(DBSecondaryTest, InternalCompactionCompactedFiles) {
  320. Options options;
  321. options.env = env_;
  322. options.level0_file_num_compaction_trigger = 4;
  323. Reopen(options);
  324. for (int i = 0; i < 3; ++i) {
  325. ASSERT_OK(Put("foo", "foo_value" + std::to_string(i)));
  326. ASSERT_OK(Put("bar", "bar_value" + std::to_string(i)));
  327. ASSERT_OK(Flush());
  328. }
  329. CompactionServiceInput input;
  330. ColumnFamilyMetaData meta;
  331. db_->GetColumnFamilyMetaData(&meta);
  332. for (auto& file : meta.levels[0].files) {
  333. ASSERT_EQ(0, meta.levels[0].level);
  334. input.input_files.push_back(file.name);
  335. }
  336. ASSERT_EQ(input.input_files.size(), 3);
  337. input.output_level = 1;
  338. ASSERT_OK(db_->GetDbIdentity(input.db_id));
  339. // trigger compaction to delete the files for secondary instance compaction
  340. ASSERT_OK(Put("foo", "foo_value" + std::to_string(3)));
  341. ASSERT_OK(Put("bar", "bar_value" + std::to_string(3)));
  342. ASSERT_OK(Flush());
  343. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  344. Close();
  345. options.max_open_files = -1;
  346. OpenSecondary(options);
  347. auto cfh = db_secondary_->DefaultColumnFamily();
  348. CompactionServiceResult result;
  349. Status s = db_secondary_full()->TEST_CompactWithoutInstallation(
  350. OpenAndCompactOptions(), cfh, input, &result);
  351. ASSERT_TRUE(s.IsInvalidArgument());
  352. ASSERT_OK(result.status);
  353. }
  354. TEST_F(DBSecondaryTest, InternalCompactionMissingFiles) {
  355. Options options;
  356. options.env = env_;
  357. options.level0_file_num_compaction_trigger = 4;
  358. Reopen(options);
  359. for (int i = 0; i < 3; ++i) {
  360. ASSERT_OK(Put("foo", "foo_value" + std::to_string(i)));
  361. ASSERT_OK(Put("bar", "bar_value" + std::to_string(i)));
  362. ASSERT_OK(Flush());
  363. }
  364. CompactionServiceInput input;
  365. ColumnFamilyMetaData meta;
  366. db_->GetColumnFamilyMetaData(&meta);
  367. for (auto& file : meta.levels[0].files) {
  368. ASSERT_EQ(0, meta.levels[0].level);
  369. input.input_files.push_back(file.name);
  370. }
  371. ASSERT_EQ(input.input_files.size(), 3);
  372. input.output_level = 1;
  373. ASSERT_OK(db_->GetDbIdentity(input.db_id));
  374. Close();
  375. ASSERT_OK(env_->DeleteFile(dbname_ + input.input_files[0]));
  376. options.max_open_files = -1;
  377. OpenSecondary(options);
  378. auto cfh = db_secondary_->DefaultColumnFamily();
  379. CompactionServiceResult result;
  380. Status s = db_secondary_full()->TEST_CompactWithoutInstallation(
  381. OpenAndCompactOptions(), cfh, input, &result);
  382. ASSERT_TRUE(s.IsInvalidArgument());
  383. ASSERT_OK(result.status);
  384. input.input_files.erase(input.input_files.begin());
  385. ASSERT_OK(db_secondary_full()->TEST_CompactWithoutInstallation(
  386. OpenAndCompactOptions(), cfh, input, &result));
  387. ASSERT_OK(result.status);
  388. }
  389. TEST_F(DBSecondaryTest, OpenAsSecondary) {
  390. Options options;
  391. options.env = env_;
  392. options.level0_file_num_compaction_trigger = 4;
  393. Reopen(options);
  394. for (int i = 0; i < 3; ++i) {
  395. ASSERT_OK(Put("foo", "foo_value" + std::to_string(i)));
  396. ASSERT_OK(Put("bar", "bar_value" + std::to_string(i)));
  397. ASSERT_OK(Flush());
  398. }
  399. Options options1;
  400. options1.env = env_;
  401. options1.max_open_files = -1;
  402. OpenSecondary(options1);
  403. ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  404. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  405. ReadOptions ropts;
  406. ropts.verify_checksums = true;
  407. const auto verify_db_func = [&](const std::string& foo_val,
  408. const std::string& bar_val) {
  409. std::string value;
  410. ASSERT_OK(db_secondary_->Get(ropts, "foo", &value));
  411. ASSERT_EQ(foo_val, value);
  412. ASSERT_OK(db_secondary_->Get(ropts, "bar", &value));
  413. ASSERT_EQ(bar_val, value);
  414. Iterator* iter = db_secondary_->NewIterator(ropts);
  415. ASSERT_NE(nullptr, iter);
  416. iter->Seek("foo");
  417. ASSERT_TRUE(iter->Valid());
  418. ASSERT_EQ("foo", iter->key().ToString());
  419. ASSERT_EQ(foo_val, iter->value().ToString());
  420. iter->Seek("bar");
  421. ASSERT_TRUE(iter->Valid());
  422. ASSERT_EQ("bar", iter->key().ToString());
  423. ASSERT_EQ(bar_val, iter->value().ToString());
  424. size_t count = 0;
  425. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  426. ++count;
  427. }
  428. ASSERT_EQ(2, count);
  429. delete iter;
  430. };
  431. verify_db_func("foo_value2", "bar_value2");
  432. ASSERT_OK(Put("foo", "new_foo_value"));
  433. ASSERT_OK(Put("bar", "new_bar_value"));
  434. ASSERT_OK(Flush());
  435. ASSERT_OK(db_secondary_->TryCatchUpWithPrimary());
  436. verify_db_func("new_foo_value", "new_bar_value");
  437. }
  438. TEST_F(DBSecondaryTest, OptionsOverrideTest) {
  439. Options options;
  440. options.env = env_;
  441. options.preserve_internal_time_seconds = 300;
  442. options.compaction_readahead_size = 200;
  443. options.blob_compaction_readahead_size = 100;
  444. Reopen(options);
  445. for (int i = 0; i < 3; ++i) {
  446. ASSERT_OK(Put("foo", "foo_value" + std::to_string(i)));
  447. ASSERT_OK(Put("bar", "bar_value" + std::to_string(i)));
  448. ASSERT_OK(Flush());
  449. }
  450. CompactionServiceInput input;
  451. ColumnFamilyMetaData meta;
  452. db_->GetColumnFamilyMetaData(&meta);
  453. for (auto& file : meta.levels[0].files) {
  454. ASSERT_EQ(0, meta.levels[0].level);
  455. input.input_files.push_back(file.name);
  456. }
  457. ASSERT_EQ(input.input_files.size(), 3);
  458. input.output_level = 1;
  459. input.options_file_number = dbfull()->GetVersionSet()->options_file_number();
  460. input.cf_name = kDefaultColumnFamilyName;
  461. ASSERT_OK(db_->GetDbIdentity(input.db_id));
  462. ASSERT_EQ(db_->GetOptions().compaction_readahead_size, 200);
  463. ASSERT_EQ(db_->GetOptions().blob_compaction_readahead_size, 100);
  464. Close();
  465. std::string compaction_input_binary;
  466. ASSERT_OK(input.Write(&compaction_input_binary));
  467. std::string compaction_result_binary;
  468. CompactionServiceOptionsOverride override_options;
  469. override_options.env = env_;
  470. override_options.table_factory.reset(
  471. NewBlockBasedTableFactory(BlockBasedTableOptions()));
  472. ASSERT_OK(
  473. StringToMap("compaction_readahead_size=8388608;"
  474. "blob_compaction_readahead_size=4194304;"
  475. "some_invalid_option=ignore_me;"
  476. "env=this_should_not_fail;"
  477. "max_open_files=100;", // this should be always overriden as
  478. // -1 in remote compaction
  479. &override_options.options_map));
  480. bool verified = false;
  481. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  482. "DBImplSecondary::OpenAndCompact::AfterOpenAsSecondary:0",
  483. [&](void* arg) {
  484. auto secondary_db = static_cast<DB*>(arg);
  485. auto secondary_db_options = secondary_db->GetOptions();
  486. // DBOption
  487. ASSERT_EQ(secondary_db_options.compaction_readahead_size, 8388608);
  488. ASSERT_EQ(secondary_db_options.max_open_files, -1);
  489. // CFOption
  490. ASSERT_EQ(secondary_db_options.blob_compaction_readahead_size, 4194304);
  491. verified = true;
  492. });
  493. SyncPoint::GetInstance()->EnableProcessing();
  494. ASSERT_OK(DB::OpenAndCompact(OpenAndCompactOptions(), dbname_,
  495. secondary_path_, compaction_input_binary,
  496. &compaction_result_binary, override_options));
  497. SyncPoint::GetInstance()->DisableProcessing();
  498. SyncPoint::GetInstance()->ClearAllCallBacks();
  499. ASSERT_TRUE(verified);
  500. }
  501. namespace {
  502. class TraceFileEnv : public EnvWrapper {
  503. public:
  504. explicit TraceFileEnv(Env* _target) : EnvWrapper(_target) {}
  505. static const char* kClassName() { return "TraceFileEnv"; }
  506. const char* Name() const override { return kClassName(); }
  507. Status NewRandomAccessFile(const std::string& f,
  508. std::unique_ptr<RandomAccessFile>* r,
  509. const EnvOptions& env_options) override {
  510. class TracedRandomAccessFile : public RandomAccessFile {
  511. public:
  512. TracedRandomAccessFile(std::unique_ptr<RandomAccessFile>&& target,
  513. std::atomic<int>& counter)
  514. : target_(std::move(target)), files_closed_(counter) {}
  515. ~TracedRandomAccessFile() override {
  516. files_closed_.fetch_add(1, std::memory_order_relaxed);
  517. }
  518. Status Read(uint64_t offset, size_t n, Slice* result,
  519. char* scratch) const override {
  520. return target_->Read(offset, n, result, scratch);
  521. }
  522. Status GetFileSize(uint64_t* file_size) override {
  523. return target_->GetFileSize(file_size);
  524. }
  525. private:
  526. std::unique_ptr<RandomAccessFile> target_;
  527. std::atomic<int>& files_closed_;
  528. };
  529. Status s = target()->NewRandomAccessFile(f, r, env_options);
  530. if (s.ok()) {
  531. r->reset(new TracedRandomAccessFile(std::move(*r), files_closed_));
  532. }
  533. return s;
  534. }
  535. int files_closed() const {
  536. return files_closed_.load(std::memory_order_relaxed);
  537. }
  538. private:
  539. std::atomic<int> files_closed_{0};
  540. };
  541. } // anonymous namespace
  542. TEST_F(DBSecondaryTest, SecondaryCloseFiles) {
  543. Options options;
  544. options.env = env_;
  545. options.max_open_files = 1;
  546. options.disable_auto_compactions = true;
  547. Reopen(options);
  548. Options options1;
  549. std::unique_ptr<Env> traced_env(new TraceFileEnv(env_));
  550. options1.env = traced_env.get();
  551. OpenSecondary(options1);
  552. static const auto verify_db = [&]() {
  553. std::unique_ptr<Iterator> iter1(dbfull()->NewIterator(ReadOptions()));
  554. std::unique_ptr<Iterator> iter2(db_secondary_->NewIterator(ReadOptions()));
  555. for (iter1->SeekToFirst(), iter2->SeekToFirst();
  556. iter1->Valid() && iter2->Valid(); iter1->Next(), iter2->Next()) {
  557. ASSERT_EQ(iter1->key(), iter2->key());
  558. ASSERT_EQ(iter1->value(), iter2->value());
  559. }
  560. ASSERT_FALSE(iter1->Valid());
  561. ASSERT_FALSE(iter2->Valid());
  562. ASSERT_OK(iter1->status());
  563. ASSERT_OK(iter2->status());
  564. };
  565. ASSERT_OK(Put("a", "value"));
  566. ASSERT_OK(Put("c", "value"));
  567. ASSERT_OK(Flush());
  568. ASSERT_OK(db_secondary_->TryCatchUpWithPrimary());
  569. verify_db();
  570. ASSERT_OK(Put("b", "value"));
  571. ASSERT_OK(Put("d", "value"));
  572. ASSERT_OK(Flush());
  573. ASSERT_OK(db_secondary_->TryCatchUpWithPrimary());
  574. verify_db();
  575. ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  576. ASSERT_OK(db_secondary_->TryCatchUpWithPrimary());
  577. ASSERT_EQ(2, static_cast<TraceFileEnv*>(traced_env.get())->files_closed());
  578. Status s = db_secondary_->SetDBOptions({{"max_open_files", "-1"}});
  579. ASSERT_TRUE(s.IsNotSupported());
  580. CloseSecondary();
  581. }
  582. TEST_F(DBSecondaryTest, OpenAsSecondaryWALTailing) {
  583. Options options;
  584. options.env = env_;
  585. options.level0_file_num_compaction_trigger = 4;
  586. Reopen(options);
  587. for (int i = 0; i < 3; ++i) {
  588. ASSERT_OK(Put("foo", "foo_value" + std::to_string(i)));
  589. ASSERT_OK(Put("bar", "bar_value" + std::to_string(i)));
  590. }
  591. Options options1;
  592. options1.env = env_;
  593. options1.max_open_files = -1;
  594. OpenSecondary(options1);
  595. ReadOptions ropts;
  596. ropts.verify_checksums = true;
  597. const auto verify_db_func = [&](const std::string& foo_val,
  598. const std::string& bar_val) {
  599. std::string value;
  600. ASSERT_OK(db_secondary_->Get(ropts, "foo", &value));
  601. ASSERT_EQ(foo_val, value);
  602. ASSERT_OK(db_secondary_->Get(ropts, "bar", &value));
  603. ASSERT_EQ(bar_val, value);
  604. Iterator* iter = db_secondary_->NewIterator(ropts);
  605. ASSERT_NE(nullptr, iter);
  606. iter->Seek("foo");
  607. ASSERT_TRUE(iter->Valid());
  608. ASSERT_EQ("foo", iter->key().ToString());
  609. ASSERT_EQ(foo_val, iter->value().ToString());
  610. iter->Seek("bar");
  611. ASSERT_TRUE(iter->Valid());
  612. ASSERT_EQ("bar", iter->key().ToString());
  613. ASSERT_EQ(bar_val, iter->value().ToString());
  614. size_t count = 0;
  615. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  616. ++count;
  617. }
  618. ASSERT_EQ(2, count);
  619. delete iter;
  620. };
  621. verify_db_func("foo_value2", "bar_value2");
  622. ASSERT_OK(Put("foo", "new_foo_value"));
  623. ASSERT_OK(Put("bar", "new_bar_value"));
  624. ASSERT_OK(db_secondary_->TryCatchUpWithPrimary());
  625. verify_db_func("new_foo_value", "new_bar_value");
  626. ASSERT_OK(Flush());
  627. ASSERT_OK(Put("foo", "new_foo_value_1"));
  628. ASSERT_OK(db_secondary_->TryCatchUpWithPrimary());
  629. verify_db_func("new_foo_value_1", "new_bar_value");
  630. }
  631. TEST_F(DBSecondaryTest, SecondaryTailingBug_ISSUE_8467) {
  632. Options options;
  633. options.env = env_;
  634. Reopen(options);
  635. for (int i = 0; i < 3; ++i) {
  636. ASSERT_OK(Put("foo", "foo_value" + std::to_string(i)));
  637. ASSERT_OK(Put("bar", "bar_value" + std::to_string(i)));
  638. }
  639. Options options1;
  640. options1.env = env_;
  641. options1.max_open_files = -1;
  642. OpenSecondary(options1);
  643. const auto verify_db = [&](const std::string& foo_val,
  644. const std::string& bar_val) {
  645. std::string value;
  646. ReadOptions ropts;
  647. Status s = db_secondary_->Get(ropts, "foo", &value);
  648. ASSERT_OK(s);
  649. ASSERT_EQ(foo_val, value);
  650. s = db_secondary_->Get(ropts, "bar", &value);
  651. ASSERT_OK(s);
  652. ASSERT_EQ(bar_val, value);
  653. };
  654. for (int i = 0; i < 2; ++i) {
  655. ASSERT_OK(db_secondary_->TryCatchUpWithPrimary());
  656. verify_db("foo_value2", "bar_value2");
  657. }
  658. }
  659. TEST_F(DBSecondaryTest, RefreshIterator) {
  660. Options options;
  661. options.env = env_;
  662. Reopen(options);
  663. Options options1;
  664. options1.env = env_;
  665. options1.max_open_files = -1;
  666. OpenSecondary(options1);
  667. std::unique_ptr<Iterator> it(db_secondary_->NewIterator(ReadOptions()));
  668. for (int i = 0; i < 3; ++i) {
  669. ASSERT_OK(Put("foo", "foo_value" + std::to_string(i)));
  670. ASSERT_OK(db_secondary_->TryCatchUpWithPrimary());
  671. if (0 == i) {
  672. it->Seek("foo");
  673. ASSERT_FALSE(it->Valid());
  674. ASSERT_OK(it->status());
  675. ASSERT_OK(it->Refresh());
  676. it->Seek("foo");
  677. ASSERT_OK(it->status());
  678. ASSERT_TRUE(it->Valid());
  679. ASSERT_EQ("foo", it->key());
  680. ASSERT_EQ("foo_value0", it->value());
  681. } else {
  682. it->Seek("foo");
  683. ASSERT_TRUE(it->Valid());
  684. ASSERT_EQ("foo", it->key());
  685. ASSERT_EQ("foo_value" + std::to_string(i - 1), it->value());
  686. ASSERT_OK(it->status());
  687. ASSERT_OK(it->Refresh());
  688. it->Seek("foo");
  689. ASSERT_OK(it->status());
  690. ASSERT_TRUE(it->Valid());
  691. ASSERT_EQ("foo", it->key());
  692. ASSERT_EQ("foo_value" + std::to_string(i), it->value());
  693. }
  694. }
  695. }
  696. TEST_F(DBSecondaryTest, OpenWithNonExistColumnFamily) {
  697. Options options;
  698. options.env = env_;
  699. CreateAndReopenWithCF({"pikachu"}, options);
  700. Options options1;
  701. options1.env = env_;
  702. options1.max_open_files = -1;
  703. std::vector<ColumnFamilyDescriptor> cf_descs;
  704. cf_descs.emplace_back(kDefaultColumnFamilyName, options1);
  705. cf_descs.emplace_back("pikachu", options1);
  706. cf_descs.emplace_back("eevee", options1);
  707. Status s = DB::OpenAsSecondary(options1, dbname_, secondary_path_, cf_descs,
  708. &handles_secondary_, &db_secondary_);
  709. ASSERT_NOK(s);
  710. }
  711. TEST_F(DBSecondaryTest, OpenWithSubsetOfColumnFamilies) {
  712. Options options;
  713. options.env = env_;
  714. CreateAndReopenWithCF({"pikachu"}, options);
  715. Options options1;
  716. options1.env = env_;
  717. options1.max_open_files = -1;
  718. OpenSecondary(options1);
  719. ASSERT_EQ(0, handles_secondary_.size());
  720. ASSERT_NE(nullptr, db_secondary_);
  721. ASSERT_OK(Put(0 /*cf*/, "foo", "foo_value"));
  722. ASSERT_OK(Put(1 /*cf*/, "foo", "foo_value"));
  723. ASSERT_OK(Flush(0 /*cf*/));
  724. ASSERT_OK(Flush(1 /*cf*/));
  725. ASSERT_OK(db_secondary_->TryCatchUpWithPrimary());
  726. ReadOptions ropts;
  727. ropts.verify_checksums = true;
  728. std::string value;
  729. ASSERT_OK(db_secondary_->Get(ropts, "foo", &value));
  730. ASSERT_EQ("foo_value", value);
  731. }
  732. TEST_F(DBSecondaryTest, SwitchToNewManifestDuringOpen) {
  733. Options options;
  734. options.env = env_;
  735. Reopen(options);
  736. Close();
  737. SyncPoint::GetInstance()->DisableProcessing();
  738. SyncPoint::GetInstance()->ClearAllCallBacks();
  739. SyncPoint::GetInstance()->LoadDependency(
  740. {{"ReactiveVersionSet::MaybeSwitchManifest:AfterGetCurrentManifestPath:0",
  741. "VersionSet::ProcessManifestWrites:BeforeNewManifest"},
  742. {"DBImpl::Open:AfterDeleteFiles",
  743. "ReactiveVersionSet::MaybeSwitchManifest:AfterGetCurrentManifestPath:"
  744. "1"}});
  745. SyncPoint::GetInstance()->EnableProcessing();
  746. port::Thread ro_db_thread([&]() {
  747. Options options1;
  748. options1.env = env_;
  749. options1.max_open_files = -1;
  750. Status s = TryOpenSecondary(options1);
  751. ASSERT_TRUE(s.IsTryAgain());
  752. // Try again
  753. OpenSecondary(options1);
  754. CloseSecondary();
  755. });
  756. Reopen(options);
  757. ro_db_thread.join();
  758. }
  759. TEST_F(DBSecondaryTest, MissingTableFileDuringOpen) {
  760. Options options;
  761. options.env = env_;
  762. options.level0_file_num_compaction_trigger = 4;
  763. Reopen(options);
  764. for (int i = 0; i != options.level0_file_num_compaction_trigger; ++i) {
  765. ASSERT_OK(Put("foo", "foo_value" + std::to_string(i)));
  766. ASSERT_OK(Put("bar", "bar_value" + std::to_string(i)));
  767. ASSERT_OK(dbfull()->Flush(FlushOptions()));
  768. }
  769. ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
  770. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  771. Options options1;
  772. options1.env = env_;
  773. options1.max_open_files = -1;
  774. OpenSecondary(options1);
  775. ReadOptions ropts;
  776. ropts.verify_checksums = true;
  777. std::string value;
  778. ASSERT_OK(db_secondary_->Get(ropts, "foo", &value));
  779. ASSERT_EQ("foo_value" +
  780. std::to_string(options.level0_file_num_compaction_trigger - 1),
  781. value);
  782. ASSERT_OK(db_secondary_->Get(ropts, "bar", &value));
  783. ASSERT_EQ("bar_value" +
  784. std::to_string(options.level0_file_num_compaction_trigger - 1),
  785. value);
  786. Iterator* iter = db_secondary_->NewIterator(ropts);
  787. ASSERT_NE(nullptr, iter);
  788. iter->Seek("bar");
  789. ASSERT_TRUE(iter->Valid());
  790. ASSERT_EQ("bar", iter->key().ToString());
  791. ASSERT_EQ("bar_value" +
  792. std::to_string(options.level0_file_num_compaction_trigger - 1),
  793. iter->value().ToString());
  794. iter->Seek("foo");
  795. ASSERT_TRUE(iter->Valid());
  796. ASSERT_EQ("foo", iter->key().ToString());
  797. ASSERT_EQ("foo_value" +
  798. std::to_string(options.level0_file_num_compaction_trigger - 1),
  799. iter->value().ToString());
  800. size_t count = 0;
  801. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  802. ++count;
  803. }
  804. ASSERT_OK(iter->status());
  805. ASSERT_EQ(2, count);
  806. delete iter;
  807. }
  808. TEST_F(DBSecondaryTest, MissingTableFile) {
  809. Options options;
  810. options.env = env_;
  811. options.level0_file_num_compaction_trigger = 4;
  812. Reopen(options);
  813. Options options1;
  814. options1.env = env_;
  815. options1.max_open_files = -1;
  816. OpenSecondary(options1);
  817. for (int i = 0; i != options.level0_file_num_compaction_trigger; ++i) {
  818. ASSERT_OK(Put("foo", "foo_value" + std::to_string(i)));
  819. ASSERT_OK(Put("bar", "bar_value" + std::to_string(i)));
  820. ASSERT_OK(dbfull()->Flush(FlushOptions()));
  821. }
  822. ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
  823. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  824. ASSERT_NE(nullptr, db_secondary_full());
  825. ReadOptions ropts;
  826. ropts.verify_checksums = true;
  827. std::string value;
  828. ASSERT_NOK(db_secondary_->Get(ropts, "foo", &value));
  829. ASSERT_NOK(db_secondary_->Get(ropts, "bar", &value));
  830. ASSERT_OK(db_secondary_->TryCatchUpWithPrimary());
  831. ASSERT_OK(db_secondary_->Get(ropts, "foo", &value));
  832. ASSERT_EQ("foo_value" +
  833. std::to_string(options.level0_file_num_compaction_trigger - 1),
  834. value);
  835. ASSERT_OK(db_secondary_->Get(ropts, "bar", &value));
  836. ASSERT_EQ("bar_value" +
  837. std::to_string(options.level0_file_num_compaction_trigger - 1),
  838. value);
  839. Iterator* iter = db_secondary_->NewIterator(ropts);
  840. ASSERT_NE(nullptr, iter);
  841. iter->Seek("bar");
  842. ASSERT_TRUE(iter->Valid());
  843. ASSERT_EQ("bar", iter->key().ToString());
  844. ASSERT_EQ("bar_value" +
  845. std::to_string(options.level0_file_num_compaction_trigger - 1),
  846. iter->value().ToString());
  847. iter->Seek("foo");
  848. ASSERT_TRUE(iter->Valid());
  849. ASSERT_EQ("foo", iter->key().ToString());
  850. ASSERT_EQ("foo_value" +
  851. std::to_string(options.level0_file_num_compaction_trigger - 1),
  852. iter->value().ToString());
  853. size_t count = 0;
  854. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  855. ++count;
  856. }
  857. ASSERT_OK(iter->status());
  858. ASSERT_EQ(2, count);
  859. delete iter;
  860. }
  861. TEST_F(DBSecondaryTest, PrimaryDropColumnFamily) {
  862. Options options;
  863. options.env = env_;
  864. const std::string kCfName1 = "pikachu";
  865. CreateAndReopenWithCF({kCfName1}, options);
  866. Options options1;
  867. options1.env = env_;
  868. options1.max_open_files = -1;
  869. OpenSecondaryWithColumnFamilies({kCfName1}, options1);
  870. ASSERT_EQ(2, handles_secondary_.size());
  871. ASSERT_OK(Put(1 /*cf*/, "foo", "foo_val_1"));
  872. ASSERT_OK(Flush(1 /*cf*/));
  873. ASSERT_OK(db_secondary_->TryCatchUpWithPrimary());
  874. ReadOptions ropts;
  875. ropts.verify_checksums = true;
  876. std::string value;
  877. ASSERT_OK(db_secondary_->Get(ropts, handles_secondary_[1], "foo", &value));
  878. ASSERT_EQ("foo_val_1", value);
  879. ASSERT_OK(dbfull()->DropColumnFamily(handles_[1]));
  880. Close();
  881. CheckFileTypeCounts(dbname_, 1, 0, 1);
  882. ASSERT_OK(db_secondary_->TryCatchUpWithPrimary());
  883. value.clear();
  884. ASSERT_OK(db_secondary_->Get(ropts, handles_secondary_[1], "foo", &value));
  885. ASSERT_EQ("foo_val_1", value);
  886. }
  887. TEST_F(DBSecondaryTest, SwitchManifest) {
  888. Options options;
  889. options.env = env_;
  890. options.level0_file_num_compaction_trigger = 4;
  891. const std::string cf1_name("test_cf");
  892. CreateAndReopenWithCF({cf1_name}, options);
  893. Options options1;
  894. options1.env = env_;
  895. options1.max_open_files = -1;
  896. OpenSecondaryWithColumnFamilies({kDefaultColumnFamilyName, cf1_name},
  897. options1);
  898. const int kNumFiles = options.level0_file_num_compaction_trigger - 1;
  899. // Keep it smaller than 10 so that key0, key1, ..., key9 are sorted as 0, 1,
  900. // ..., 9.
  901. const int kNumKeys = 10;
  902. // Create two sst
  903. for (int i = 0; i != kNumFiles; ++i) {
  904. for (int j = 0; j != kNumKeys; ++j) {
  905. ASSERT_OK(Put("key" + std::to_string(j), "value_" + std::to_string(i)));
  906. }
  907. ASSERT_OK(Flush());
  908. }
  909. ASSERT_OK(db_secondary_->TryCatchUpWithPrimary());
  910. const auto& range_scan_db = [&]() {
  911. ReadOptions tmp_ropts;
  912. tmp_ropts.total_order_seek = true;
  913. tmp_ropts.verify_checksums = true;
  914. std::unique_ptr<Iterator> iter(db_secondary_->NewIterator(tmp_ropts));
  915. int cnt = 0;
  916. for (iter->SeekToFirst(); iter->Valid(); iter->Next(), ++cnt) {
  917. ASSERT_EQ("key" + std::to_string(cnt), iter->key().ToString());
  918. ASSERT_EQ("value_" + std::to_string(kNumFiles - 1),
  919. iter->value().ToString());
  920. }
  921. EXPECT_OK(iter->status());
  922. };
  923. range_scan_db();
  924. // While secondary instance still keeps old MANIFEST open, we close primary,
  925. // restart primary, performs full compaction, close again, restart again so
  926. // that next time secondary tries to catch up with primary, the secondary
  927. // will skip the MANIFEST in middle.
  928. ReopenWithColumnFamilies({kDefaultColumnFamilyName, cf1_name}, options);
  929. ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  930. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  931. ReopenWithColumnFamilies({kDefaultColumnFamilyName, cf1_name}, options);
  932. ASSERT_OK(dbfull()->SetOptions({{"disable_auto_compactions", "false"}}));
  933. ASSERT_OK(db_secondary_->TryCatchUpWithPrimary());
  934. range_scan_db();
  935. }
  936. TEST_F(DBSecondaryTest, SwitchManifestTwice) {
  937. Options options;
  938. options.env = env_;
  939. options.disable_auto_compactions = true;
  940. const std::string cf1_name("test_cf");
  941. CreateAndReopenWithCF({cf1_name}, options);
  942. Options options1;
  943. options1.env = env_;
  944. options1.max_open_files = -1;
  945. OpenSecondaryWithColumnFamilies({kDefaultColumnFamilyName, cf1_name},
  946. options1);
  947. ASSERT_OK(Put("0", "value0"));
  948. ASSERT_OK(Flush());
  949. ASSERT_OK(db_secondary_->TryCatchUpWithPrimary());
  950. std::string value;
  951. ReadOptions ropts;
  952. ropts.verify_checksums = true;
  953. ASSERT_OK(db_secondary_->Get(ropts, "0", &value));
  954. ASSERT_EQ("value0", value);
  955. ReopenWithColumnFamilies({kDefaultColumnFamilyName, cf1_name}, options);
  956. ASSERT_OK(dbfull()->SetOptions({{"disable_auto_compactions", "false"}}));
  957. ReopenWithColumnFamilies({kDefaultColumnFamilyName, cf1_name}, options);
  958. ASSERT_OK(Put("0", "value1"));
  959. ASSERT_OK(db_secondary_->TryCatchUpWithPrimary());
  960. ASSERT_OK(db_secondary_->Get(ropts, "0", &value));
  961. ASSERT_EQ("value1", value);
  962. }
  963. TEST_F(DBSecondaryTest, DISABLED_SwitchWAL) {
  964. const int kNumKeysPerMemtable = 1;
  965. Options options;
  966. options.env = env_;
  967. options.max_write_buffer_number = 4;
  968. options.min_write_buffer_number_to_merge = 2;
  969. options.memtable_factory.reset(
  970. test::NewSpecialSkipListFactory(kNumKeysPerMemtable));
  971. Reopen(options);
  972. Options options1;
  973. options1.env = env_;
  974. options1.max_open_files = -1;
  975. OpenSecondary(options1);
  976. const auto& verify_db = [](DB* db1, DB* db2) {
  977. ASSERT_NE(nullptr, db1);
  978. ASSERT_NE(nullptr, db2);
  979. ReadOptions read_opts;
  980. read_opts.verify_checksums = true;
  981. std::unique_ptr<Iterator> it1(db1->NewIterator(read_opts));
  982. std::unique_ptr<Iterator> it2(db2->NewIterator(read_opts));
  983. it1->SeekToFirst();
  984. it2->SeekToFirst();
  985. for (; it1->Valid() && it2->Valid(); it1->Next(), it2->Next()) {
  986. ASSERT_EQ(it1->key(), it2->key());
  987. ASSERT_EQ(it1->value(), it2->value());
  988. }
  989. ASSERT_FALSE(it1->Valid());
  990. ASSERT_FALSE(it2->Valid());
  991. for (it1->SeekToFirst(); it1->Valid(); it1->Next()) {
  992. std::string value;
  993. ASSERT_OK(db2->Get(read_opts, it1->key(), &value));
  994. ASSERT_EQ(it1->value(), value);
  995. }
  996. for (it2->SeekToFirst(); it2->Valid(); it2->Next()) {
  997. std::string value;
  998. ASSERT_OK(db1->Get(read_opts, it2->key(), &value));
  999. ASSERT_EQ(it2->value(), value);
  1000. }
  1001. };
  1002. for (int k = 0; k != 16; ++k) {
  1003. ASSERT_OK(Put("key" + std::to_string(k), "value" + std::to_string(k)));
  1004. ASSERT_OK(db_secondary_->TryCatchUpWithPrimary());
  1005. verify_db(dbfull(), db_secondary_);
  1006. }
  1007. }
  1008. TEST_F(DBSecondaryTest, DISABLED_SwitchWALMultiColumnFamilies) {
  1009. const int kNumKeysPerMemtable = 1;
  1010. SyncPoint::GetInstance()->DisableProcessing();
  1011. SyncPoint::GetInstance()->LoadDependency(
  1012. {{"DBImpl::BackgroundCallFlush:ContextCleanedUp",
  1013. "DBSecondaryTest::SwitchWALMultipleColumnFamilies:BeforeCatchUp"}});
  1014. SyncPoint::GetInstance()->EnableProcessing();
  1015. const std::string kCFName1 = "pikachu";
  1016. Options options;
  1017. options.env = env_;
  1018. options.max_write_buffer_number = 4;
  1019. options.min_write_buffer_number_to_merge = 2;
  1020. options.memtable_factory.reset(
  1021. test::NewSpecialSkipListFactory(kNumKeysPerMemtable));
  1022. CreateAndReopenWithCF({kCFName1}, options);
  1023. Options options1;
  1024. options1.env = env_;
  1025. options1.max_open_files = -1;
  1026. OpenSecondaryWithColumnFamilies({kCFName1}, options1);
  1027. ASSERT_EQ(2, handles_secondary_.size());
  1028. const auto& verify_db = [](DB* db1,
  1029. const std::vector<ColumnFamilyHandle*>& handles1,
  1030. DB* db2,
  1031. const std::vector<ColumnFamilyHandle*>& handles2) {
  1032. ASSERT_NE(nullptr, db1);
  1033. ASSERT_NE(nullptr, db2);
  1034. ReadOptions read_opts;
  1035. read_opts.verify_checksums = true;
  1036. ASSERT_EQ(handles1.size(), handles2.size());
  1037. for (size_t i = 0; i != handles1.size(); ++i) {
  1038. std::unique_ptr<Iterator> it1(db1->NewIterator(read_opts, handles1[i]));
  1039. std::unique_ptr<Iterator> it2(db2->NewIterator(read_opts, handles2[i]));
  1040. it1->SeekToFirst();
  1041. it2->SeekToFirst();
  1042. for (; it1->Valid() && it2->Valid(); it1->Next(), it2->Next()) {
  1043. ASSERT_EQ(it1->key(), it2->key());
  1044. ASSERT_EQ(it1->value(), it2->value());
  1045. }
  1046. ASSERT_FALSE(it1->Valid());
  1047. ASSERT_FALSE(it2->Valid());
  1048. for (it1->SeekToFirst(); it1->Valid(); it1->Next()) {
  1049. std::string value;
  1050. ASSERT_OK(db2->Get(read_opts, handles2[i], it1->key(), &value));
  1051. ASSERT_EQ(it1->value(), value);
  1052. }
  1053. for (it2->SeekToFirst(); it2->Valid(); it2->Next()) {
  1054. std::string value;
  1055. ASSERT_OK(db1->Get(read_opts, handles1[i], it2->key(), &value));
  1056. ASSERT_EQ(it2->value(), value);
  1057. }
  1058. }
  1059. };
  1060. for (int k = 0; k != 8; ++k) {
  1061. for (int j = 0; j < 2; ++j) {
  1062. ASSERT_OK(Put(0 /*cf*/, "key" + std::to_string(k),
  1063. "value" + std::to_string(k)));
  1064. ASSERT_OK(Put(1 /*cf*/, "key" + std::to_string(k),
  1065. "value" + std::to_string(k)));
  1066. }
  1067. TEST_SYNC_POINT(
  1068. "DBSecondaryTest::SwitchWALMultipleColumnFamilies:BeforeCatchUp");
  1069. ASSERT_OK(db_secondary_->TryCatchUpWithPrimary());
  1070. verify_db(dbfull(), handles_, db_secondary_, handles_secondary_);
  1071. SyncPoint::GetInstance()->ClearTrace();
  1072. }
  1073. }
  1074. TEST_F(DBSecondaryTest, CatchUpAfterFlush) {
  1075. const int kNumKeysPerMemtable = 16;
  1076. Options options;
  1077. options.env = env_;
  1078. options.max_write_buffer_number = 4;
  1079. options.min_write_buffer_number_to_merge = 2;
  1080. options.memtable_factory.reset(
  1081. test::NewSpecialSkipListFactory(kNumKeysPerMemtable));
  1082. Reopen(options);
  1083. Options options1;
  1084. options1.env = env_;
  1085. options1.max_open_files = -1;
  1086. OpenSecondary(options1);
  1087. WriteOptions write_opts;
  1088. WriteBatch wb;
  1089. ASSERT_OK(wb.Put("key0", "value0"));
  1090. ASSERT_OK(wb.Put("key1", "value1"));
  1091. ASSERT_OK(dbfull()->Write(write_opts, &wb));
  1092. ReadOptions read_opts;
  1093. std::unique_ptr<Iterator> iter1(db_secondary_->NewIterator(read_opts));
  1094. iter1->Seek("key0");
  1095. ASSERT_FALSE(iter1->Valid());
  1096. iter1->Seek("key1");
  1097. ASSERT_FALSE(iter1->Valid());
  1098. ASSERT_OK(db_secondary_->TryCatchUpWithPrimary());
  1099. iter1->Seek("key0");
  1100. ASSERT_FALSE(iter1->Valid());
  1101. iter1->Seek("key1");
  1102. ASSERT_FALSE(iter1->Valid());
  1103. ASSERT_OK(iter1->status());
  1104. std::unique_ptr<Iterator> iter2(db_secondary_->NewIterator(read_opts));
  1105. iter2->Seek("key0");
  1106. ASSERT_TRUE(iter2->Valid());
  1107. ASSERT_EQ("value0", iter2->value());
  1108. iter2->Seek("key1");
  1109. ASSERT_TRUE(iter2->Valid());
  1110. ASSERT_OK(iter2->status());
  1111. ASSERT_EQ("value1", iter2->value());
  1112. {
  1113. WriteBatch wb1;
  1114. ASSERT_OK(wb1.Put("key0", "value01"));
  1115. ASSERT_OK(wb1.Put("key1", "value11"));
  1116. ASSERT_OK(dbfull()->Write(write_opts, &wb1));
  1117. }
  1118. {
  1119. WriteBatch wb2;
  1120. ASSERT_OK(wb2.Put("key0", "new_value0"));
  1121. ASSERT_OK(wb2.Delete("key1"));
  1122. ASSERT_OK(dbfull()->Write(write_opts, &wb2));
  1123. }
  1124. ASSERT_OK(Flush());
  1125. ASSERT_OK(db_secondary_->TryCatchUpWithPrimary());
  1126. std::unique_ptr<Iterator> iter3(db_secondary_->NewIterator(read_opts));
  1127. // iter3 should not see value01 and value11 at all.
  1128. iter3->Seek("key0");
  1129. ASSERT_TRUE(iter3->Valid());
  1130. ASSERT_EQ("new_value0", iter3->value());
  1131. iter3->Seek("key1");
  1132. ASSERT_FALSE(iter3->Valid());
  1133. ASSERT_OK(iter3->status());
  1134. }
  1135. TEST_F(DBSecondaryTest, StartFromInconsistent) {
  1136. Options options = CurrentOptions();
  1137. DestroyAndReopen(options);
  1138. ASSERT_OK(Put("foo", "value"));
  1139. ASSERT_OK(Flush());
  1140. SyncPoint::GetInstance()->DisableProcessing();
  1141. SyncPoint::GetInstance()->ClearAllCallBacks();
  1142. SyncPoint::GetInstance()->SetCallBack(
  1143. "VersionBuilder::CheckConsistencyBeforeReturn", [&](void* arg) {
  1144. ASSERT_NE(nullptr, arg);
  1145. *(static_cast<Status*>(arg)) = Status::Corruption("Inject corruption");
  1146. });
  1147. SyncPoint::GetInstance()->EnableProcessing();
  1148. Options options1;
  1149. options1.env = env_;
  1150. Status s = TryOpenSecondary(options1);
  1151. ASSERT_TRUE(s.IsCorruption());
  1152. }
  1153. TEST_F(DBSecondaryTest, InconsistencyDuringCatchUp) {
  1154. Options options = CurrentOptions();
  1155. DestroyAndReopen(options);
  1156. ASSERT_OK(Put("foo", "value"));
  1157. ASSERT_OK(Flush());
  1158. Options options1;
  1159. options1.env = env_;
  1160. OpenSecondary(options1);
  1161. {
  1162. std::string value;
  1163. ASSERT_OK(db_secondary_->Get(ReadOptions(), "foo", &value));
  1164. ASSERT_EQ("value", value);
  1165. }
  1166. ASSERT_OK(Put("bar", "value1"));
  1167. ASSERT_OK(Flush());
  1168. SyncPoint::GetInstance()->DisableProcessing();
  1169. SyncPoint::GetInstance()->ClearAllCallBacks();
  1170. SyncPoint::GetInstance()->SetCallBack(
  1171. "VersionBuilder::CheckConsistencyBeforeReturn", [&](void* arg) {
  1172. ASSERT_NE(nullptr, arg);
  1173. *(static_cast<Status*>(arg)) = Status::Corruption("Inject corruption");
  1174. });
  1175. SyncPoint::GetInstance()->EnableProcessing();
  1176. Status s = db_secondary_->TryCatchUpWithPrimary();
  1177. ASSERT_TRUE(s.IsCorruption());
  1178. }
  1179. TEST_F(DBSecondaryTest, OpenWithTransactionDB) {
  1180. Options options = CurrentOptions();
  1181. options.create_if_missing = true;
  1182. // Destroy the DB to recreate as a TransactionDB.
  1183. Close();
  1184. Destroy(options, true);
  1185. // Create a TransactionDB.
  1186. TransactionDB* txn_db = nullptr;
  1187. TransactionDBOptions txn_db_opts;
  1188. ASSERT_OK(TransactionDB::Open(options, txn_db_opts, dbname_, &txn_db));
  1189. ASSERT_NE(txn_db, nullptr);
  1190. db_ = txn_db;
  1191. std::vector<std::string> cfs = {"new_CF"};
  1192. CreateColumnFamilies(cfs, options);
  1193. ASSERT_EQ(handles_.size(), 1);
  1194. WriteOptions wopts;
  1195. TransactionOptions txn_opts;
  1196. Transaction* txn1 = txn_db->BeginTransaction(wopts, txn_opts, nullptr);
  1197. ASSERT_NE(txn1, nullptr);
  1198. ASSERT_OK(txn1->Put(handles_[0], "k1", "v1"));
  1199. ASSERT_OK(txn1->Commit());
  1200. delete txn1;
  1201. options = CurrentOptions();
  1202. options.max_open_files = -1;
  1203. ASSERT_OK(TryOpenSecondary(options));
  1204. }
  1205. class DBSecondaryTestWithTimestamp : public DBSecondaryTestBase {
  1206. public:
  1207. explicit DBSecondaryTestWithTimestamp()
  1208. : DBSecondaryTestBase("db_secondary_test_with_timestamp") {}
  1209. };
  1210. TEST_F(DBSecondaryTestWithTimestamp, IteratorAndGetReadTimestampSizeMismatch) {
  1211. const int kNumKeysPerFile = 128;
  1212. const uint64_t kMaxKey = 1024;
  1213. Options options = CurrentOptions();
  1214. options.env = env_;
  1215. options.create_if_missing = true;
  1216. const size_t kTimestampSize = Timestamp(0, 0).size();
  1217. TestComparator test_cmp(kTimestampSize);
  1218. options.comparator = &test_cmp;
  1219. options.memtable_factory.reset(
  1220. test::NewSpecialSkipListFactory(kNumKeysPerFile));
  1221. DestroyAndReopen(options);
  1222. const std::string write_timestamp = Timestamp(1, 0);
  1223. WriteOptions write_opts;
  1224. for (uint64_t key = 0; key <= kMaxKey; ++key) {
  1225. Status s = db_->Put(write_opts, Key1(key), write_timestamp,
  1226. "value" + std::to_string(key));
  1227. ASSERT_OK(s);
  1228. }
  1229. // Reopen the database as secondary instance to test its timestamp support.
  1230. Close();
  1231. options.max_open_files = -1;
  1232. ASSERT_OK(ReopenAsSecondary(options));
  1233. ReadOptions read_opts;
  1234. std::string different_size_read_timestamp;
  1235. PutFixed32(&different_size_read_timestamp, 2);
  1236. Slice different_size_read_ts = different_size_read_timestamp;
  1237. read_opts.timestamp = &different_size_read_ts;
  1238. {
  1239. std::unique_ptr<Iterator> iter(db_->NewIterator(read_opts));
  1240. ASSERT_FALSE(iter->Valid());
  1241. ASSERT_TRUE(iter->status().IsInvalidArgument());
  1242. }
  1243. for (uint64_t key = 0; key <= kMaxKey; ++key) {
  1244. std::string value_from_get;
  1245. std::string timestamp;
  1246. ASSERT_TRUE(db_->Get(read_opts, Key1(key), &value_from_get, &timestamp)
  1247. .IsInvalidArgument());
  1248. }
  1249. Close();
  1250. }
  1251. TEST_F(DBSecondaryTestWithTimestamp,
  1252. IteratorAndGetReadTimestampSpecifiedWithoutWriteTimestamp) {
  1253. const int kNumKeysPerFile = 128;
  1254. const uint64_t kMaxKey = 1024;
  1255. Options options = CurrentOptions();
  1256. options.env = env_;
  1257. options.create_if_missing = true;
  1258. options.memtable_factory.reset(
  1259. test::NewSpecialSkipListFactory(kNumKeysPerFile));
  1260. DestroyAndReopen(options);
  1261. WriteOptions write_opts;
  1262. for (uint64_t key = 0; key <= kMaxKey; ++key) {
  1263. Status s = db_->Put(write_opts, Key1(key), "value" + std::to_string(key));
  1264. ASSERT_OK(s);
  1265. }
  1266. // Reopen the database as secondary instance to test its timestamp support.
  1267. Close();
  1268. options.max_open_files = -1;
  1269. ASSERT_OK(ReopenAsSecondary(options));
  1270. ReadOptions read_opts;
  1271. const std::string read_timestamp = Timestamp(2, 0);
  1272. Slice read_ts = read_timestamp;
  1273. read_opts.timestamp = &read_ts;
  1274. {
  1275. std::unique_ptr<Iterator> iter(db_->NewIterator(read_opts));
  1276. ASSERT_FALSE(iter->Valid());
  1277. ASSERT_TRUE(iter->status().IsInvalidArgument());
  1278. }
  1279. for (uint64_t key = 0; key <= kMaxKey; ++key) {
  1280. std::string value_from_get;
  1281. std::string timestamp;
  1282. ASSERT_TRUE(db_->Get(read_opts, Key1(key), &value_from_get, &timestamp)
  1283. .IsInvalidArgument());
  1284. }
  1285. Close();
  1286. }
  1287. TEST_F(DBSecondaryTestWithTimestamp,
  1288. IteratorAndGetWriteWithTimestampReadWithoutTimestamp) {
  1289. const int kNumKeysPerFile = 128;
  1290. const uint64_t kMaxKey = 1024;
  1291. Options options = CurrentOptions();
  1292. options.env = env_;
  1293. options.create_if_missing = true;
  1294. const size_t kTimestampSize = Timestamp(0, 0).size();
  1295. TestComparator test_cmp(kTimestampSize);
  1296. options.comparator = &test_cmp;
  1297. options.memtable_factory.reset(
  1298. test::NewSpecialSkipListFactory(kNumKeysPerFile));
  1299. DestroyAndReopen(options);
  1300. const std::string write_timestamp = Timestamp(1, 0);
  1301. WriteOptions write_opts;
  1302. for (uint64_t key = 0; key <= kMaxKey; ++key) {
  1303. Status s = db_->Put(write_opts, Key1(key), write_timestamp,
  1304. "value" + std::to_string(key));
  1305. ASSERT_OK(s);
  1306. }
  1307. // Reopen the database as secondary instance to test its timestamp support.
  1308. Close();
  1309. options.max_open_files = -1;
  1310. ASSERT_OK(ReopenAsSecondary(options));
  1311. ReadOptions read_opts;
  1312. {
  1313. std::unique_ptr<Iterator> iter(db_->NewIterator(read_opts));
  1314. ASSERT_FALSE(iter->Valid());
  1315. ASSERT_TRUE(iter->status().IsInvalidArgument());
  1316. }
  1317. for (uint64_t key = 0; key <= kMaxKey; ++key) {
  1318. std::string value_from_get;
  1319. ASSERT_TRUE(
  1320. db_->Get(read_opts, Key1(key), &value_from_get).IsInvalidArgument());
  1321. }
  1322. Close();
  1323. }
  1324. TEST_F(DBSecondaryTestWithTimestamp, IteratorAndGet) {
  1325. const int kNumKeysPerFile = 128;
  1326. const uint64_t kMaxKey = 1024;
  1327. Options options = CurrentOptions();
  1328. options.env = env_;
  1329. options.create_if_missing = true;
  1330. const size_t kTimestampSize = Timestamp(0, 0).size();
  1331. TestComparator test_cmp(kTimestampSize);
  1332. options.comparator = &test_cmp;
  1333. options.memtable_factory.reset(
  1334. test::NewSpecialSkipListFactory(kNumKeysPerFile));
  1335. DestroyAndReopen(options);
  1336. const std::vector<uint64_t> start_keys = {1, 0};
  1337. const std::vector<std::string> write_timestamps = {Timestamp(1, 0),
  1338. Timestamp(3, 0)};
  1339. const std::vector<std::string> read_timestamps = {Timestamp(2, 0),
  1340. Timestamp(4, 0)};
  1341. for (size_t i = 0; i < write_timestamps.size(); ++i) {
  1342. WriteOptions write_opts;
  1343. for (uint64_t key = start_keys[i]; key <= kMaxKey; ++key) {
  1344. Status s = db_->Put(write_opts, Key1(key), write_timestamps[i],
  1345. "value" + std::to_string(i));
  1346. ASSERT_OK(s);
  1347. }
  1348. }
  1349. // Reopen the database as secondary instance to test its timestamp support.
  1350. Close();
  1351. options.max_open_files = -1;
  1352. ASSERT_OK(ReopenAsSecondary(options));
  1353. auto get_value_and_check = [](DB* db, ReadOptions read_opts, Slice key,
  1354. Slice expected_value, std::string expected_ts) {
  1355. std::string value_from_get;
  1356. std::string timestamp;
  1357. ASSERT_OK(db->Get(read_opts, key.ToString(), &value_from_get, &timestamp));
  1358. ASSERT_EQ(expected_value, value_from_get);
  1359. ASSERT_EQ(expected_ts, timestamp);
  1360. };
  1361. for (size_t i = 0; i < read_timestamps.size(); ++i) {
  1362. ReadOptions read_opts;
  1363. Slice read_ts = read_timestamps[i];
  1364. read_opts.timestamp = &read_ts;
  1365. std::unique_ptr<Iterator> it(db_->NewIterator(read_opts));
  1366. int count = 0;
  1367. uint64_t key = 0;
  1368. // Forward iterate.
  1369. for (it->Seek(Key1(0)), key = start_keys[i]; it->Valid();
  1370. it->Next(), ++count, ++key) {
  1371. CheckIterUserEntry(it.get(), Key1(key), kTypeValue,
  1372. "value" + std::to_string(i), write_timestamps[i]);
  1373. get_value_and_check(db_, read_opts, it->key(), it->value(),
  1374. write_timestamps[i]);
  1375. }
  1376. ASSERT_OK(it->status());
  1377. size_t expected_count = kMaxKey - start_keys[i] + 1;
  1378. ASSERT_EQ(expected_count, count);
  1379. // Backward iterate.
  1380. count = 0;
  1381. for (it->SeekForPrev(Key1(kMaxKey)), key = kMaxKey; it->Valid();
  1382. it->Prev(), ++count, --key) {
  1383. CheckIterUserEntry(it.get(), Key1(key), kTypeValue,
  1384. "value" + std::to_string(i), write_timestamps[i]);
  1385. get_value_and_check(db_, read_opts, it->key(), it->value(),
  1386. write_timestamps[i]);
  1387. }
  1388. ASSERT_OK(it->status());
  1389. ASSERT_EQ(static_cast<size_t>(kMaxKey) - start_keys[i] + 1, count);
  1390. // SeekToFirst()/SeekToLast() with lower/upper bounds.
  1391. // Then iter with lower and upper bounds.
  1392. uint64_t l = 0;
  1393. uint64_t r = kMaxKey + 1;
  1394. while (l < r) {
  1395. std::string lb_str = Key1(l);
  1396. Slice lb = lb_str;
  1397. std::string ub_str = Key1(r);
  1398. Slice ub = ub_str;
  1399. read_opts.iterate_lower_bound = &lb;
  1400. read_opts.iterate_upper_bound = &ub;
  1401. it.reset(db_->NewIterator(read_opts));
  1402. for (it->SeekToFirst(), key = std::max(l, start_keys[i]), count = 0;
  1403. it->Valid(); it->Next(), ++key, ++count) {
  1404. CheckIterUserEntry(it.get(), Key1(key), kTypeValue,
  1405. "value" + std::to_string(i), write_timestamps[i]);
  1406. get_value_and_check(db_, read_opts, it->key(), it->value(),
  1407. write_timestamps[i]);
  1408. }
  1409. ASSERT_OK(it->status());
  1410. ASSERT_EQ(r - std::max(l, start_keys[i]), count);
  1411. for (it->SeekToLast(), key = std::min(r, kMaxKey + 1), count = 0;
  1412. it->Valid(); it->Prev(), --key, ++count) {
  1413. CheckIterUserEntry(it.get(), Key1(key - 1), kTypeValue,
  1414. "value" + std::to_string(i), write_timestamps[i]);
  1415. get_value_and_check(db_, read_opts, it->key(), it->value(),
  1416. write_timestamps[i]);
  1417. }
  1418. ASSERT_OK(it->status());
  1419. l += (kMaxKey / 100);
  1420. r -= (kMaxKey / 100);
  1421. }
  1422. }
  1423. Close();
  1424. }
  1425. TEST_F(DBSecondaryTestWithTimestamp, IteratorsReadTimestampSizeMismatch) {
  1426. const int kNumKeysPerFile = 128;
  1427. const uint64_t kMaxKey = 1024;
  1428. Options options = CurrentOptions();
  1429. options.env = env_;
  1430. options.create_if_missing = true;
  1431. const size_t kTimestampSize = Timestamp(0, 0).size();
  1432. TestComparator test_cmp(kTimestampSize);
  1433. options.comparator = &test_cmp;
  1434. options.memtable_factory.reset(
  1435. test::NewSpecialSkipListFactory(kNumKeysPerFile));
  1436. DestroyAndReopen(options);
  1437. const std::string write_timestamp = Timestamp(1, 0);
  1438. WriteOptions write_opts;
  1439. for (uint64_t key = 0; key <= kMaxKey; ++key) {
  1440. Status s = db_->Put(write_opts, Key1(key), write_timestamp,
  1441. "value" + std::to_string(key));
  1442. ASSERT_OK(s);
  1443. }
  1444. // Reopen the database as secondary instance to test its timestamp support.
  1445. Close();
  1446. options.max_open_files = -1;
  1447. ASSERT_OK(ReopenAsSecondary(options));
  1448. ReadOptions read_opts;
  1449. std::string different_size_read_timestamp;
  1450. PutFixed32(&different_size_read_timestamp, 2);
  1451. Slice different_size_read_ts = different_size_read_timestamp;
  1452. read_opts.timestamp = &different_size_read_ts;
  1453. {
  1454. std::vector<Iterator*> iters;
  1455. ASSERT_TRUE(
  1456. db_->NewIterators(read_opts, {db_->DefaultColumnFamily()}, &iters)
  1457. .IsInvalidArgument());
  1458. }
  1459. Close();
  1460. }
  1461. TEST_F(DBSecondaryTestWithTimestamp, FullHistoryTsLowSanityCheckFail) {
  1462. Options options = CurrentOptions();
  1463. options.env = env_;
  1464. options.comparator = test::BytewiseComparatorWithU64TsWrapper();
  1465. // Use UDT in memtable only feature for this test, so we can control that
  1466. // newly set `full_history_ts_low` collapse history when Flush happens.
  1467. options.persist_user_defined_timestamps = false;
  1468. options.allow_concurrent_memtable_write = false;
  1469. DestroyAndReopen(options);
  1470. std::string write_ts;
  1471. PutFixed64(&write_ts, 1);
  1472. ASSERT_OK(db_->Put(WriteOptions(), "foo", write_ts, "val1"));
  1473. std::string full_history_ts_low;
  1474. PutFixed64(&full_history_ts_low, 3);
  1475. ASSERT_OK(db_->IncreaseFullHistoryTsLow(db_->DefaultColumnFamily(),
  1476. full_history_ts_low));
  1477. ASSERT_OK(Flush(0));
  1478. // Reopen the database as secondary instance to test its timestamp support.
  1479. Close();
  1480. options.max_open_files = -1;
  1481. ASSERT_OK(ReopenAsSecondary(options));
  1482. // Reading below full_history_ts_low fails a sanity check.
  1483. std::string read_ts;
  1484. PutFixed64(&read_ts, 2);
  1485. Slice read_ts_slice = read_ts;
  1486. ReadOptions read_opts;
  1487. read_opts.timestamp = &read_ts_slice;
  1488. // Get()
  1489. std::string value;
  1490. ASSERT_TRUE(db_->Get(read_opts, "foo", &value).IsInvalidArgument());
  1491. // NewIterator()
  1492. std::unique_ptr<Iterator> iter(
  1493. db_->NewIterator(read_opts, db_->DefaultColumnFamily()));
  1494. ASSERT_TRUE(iter->status().IsInvalidArgument());
  1495. // NewIterators()
  1496. std::vector<ColumnFamilyHandle*> cfhs = {db_->DefaultColumnFamily()};
  1497. std::vector<Iterator*> iterators;
  1498. ASSERT_TRUE(
  1499. db_->NewIterators(read_opts, cfhs, &iterators).IsInvalidArgument());
  1500. Close();
  1501. }
  1502. TEST_F(DBSecondaryTestWithTimestamp,
  1503. IteratorsReadTimestampSpecifiedWithoutWriteTimestamp) {
  1504. const int kNumKeysPerFile = 128;
  1505. const uint64_t kMaxKey = 1024;
  1506. Options options = CurrentOptions();
  1507. options.env = env_;
  1508. options.create_if_missing = true;
  1509. options.memtable_factory.reset(
  1510. test::NewSpecialSkipListFactory(kNumKeysPerFile));
  1511. DestroyAndReopen(options);
  1512. WriteOptions write_opts;
  1513. for (uint64_t key = 0; key <= kMaxKey; ++key) {
  1514. Status s = db_->Put(write_opts, Key1(key), "value" + std::to_string(key));
  1515. ASSERT_OK(s);
  1516. }
  1517. // Reopen the database as secondary instance to test its timestamp support.
  1518. Close();
  1519. options.max_open_files = -1;
  1520. ASSERT_OK(ReopenAsSecondary(options));
  1521. ReadOptions read_opts;
  1522. const std::string read_timestamp = Timestamp(2, 0);
  1523. Slice read_ts = read_timestamp;
  1524. read_opts.timestamp = &read_ts;
  1525. {
  1526. std::vector<Iterator*> iters;
  1527. ASSERT_TRUE(
  1528. db_->NewIterators(read_opts, {db_->DefaultColumnFamily()}, &iters)
  1529. .IsInvalidArgument());
  1530. }
  1531. Close();
  1532. }
  1533. TEST_F(DBSecondaryTestWithTimestamp,
  1534. IteratorsWriteWithTimestampReadWithoutTimestamp) {
  1535. const int kNumKeysPerFile = 128;
  1536. const uint64_t kMaxKey = 1024;
  1537. Options options = CurrentOptions();
  1538. options.env = env_;
  1539. options.create_if_missing = true;
  1540. const size_t kTimestampSize = Timestamp(0, 0).size();
  1541. TestComparator test_cmp(kTimestampSize);
  1542. options.comparator = &test_cmp;
  1543. options.memtable_factory.reset(
  1544. test::NewSpecialSkipListFactory(kNumKeysPerFile));
  1545. DestroyAndReopen(options);
  1546. const std::string write_timestamp = Timestamp(1, 0);
  1547. WriteOptions write_opts;
  1548. for (uint64_t key = 0; key <= kMaxKey; ++key) {
  1549. Status s = db_->Put(write_opts, Key1(key), write_timestamp,
  1550. "value" + std::to_string(key));
  1551. ASSERT_OK(s);
  1552. }
  1553. // Reopen the database as secondary instance to test its timestamp support.
  1554. Close();
  1555. options.max_open_files = -1;
  1556. ASSERT_OK(ReopenAsSecondary(options));
  1557. ReadOptions read_opts;
  1558. {
  1559. std::vector<Iterator*> iters;
  1560. ASSERT_TRUE(
  1561. db_->NewIterators(read_opts, {db_->DefaultColumnFamily()}, &iters)
  1562. .IsInvalidArgument());
  1563. }
  1564. Close();
  1565. }
  1566. TEST_F(DBSecondaryTestWithTimestamp, Iterators) {
  1567. const int kNumKeysPerFile = 128;
  1568. const uint64_t kMaxKey = 1024;
  1569. Options options = CurrentOptions();
  1570. options.env = env_;
  1571. options.create_if_missing = true;
  1572. const size_t kTimestampSize = Timestamp(0, 0).size();
  1573. TestComparator test_cmp(kTimestampSize);
  1574. options.comparator = &test_cmp;
  1575. options.memtable_factory.reset(
  1576. test::NewSpecialSkipListFactory(kNumKeysPerFile));
  1577. DestroyAndReopen(options);
  1578. const std::string write_timestamp = Timestamp(1, 0);
  1579. const std::string read_timestamp = Timestamp(2, 0);
  1580. WriteOptions write_opts;
  1581. for (uint64_t key = 0; key <= kMaxKey; ++key) {
  1582. Status s = db_->Put(write_opts, Key1(key), write_timestamp,
  1583. "value" + std::to_string(key));
  1584. ASSERT_OK(s);
  1585. }
  1586. // Reopen the database as secondary instance to test its timestamp support.
  1587. Close();
  1588. options.max_open_files = -1;
  1589. ASSERT_OK(ReopenAsSecondary(options));
  1590. ReadOptions read_opts;
  1591. Slice read_ts = read_timestamp;
  1592. read_opts.timestamp = &read_ts;
  1593. std::vector<Iterator*> iters;
  1594. ASSERT_OK(db_->NewIterators(read_opts, {db_->DefaultColumnFamily()}, &iters));
  1595. ASSERT_EQ(static_cast<uint64_t>(1), iters.size());
  1596. int count = 0;
  1597. uint64_t key = 0;
  1598. // Forward iterate.
  1599. for (iters[0]->Seek(Key1(0)), key = 0; iters[0]->Valid();
  1600. iters[0]->Next(), ++count, ++key) {
  1601. CheckIterUserEntry(iters[0], Key1(key), kTypeValue,
  1602. "value" + std::to_string(key), write_timestamp);
  1603. }
  1604. ASSERT_OK(iters[0]->status());
  1605. size_t expected_count = kMaxKey - 0 + 1;
  1606. ASSERT_EQ(expected_count, count);
  1607. delete iters[0];
  1608. Close();
  1609. }
  1610. } // namespace ROCKSDB_NAMESPACE
  1611. int main(int argc, char** argv) {
  1612. ROCKSDB_NAMESPACE::port::InstallStackTraceHandler();
  1613. ::testing::InitGoogleTest(&argc, argv);
  1614. return RUN_ALL_TESTS();
  1615. }