]> git.proxmox.com Git - ceph.git/blob - ceph/src/jaegertracing/opentelemetry-cpp/sdk/src/common/random.cc
update ceph source to reef 18.1.2
[ceph.git] / ceph / src / jaegertracing / opentelemetry-cpp / sdk / src / common / random.cc
1
2 // Copyright The OpenTelemetry Authors
3 // SPDX-License-Identifier: Apache-2.0
4
5 #include "src/common/random.h"
6 #include "src/common/platform/fork.h"
7
8 #include <cstring>
9 #include <random>
10
11 OPENTELEMETRY_BEGIN_NAMESPACE
12 namespace sdk
13 {
14 namespace common
15 {
16 // Wraps a thread_local random number generator, but adds a fork handler so that
17 // the generator will be correctly seeded after forking.
18 //
19 // See https://stackoverflow.com/q/51882689/4447365 and
20 // https://github.com/opentracing-contrib/nginx-opentracing/issues/52
21 namespace
22 {
23 class TlsRandomNumberGenerator
24 {
25 public:
26 TlsRandomNumberGenerator() noexcept
27 {
28 Seed();
29 platform::AtFork(nullptr, nullptr, OnFork);
30 }
31
32 static FastRandomNumberGenerator &engine() noexcept { return engine_; }
33
34 private:
35 static thread_local FastRandomNumberGenerator engine_;
36
37 static void OnFork() noexcept { Seed(); }
38
39 static void Seed() noexcept
40 {
41 std::random_device random_device;
42 std::seed_seq seed_seq{random_device(), random_device(), random_device(), random_device()};
43 engine_.seed(seed_seq);
44 }
45 };
46
47 thread_local FastRandomNumberGenerator TlsRandomNumberGenerator::engine_{};
48 } // namespace
49
50 FastRandomNumberGenerator &Random::GetRandomNumberGenerator() noexcept
51 {
52 static thread_local TlsRandomNumberGenerator random_number_generator{};
53 return TlsRandomNumberGenerator::engine();
54 }
55
56 uint64_t Random::GenerateRandom64() noexcept
57 {
58 return GetRandomNumberGenerator()();
59 }
60
61 void Random::GenerateRandomBuffer(opentelemetry::nostd::span<uint8_t> buffer) noexcept
62 {
63 auto buf_size = buffer.size();
64
65 for (size_t i = 0; i < buf_size; i += sizeof(uint64_t))
66 {
67 uint64_t value = GenerateRandom64();
68 if (i + sizeof(uint64_t) <= buf_size)
69 {
70 memcpy(&buffer[i], &value, sizeof(uint64_t));
71 }
72 else
73 {
74 memcpy(&buffer[i], &value, buf_size - i);
75 }
76 }
77 }
78 } // namespace common
79 } // namespace sdk
80 OPENTELEMETRY_END_NAMESPACE