transaction_test_util.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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. #include "test_util/transaction_test_util.h"
  6. #include <algorithm>
  7. #include <cinttypes>
  8. #include <numeric>
  9. #include <random>
  10. #include <string>
  11. #include <thread>
  12. #include "db/dbformat.h"
  13. #include "db/snapshot_impl.h"
  14. #include "logging/logging.h"
  15. #include "rocksdb/db.h"
  16. #include "rocksdb/utilities/optimistic_transaction_db.h"
  17. #include "rocksdb/utilities/transaction.h"
  18. #include "rocksdb/utilities/transaction_db.h"
  19. #include "util/random.h"
  20. #include "util/string_util.h"
  21. namespace ROCKSDB_NAMESPACE {
  22. RandomTransactionInserter::RandomTransactionInserter(
  23. Random64* rand, const WriteOptions& write_options,
  24. const ReadOptions& read_options, uint64_t num_keys, uint16_t num_sets,
  25. const uint64_t cmt_delay_ms, const uint64_t first_id)
  26. : rand_(rand),
  27. write_options_(write_options),
  28. read_options_(read_options),
  29. num_keys_(num_keys),
  30. num_sets_(num_sets),
  31. txn_id_(first_id),
  32. cmt_delay_ms_(cmt_delay_ms) {}
  33. RandomTransactionInserter::~RandomTransactionInserter() {
  34. if (txn_ != nullptr) {
  35. delete txn_;
  36. }
  37. if (optimistic_txn_ != nullptr) {
  38. delete optimistic_txn_;
  39. }
  40. }
  41. bool RandomTransactionInserter::TransactionDBInsert(
  42. TransactionDB* db, const TransactionOptions& txn_options) {
  43. txn_ = db->BeginTransaction(write_options_, txn_options, txn_);
  44. std::hash<std::thread::id> hasher;
  45. char name[64];
  46. snprintf(name, 64, "txn%" ROCKSDB_PRIszt "-%" PRIu64,
  47. hasher(std::this_thread::get_id()), txn_id_++);
  48. assert(strlen(name) < 64 - 1);
  49. assert(txn_->SetName(name).ok());
  50. // Take a snapshot if set_snapshot was not set or with 50% change otherwise
  51. bool take_snapshot = txn_->GetSnapshot() == nullptr || rand_->OneIn(2);
  52. if (take_snapshot) {
  53. txn_->SetSnapshot();
  54. read_options_.snapshot = txn_->GetSnapshot();
  55. }
  56. auto res = DoInsert(db, txn_, false);
  57. if (take_snapshot) {
  58. read_options_.snapshot = nullptr;
  59. }
  60. return res;
  61. }
  62. bool RandomTransactionInserter::OptimisticTransactionDBInsert(
  63. OptimisticTransactionDB* db,
  64. const OptimisticTransactionOptions& txn_options) {
  65. optimistic_txn_ =
  66. db->BeginTransaction(write_options_, txn_options, optimistic_txn_);
  67. return DoInsert(db, optimistic_txn_, true);
  68. }
  69. bool RandomTransactionInserter::DBInsert(DB* db) {
  70. return DoInsert(db, nullptr, false);
  71. }
  72. Status RandomTransactionInserter::DBGet(
  73. DB* db, Transaction* txn, ReadOptions& read_options, uint16_t set_i,
  74. uint64_t ikey, bool get_for_update, uint64_t* int_value,
  75. std::string* full_key, bool* unexpected_error) {
  76. Status s;
  77. // Five digits (since the largest uint16_t is 65535) plus the NUL
  78. // end char.
  79. char prefix_buf[6] = {0};
  80. // Pad prefix appropriately so we can iterate over each set
  81. assert(set_i + 1 <= 9999);
  82. snprintf(prefix_buf, sizeof(prefix_buf), "%.4u", set_i + 1);
  83. // key format: [SET#][random#]
  84. std::string skey = std::to_string(ikey);
  85. Slice base_key(skey);
  86. *full_key = std::string(prefix_buf) + base_key.ToString();
  87. Slice key(*full_key);
  88. std::string value;
  89. if (txn != nullptr) {
  90. if (get_for_update) {
  91. s = txn->GetForUpdate(read_options, key, &value);
  92. } else {
  93. s = txn->Get(read_options, key, &value);
  94. }
  95. } else {
  96. s = db->Get(read_options, key, &value);
  97. }
  98. if (s.ok()) {
  99. // Found key, parse its value
  100. *int_value = std::stoull(value);
  101. if (*int_value == 0 || *int_value == ULONG_MAX) {
  102. *unexpected_error = true;
  103. fprintf(stderr, "Get returned unexpected value: %s\n", value.c_str());
  104. s = Status::Corruption();
  105. }
  106. } else if (s.IsNotFound()) {
  107. // Have not yet written to this key, so assume its value is 0
  108. *int_value = 0;
  109. s = Status::OK();
  110. }
  111. return s;
  112. }
  113. bool RandomTransactionInserter::DoInsert(DB* db, Transaction* txn,
  114. bool is_optimistic) {
  115. Status s;
  116. WriteBatch batch;
  117. // pick a random number to use to increment a key in each set
  118. uint64_t incr = (rand_->Next() % 100) + 1;
  119. bool unexpected_error = false;
  120. std::vector<uint16_t> set_vec(num_sets_);
  121. std::iota(set_vec.begin(), set_vec.end(), static_cast<uint16_t>(0));
  122. RandomShuffle(set_vec.begin(), set_vec.end());
  123. // For each set, pick a key at random and increment it
  124. for (uint16_t set_i : set_vec) {
  125. uint64_t int_value = 0;
  126. std::string full_key;
  127. uint64_t rand_key = rand_->Next() % num_keys_;
  128. const bool get_for_update = txn ? rand_->OneIn(2) : false;
  129. s = DBGet(db, txn, read_options_, set_i, rand_key, get_for_update,
  130. &int_value, &full_key, &unexpected_error);
  131. Slice key(full_key);
  132. if (!s.ok()) {
  133. // Optimistic transactions should never return non-ok status here.
  134. // Non-optimistic transactions may return write-coflict/timeout errors.
  135. if (is_optimistic || !(s.IsBusy() || s.IsTimedOut() || s.IsTryAgain())) {
  136. fprintf(stderr, "Get returned an unexpected error: %s\n",
  137. s.ToString().c_str());
  138. unexpected_error = true;
  139. }
  140. break;
  141. }
  142. if (s.ok()) {
  143. // Increment key
  144. std::string sum = std::to_string(int_value + incr);
  145. if (txn != nullptr) {
  146. if ((set_i % 4) != 0) {
  147. s = txn->SingleDelete(key);
  148. } else {
  149. s = txn->Delete(key);
  150. }
  151. if (!get_for_update && (s.IsBusy() || s.IsTimedOut())) {
  152. // If the initial get was not for update, then the key is not locked
  153. // before put and put could fail due to concurrent writes.
  154. break;
  155. } else if (!s.ok()) {
  156. // Since we did a GetForUpdate, SingleDelete should not fail.
  157. fprintf(stderr, "SingleDelete returned an unexpected error: %s\n",
  158. s.ToString().c_str());
  159. unexpected_error = true;
  160. }
  161. s = txn->Put(key, sum);
  162. if (!s.ok()) {
  163. // Since we did a GetForUpdate, Put should not fail.
  164. fprintf(stderr, "Put returned an unexpected error: %s\n",
  165. s.ToString().c_str());
  166. unexpected_error = true;
  167. }
  168. } else {
  169. batch.Put(key, sum);
  170. }
  171. bytes_inserted_ += key.size() + sum.size();
  172. }
  173. if (txn != nullptr) {
  174. ROCKS_LOG_DEBUG(db->GetDBOptions().info_log,
  175. "Insert (%s) %s snap: %" PRIu64 " key:%s value: %" PRIu64
  176. "+%" PRIu64 "=%" PRIu64,
  177. txn->GetName().c_str(), s.ToString().c_str(),
  178. txn->GetSnapshot()->GetSequenceNumber(), full_key.c_str(),
  179. int_value, incr, int_value + incr);
  180. }
  181. }
  182. if (s.ok()) {
  183. if (txn != nullptr) {
  184. bool with_prepare = !is_optimistic && !rand_->OneIn(10);
  185. if (with_prepare) {
  186. // Also try commit without prepare
  187. s = txn->Prepare();
  188. if (!s.ok()) {
  189. fprintf(stderr, "Prepare returned an unexpected error: %s\n",
  190. s.ToString().c_str());
  191. }
  192. assert(s.ok());
  193. ROCKS_LOG_DEBUG(db->GetDBOptions().info_log,
  194. "Prepare of %" PRIu64 " %s (%s)", txn->GetId(),
  195. s.ToString().c_str(), txn->GetName().c_str());
  196. if (rand_->OneIn(20)) {
  197. // This currently only tests the mechanics of writing commit time
  198. // write batch so the exact values would not matter.
  199. s = txn_->GetCommitTimeWriteBatch()->Put("cat", "dog");
  200. assert(s.ok());
  201. }
  202. db->GetDBOptions().env->SleepForMicroseconds(
  203. static_cast<int>(cmt_delay_ms_ * 1000));
  204. }
  205. if (!rand_->OneIn(20)) {
  206. s = txn->Commit();
  207. assert(!with_prepare || s.ok());
  208. ROCKS_LOG_DEBUG(db->GetDBOptions().info_log,
  209. "Commit of %" PRIu64 " %s (%s)", txn->GetId(),
  210. s.ToString().c_str(), txn->GetName().c_str());
  211. } else {
  212. // Also try 5% rollback
  213. s = txn->Rollback();
  214. ROCKS_LOG_DEBUG(db->GetDBOptions().info_log,
  215. "Rollback %" PRIu64 " %s %s", txn->GetId(),
  216. txn->GetName().c_str(), s.ToString().c_str());
  217. assert(s.ok());
  218. }
  219. assert(is_optimistic || s.ok());
  220. if (!s.ok()) {
  221. if (is_optimistic) {
  222. // Optimistic transactions can have write-conflict errors on commit.
  223. // Any other error is unexpected.
  224. if (!(s.IsBusy() || s.IsTimedOut() || s.IsTryAgain())) {
  225. unexpected_error = true;
  226. }
  227. } else {
  228. // Non-optimistic transactions should only fail due to expiration
  229. // or write failures. For testing purproses, we do not expect any
  230. // write failures.
  231. if (!s.IsExpired()) {
  232. unexpected_error = true;
  233. }
  234. }
  235. if (unexpected_error) {
  236. fprintf(stderr, "Commit returned an unexpected error: %s\n",
  237. s.ToString().c_str());
  238. }
  239. }
  240. } else {
  241. s = db->Write(write_options_, &batch);
  242. if (!s.ok()) {
  243. unexpected_error = true;
  244. fprintf(stderr, "Write returned an unexpected error: %s\n",
  245. s.ToString().c_str());
  246. }
  247. }
  248. } else {
  249. if (txn != nullptr) {
  250. assert(txn->Rollback().ok());
  251. ROCKS_LOG_DEBUG(db->GetDBOptions().info_log, "Error %s for txn %s",
  252. s.ToString().c_str(), txn->GetName().c_str());
  253. }
  254. }
  255. if (s.ok()) {
  256. success_count_++;
  257. } else {
  258. failure_count_++;
  259. }
  260. last_status_ = s;
  261. // return success if we didn't get any unexpected errors
  262. return !unexpected_error;
  263. }
  264. // Verify that the sum of the keys in each set are equal
  265. Status RandomTransactionInserter::Verify(DB* db, uint16_t num_sets,
  266. uint64_t num_keys_per_set,
  267. bool take_snapshot, Random64* rand,
  268. uint64_t delay_ms) {
  269. // delay_ms is the delay between taking a snapshot and doing the reads. It
  270. // emulates reads from a long-running backup job.
  271. assert(delay_ms == 0 || take_snapshot);
  272. uint64_t prev_total = 0;
  273. uint32_t prev_i = 0;
  274. bool prev_assigned = false;
  275. ReadOptions roptions;
  276. if (take_snapshot) {
  277. roptions.snapshot = db->GetSnapshot();
  278. db->GetDBOptions().env->SleepForMicroseconds(
  279. static_cast<int>(delay_ms * 1000));
  280. }
  281. std::vector<uint16_t> set_vec(num_sets);
  282. std::iota(set_vec.begin(), set_vec.end(), static_cast<uint16_t>(0));
  283. RandomShuffle(set_vec.begin(), set_vec.end());
  284. // For each set of keys with the same prefix, sum all the values
  285. for (uint16_t set_i : set_vec) {
  286. // Five digits (since the largest uint16_t is 65535) plus the NUL
  287. // end char.
  288. char prefix_buf[6];
  289. assert(set_i + 1 <= 9999);
  290. snprintf(prefix_buf, sizeof(prefix_buf), "%.4u", set_i + 1);
  291. uint64_t total = 0;
  292. // Use either point lookup or iterator. Point lookups are slower so we use
  293. // it less often.
  294. const bool use_point_lookup =
  295. num_keys_per_set != 0 && rand && rand->OneIn(10);
  296. if (use_point_lookup) {
  297. ReadOptions read_options;
  298. for (uint64_t k = 0; k < num_keys_per_set; k++) {
  299. std::string dont_care;
  300. uint64_t int_value = 0;
  301. bool unexpected_error = false;
  302. const bool FOR_UPDATE = false;
  303. Status s = DBGet(db, nullptr, roptions, set_i, k, FOR_UPDATE,
  304. &int_value, &dont_care, &unexpected_error);
  305. assert(s.ok());
  306. assert(!unexpected_error);
  307. total += int_value;
  308. }
  309. } else { // user iterators
  310. Iterator* iter = db->NewIterator(roptions);
  311. for (iter->Seek(Slice(prefix_buf, 4)); iter->Valid(); iter->Next()) {
  312. Slice key = iter->key();
  313. // stop when we reach a different prefix
  314. if (key.ToString().compare(0, 4, prefix_buf) != 0) {
  315. break;
  316. }
  317. Slice value = iter->value();
  318. uint64_t int_value = std::stoull(value.ToString());
  319. if (int_value == 0 || int_value == ULONG_MAX) {
  320. fprintf(stderr, "Iter returned unexpected value: %s\n",
  321. value.ToString().c_str());
  322. return Status::Corruption();
  323. }
  324. ROCKS_LOG_DEBUG(
  325. db->GetDBOptions().info_log,
  326. "VerifyRead at %" PRIu64 " (%" PRIu64 "): %.*s value: %" PRIu64,
  327. roptions.snapshot ? roptions.snapshot->GetSequenceNumber() : 0ul,
  328. roptions.snapshot
  329. ? ((SnapshotImpl*)roptions.snapshot)->min_uncommitted_
  330. : 0ul,
  331. static_cast<int>(key.size()), key.data(), int_value);
  332. total += int_value;
  333. }
  334. iter->status().PermitUncheckedError();
  335. delete iter;
  336. }
  337. if (prev_assigned && total != prev_total) {
  338. db->GetDBOptions().info_log->Flush();
  339. fprintf(stdout,
  340. "RandomTransactionVerify found inconsistent totals using "
  341. "pointlookup? %d "
  342. "Set[%" PRIu32 "]: %" PRIu64 ", Set[%" PRIu32 "]: %" PRIu64
  343. " at snapshot %" PRIu64 "\n",
  344. use_point_lookup, prev_i, prev_total, set_i, total,
  345. roptions.snapshot ? roptions.snapshot->GetSequenceNumber() : 0ul);
  346. fflush(stdout);
  347. return Status::Corruption();
  348. } else {
  349. ROCKS_LOG_DEBUG(
  350. db->GetDBOptions().info_log,
  351. "RandomTransactionVerify pass pointlookup? %d total: %" PRIu64
  352. " snap: %" PRIu64,
  353. use_point_lookup, total,
  354. roptions.snapshot ? roptions.snapshot->GetSequenceNumber() : 0ul);
  355. }
  356. prev_total = total;
  357. prev_i = set_i;
  358. prev_assigned = true;
  359. }
  360. if (take_snapshot) {
  361. db->ReleaseSnapshot(roptions.snapshot);
  362. }
  363. return Status::OK();
  364. }
  365. } // namespace ROCKSDB_NAMESPACE