unique_id_gen.cc 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. // Copyright (c) Facebook, Inc. and its affiliates. 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 "env/unique_id_gen.h"
  6. #include <algorithm>
  7. #include <array>
  8. #include <atomic>
  9. #include <cstdint>
  10. #include <cstring>
  11. #include <random>
  12. #include "port/lang.h"
  13. #include "port/port.h"
  14. #include "rocksdb/env.h"
  15. #include "rocksdb/version.h"
  16. #include "util/hash.h"
  17. #ifdef __SSE4_2__
  18. #ifdef _WIN32
  19. #include <intrin.h>
  20. #define _rdtsc() __rdtsc()
  21. #else
  22. #include <x86intrin.h>
  23. #endif
  24. #else
  25. #include "rocksdb/system_clock.h"
  26. #endif
  27. namespace ROCKSDB_NAMESPACE {
  28. namespace {
  29. struct GenerateRawUniqueIdOpts {
  30. Env* env = Env::Default();
  31. bool exclude_port_uuid = false;
  32. bool exclude_env_details = false;
  33. bool exclude_random_device = false;
  34. };
  35. // Each of these "tracks" below should be sufficient for generating 128 bits
  36. // of entropy, after hashing the raw bytes. The tracks are separable for
  37. // testing purposes, but in production we combine as many tracks as possible
  38. // to ensure quality results even if some environments have degraded
  39. // capabilities or quality in some APIs.
  40. //
  41. // This approach has not been validated for use in cryptography. The goal is
  42. // generating globally unique values with high probability without coordination
  43. // between instances.
  44. //
  45. // Linux performance: EntropyTrackRandomDevice is much faster than
  46. // EntropyTrackEnvDetails, which is much faster than EntropyTrackPortUuid.
  47. struct EntropyTrackPortUuid {
  48. std::array<char, 36> uuid;
  49. void Populate(const GenerateRawUniqueIdOpts& opts) {
  50. if (opts.exclude_port_uuid) {
  51. return;
  52. }
  53. std::string s;
  54. port::GenerateRfcUuid(&s);
  55. if (s.size() >= uuid.size()) {
  56. std::copy_n(s.begin(), uuid.size(), uuid.begin());
  57. }
  58. }
  59. };
  60. struct EntropyTrackEnvDetails {
  61. std::array<char, 64> hostname_buf;
  62. int64_t process_id;
  63. uint64_t thread_id;
  64. int64_t unix_time;
  65. uint64_t nano_time;
  66. void Populate(const GenerateRawUniqueIdOpts& opts) {
  67. if (opts.exclude_env_details) {
  68. return;
  69. }
  70. opts.env->GetHostName(hostname_buf.data(), hostname_buf.size())
  71. .PermitUncheckedError();
  72. process_id = port::GetProcessID();
  73. thread_id = opts.env->GetThreadID();
  74. opts.env->GetCurrentTime(&unix_time).PermitUncheckedError();
  75. nano_time = opts.env->NowNanos();
  76. }
  77. };
  78. struct EntropyTrackRandomDevice {
  79. using RandType = std::random_device::result_type;
  80. static constexpr size_t kNumRandVals =
  81. /* generous bits */ 192U / (8U * sizeof(RandType));
  82. std::array<RandType, kNumRandVals> rand_vals;
  83. void Populate(const GenerateRawUniqueIdOpts& opts) {
  84. if (opts.exclude_random_device) {
  85. return;
  86. }
  87. std::random_device r;
  88. for (auto& val : rand_vals) {
  89. val = r();
  90. }
  91. }
  92. };
  93. struct Entropy {
  94. uint64_t version_identifier;
  95. EntropyTrackRandomDevice et1;
  96. EntropyTrackEnvDetails et2;
  97. EntropyTrackPortUuid et3;
  98. void Populate(const GenerateRawUniqueIdOpts& opts) {
  99. // If we change the format of what goes into the entropy inputs, it's
  100. // conceivable there could be a physical collision in the hash input
  101. // even though they are logically different. This value should change
  102. // if there's a change to the "schema" here, including byte order.
  103. version_identifier = (uint64_t{ROCKSDB_MAJOR} << 32) +
  104. (uint64_t{ROCKSDB_MINOR} << 16) +
  105. uint64_t{ROCKSDB_PATCH};
  106. et1.Populate(opts);
  107. et2.Populate(opts);
  108. et3.Populate(opts);
  109. }
  110. };
  111. void GenerateRawUniqueIdImpl(uint64_t* a, uint64_t* b,
  112. const GenerateRawUniqueIdOpts& opts) {
  113. Entropy e;
  114. std::memset(&e, 0, sizeof(e));
  115. e.Populate(opts);
  116. Hash2x64(reinterpret_cast<const char*>(&e), sizeof(e), a, b);
  117. }
  118. } // namespace
  119. void GenerateRawUniqueId(uint64_t* a, uint64_t* b, bool exclude_port_uuid) {
  120. GenerateRawUniqueIdOpts opts;
  121. opts.exclude_port_uuid = exclude_port_uuid;
  122. assert(!opts.exclude_env_details);
  123. assert(!opts.exclude_random_device);
  124. GenerateRawUniqueIdImpl(a, b, opts);
  125. }
  126. #ifndef NDEBUG
  127. void TEST_GenerateRawUniqueId(uint64_t* a, uint64_t* b, bool exclude_port_uuid,
  128. bool exclude_env_details,
  129. bool exclude_random_device) {
  130. GenerateRawUniqueIdOpts opts;
  131. opts.exclude_port_uuid = exclude_port_uuid;
  132. opts.exclude_env_details = exclude_env_details;
  133. opts.exclude_random_device = exclude_random_device;
  134. GenerateRawUniqueIdImpl(a, b, opts);
  135. }
  136. #endif
  137. void SemiStructuredUniqueIdGen::Reset() {
  138. saved_process_id_ = port::GetProcessID();
  139. GenerateRawUniqueId(&base_upper_, &base_lower_);
  140. counter_ = 0;
  141. }
  142. void SemiStructuredUniqueIdGen::GenerateNext(uint64_t* upper, uint64_t* lower) {
  143. if (port::GetProcessID() == saved_process_id_) {
  144. // Safe to increment the atomic for guaranteed uniqueness within this
  145. // process lifetime. Xor slightly better than +. See
  146. // https://github.com/pdillinger/unique_id
  147. *lower = base_lower_ ^ counter_.fetch_add(1);
  148. *upper = base_upper_;
  149. } else {
  150. // There must have been a fork() or something. Rather than attempting to
  151. // update in a thread-safe way, simply fall back on GenerateRawUniqueId.
  152. GenerateRawUniqueId(upper, lower);
  153. }
  154. }
  155. void UnpredictableUniqueIdGen::Reset() {
  156. for (size_t i = 0; i < pool_.size(); i += 2) {
  157. assert(i + 1 < pool_.size());
  158. uint64_t a, b;
  159. GenerateRawUniqueId(&a, &b);
  160. pool_[i] = a;
  161. pool_[i + 1] = b;
  162. }
  163. }
  164. void UnpredictableUniqueIdGen::GenerateNext(uint64_t* upper, uint64_t* lower) {
  165. uint64_t extra_entropy;
  166. // Use timing information (if available) to add to entropy. (Not a disaster
  167. // if unavailable on some platforms. High performance is important.)
  168. #ifdef __SSE4_2__ // More than enough to guarantee rdtsc instruction
  169. extra_entropy = static_cast<uint64_t>(_rdtsc());
  170. #else
  171. extra_entropy = SystemClock::Default()->NowNanos();
  172. #endif
  173. GenerateNextWithEntropy(upper, lower, extra_entropy);
  174. }
  175. void UnpredictableUniqueIdGen::GenerateNextWithEntropy(uint64_t* upper,
  176. uint64_t* lower,
  177. uint64_t extra_entropy) {
  178. // To efficiently ensure unique inputs to the hash function in the presence
  179. // of multithreading, we do not require atomicity on the whole entropy pool,
  180. // but instead only a piece of it (a 64-bit counter) that is sufficient to
  181. // guarantee uniqueness.
  182. uint64_t count = counter_.fetch_add(1, std::memory_order_relaxed);
  183. uint64_t a = count;
  184. uint64_t b = extra_entropy;
  185. // Invoking the hash function several times avoids copying all the inputs
  186. // to a contiguous, non-atomic buffer.
  187. BijectiveHash2x64(a, b, &a, &b); // Based on XXH128
  188. // In hashing the rest of the pool with that, we don't need to worry about
  189. // races, but use atomic operations for sanitizer-friendliness.
  190. for (size_t i = 0; i < pool_.size(); i += 2) {
  191. assert(i + 1 < pool_.size());
  192. a ^= pool_[i].load(std::memory_order_relaxed);
  193. b ^= pool_[i + 1].load(std::memory_order_relaxed);
  194. BijectiveHash2x64(a, b, &a, &b); // Based on XXH128
  195. }
  196. // Return result
  197. *lower = a;
  198. *upper = b;
  199. // Add some back into pool. We don't really care that there's a race in
  200. // storing the result back and another thread computing the next value.
  201. // It's just an entropy pool.
  202. pool_[count & (pool_.size() - 1)].fetch_add(a, std::memory_order_relaxed);
  203. }
  204. #ifndef NDEBUG
  205. UnpredictableUniqueIdGen::UnpredictableUniqueIdGen(TEST_ZeroInitialized) {
  206. for (auto& p : pool_) {
  207. p.store(0);
  208. }
  209. counter_.store(0);
  210. }
  211. #endif
  212. } // namespace ROCKSDB_NAMESPACE