1 /* 2 * Copyright (C) 2023 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #include "ShardOffsetProvider.h" 18 19 #include <errno.h> 20 #include <sys/random.h> 21 #include <unistd.h> 22 23 #include <chrono> 24 25 namespace android { 26 namespace os { 27 namespace statsd { 28 ShardOffsetProvider()29ShardOffsetProvider::ShardOffsetProvider() { 30 unsigned int seed = 0; 31 // getrandom() reads bytes from urandom source into buf. If getrandom() 32 // is unable to read from urandom source, then it returns -1 and we set 33 // our seed to be time(nullptr) as a fallback. 34 if (TEMP_FAILURE_RETRY( 35 getrandom(static_cast<void*>(&seed), sizeof(unsigned int), GRND_NONBLOCK)) < 0) { 36 seed = time(nullptr); 37 } 38 srand(seed); 39 mShardOffset = rand(); 40 } 41 getInstance()42ShardOffsetProvider& ShardOffsetProvider::getInstance() { 43 static ShardOffsetProvider sShardOffsetProvider; 44 return sShardOffsetProvider; 45 } 46 47 } // namespace statsd 48 } // namespace os 49 } // namespace android 50