ClickHouse/src/Common/randomSeed.cpp

47 lines
1.2 KiB
C++
Raw Normal View History

#include <ctime>
2020-02-17 14:27:09 +00:00
#include <unistd.h>
2016-07-31 03:53:16 +00:00
#include <sys/types.h>
#include <Common/Exception.h>
#include <Common/randomSeed.h>
2018-03-03 15:36:20 +00:00
#include <Common/SipHash.h>
2021-10-02 07:13:14 +00:00
#include <base/getThreadId.h>
#include <base/types.h>
2016-07-31 03:53:16 +00:00
2022-04-20 16:15:21 +00:00
#if defined(__linux__)
#include <sys/utsname.h>
#endif
2016-07-31 03:53:16 +00:00
namespace DB
{
namespace ErrorCodes
{
extern const int CANNOT_CLOCK_GETTIME;
}
2016-07-31 03:53:16 +00:00
}
DB::UInt64 randomSeed()
2016-07-31 03:53:16 +00:00
{
struct timespec times;
2020-09-24 16:35:17 +00:00
if (clock_gettime(CLOCK_MONOTONIC, &times))
DB::throwFromErrno("Cannot clock_gettime.", DB::ErrorCodes::CANNOT_CLOCK_GETTIME);
2018-03-03 15:36:20 +00:00
/// Not cryptographically secure as time, pid and stack address can be predictable.
SipHash hash;
hash.update(times.tv_nsec);
hash.update(times.tv_sec);
2020-09-24 16:35:17 +00:00
hash.update(getThreadId());
2022-04-20 16:15:21 +00:00
/// 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(sysinfo);
#endif
2018-03-03 15:36:20 +00:00
return hash.get64();
2016-07-31 03:53:16 +00:00
}