blob: e1aa56fa811434432d59e4133449bab4d3791cce (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
#include <ctime>
#include <unistd.h>
#include <sys/types.h>
#include <Common/Exception.h>
#include <Common/randomSeed.h>
#include <Common/SipHash.h>
#include <base/getThreadId.h>
#include <base/types.h>
#if defined(__linux__)
#include <sys/utsname.h>
#endif
namespace DB
{
namespace ErrorCodes
{
extern const int CANNOT_CLOCK_GETTIME;
}
}
DB::UInt64 randomSeed()
{
struct timespec times;
if (clock_gettime(CLOCK_MONOTONIC, ×))
DB::throwFromErrno("Cannot clock_gettime.", DB::ErrorCodes::CANNOT_CLOCK_GETTIME);
/// Not cryptographically secure as time, pid and stack address can be predictable.
SipHash hash;
hash.update(times.tv_nsec);
hash.update(times.tv_sec);
hash.update(getThreadId());
/// It makes sense to add something like hostname to avoid seed collision when multiple servers start simultaneously.
/// But randomSeed() must be signal-safe and gethostname and similar functions are not.
/// Let's try to get utsname.nodename using uname syscall (it's signal-safe).
#if defined(__linux__)
struct utsname sysinfo;
if (uname(&sysinfo) == 0)
hash.update<std::identity>(sysinfo);
#endif
return hash.get64();
}
|