transaction_test_util.cc 13 KB

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