From 52b2fbe9705739fd5f03099011f652775ab3285f Mon Sep 17 00:00:00 2001 From: Moti Cohen Date: Sun, 30 Jan 2022 16:39:23 +0200 Subject: [PATCH] Improve srand entropy (and fix Sentinel failures) (#10197) As Sentinel relies upon consensus algorithm, all sentinel instances, randomize a time to initiate their next attempt to become the leader of the group. But time after time, all raffled the same value. The problem is in the line `srand(time(NULL)^getpid())` such that all spinned up containers get same time (in seconds) and same pid which is always 1. Added material `tv_usec` and verify that even consecutive calls brings different values and makes the difference. --- src/server.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/server.c b/src/server.c index 146e129540..565cd9467f 100644 --- a/src/server.c +++ b/src/server.c @@ -6585,9 +6585,12 @@ int main(int argc, char **argv) { setlocale(LC_COLLATE,""); tzset(); /* Populates 'timezone' global. */ zmalloc_set_oom_handler(redisOutOfMemoryHandler); - srand(time(NULL)^getpid()); - srandom(time(NULL)^getpid()); + + /* To achieve entropy, in case of containers, their time() and getpid() can + * be the same. But value of tv_usec is fast enough to make the difference */ gettimeofday(&tv,NULL); + srand(time(NULL)^getpid()^tv.tv_usec); + srandom(time(NULL)^getpid()^tv.tv_usec); init_genrand64(((long long) tv.tv_sec * 1000000 + tv.tv_usec) ^ getpid()); crc64_init();