A new bif unique_id(prefix) that returns a string that's unique across

Bro instaces with high probablity.

"prefix" is a string that will be prepended to the returned ID.
This commit is contained in:
Robin Sommer 2011-06-07 17:28:20 -07:00
parent 4bdb94955d
commit 8266709e20
10 changed files with 96 additions and 59 deletions

View file

@ -344,15 +344,27 @@ template<class T> int atoi_n(int len, const char* s, const char** end, int base,
template int atoi_n<int>(int len, const char* s, const char** end, int base, int& result);
template int atoi_n<int64_t>(int len, const char* s, const char** end, int base, int64_t& result);
char* uitoa_n(uint64 value, char* str, int n, int base)
char* uitoa_n(uint64 value, char* str, int n, int base, const char* prefix)
{
static char dig[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
assert(n);
int i = 0;
uint64 v;
char* p, *q;
char c;
if ( prefix )
{
strncpy(str, prefix, n);
str[n-1] = '\0';
i += strlen(prefix);
}
if ( i >= n )
return str;
v = value;
do {
@ -1122,6 +1134,56 @@ int time_compare(struct timeval* tv_a, struct timeval* tv_b)
return tv_a->tv_sec - tv_b->tv_sec;
}
static uint64 uid_counter; // Counter for unique IDs.
static uint64 uid_instance; // Instance ID, computed once.
uint64 calculate_unique_id()
{
if ( uid_instance == 0 )
{
// This is the first time we need a UID.
if ( ! have_random_seed() )
{
// If we don't need deterministic output (as
// indicated by a set seed), we calculate the
// instance ID by hashing something likely to be
// globally unique.
struct {
char hostname[128];
struct timeval time;
pid_t pid;
int rnd;
} unique;
gethostname(unique.hostname, 128);
unique.hostname[sizeof(unique.hostname)-1] = '\0';
gettimeofday(&unique.time, 0);
unique.pid = getpid();
unique.rnd = bro_random();
uid_instance = HashKey::HashBytes(&unique, sizeof(unique));
++uid_instance; // Now it's larger than zero.
}
else
// Generate determistic UIDs.
uid_instance = 1;
}
// Now calculate the unique ID.
struct {
uint64 counter;
hash_t instance;
} key;
key.counter = ++uid_counter;
key.instance = uid_instance;
uint64_t h = HashKey::HashBytes(&key, sizeof(key));
return h;
}
void out_of_memory(const char* where)
{
fprintf( stderr, "bro: out of memory in %s.\n", where );