master
c 78 lines 1.94 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 #include "boot_id.h"
4 #include "libnetdata/libnetdata.h"
5
6 static ND_UUID cached_boot_id = { 0 };
7 static SPINLOCK spinlock = SPINLOCK_INITIALIZER;
8
9 #if defined(OS_LINUX)
10
11 static ND_UUID get_boot_id(void) {
12 ND_UUID boot_id = { 0 };
13 char buf[UUID_STR_LEN];
14
15 char filename[FILENAME_MAX + 1];
16 snprintfz(filename, sizeof(filename), "%s/proc/sys/kernel/random/boot_id",
17 netdata_configured_host_prefix ? netdata_configured_host_prefix : "");
18
19 // Try reading the official boot_id first
20 if (read_txt_file(filename, buf, sizeof(buf)) == 0) {
21 if (uuid_parse(trim(buf), boot_id.uuid) == 0)
22 return boot_id;
23 }
24
25 // Fallback to boottime-based ID
26 time_t boottime = os_boottime();
27 if(boottime > 0) {
28 boot_id.parts.low64 = (uint64_t)boottime;
29 // parts.hig64 remains 0 to indicate this is a synthetic boot_id
30 }
31
32 return boot_id;
33 }
34
35 #else // !OS_LINUX
36
37 static ND_UUID get_boot_id(void) {
38 ND_UUID boot_id = { 0 };
39
40 time_t boottime = os_boottime();
41 if(boottime > 0) {
42 boot_id.parts.low64 = (uint64_t)boottime;
43 // parts.hig64 remains 0 to indicate this is a synthetic boot_id
44 }
45
46 return boot_id;
47 }
48
49 #endif // OS_LINUX
50
51 ND_UUID os_boot_id(void) {
52 // Fast path - return cached value if available
53 if(!UUIDiszero(cached_boot_id))
54 return cached_boot_id;
55
56 spinlock_lock(&spinlock);
57
58 // Check again under lock in case another thread set it
59 if(UUIDiszero(cached_boot_id)) {
60 cached_boot_id = get_boot_id();
61 }
62
63 spinlock_unlock(&spinlock);
64 return cached_boot_id;
65 }
66
67 bool os_boot_ids_match(ND_UUID a, ND_UUID b) {
68 if(UUIDeq(a, b))
69 return true;
70
71 if(a.parts.hig64 == 0 && b.parts.hig64 == 0) {
72 uint64_t diff = a.parts.low64 > b.parts.low64 ? a.parts.low64 - b.parts.low64 : b.parts.low64 - a.parts.low64;
73 if(diff <= 3)
74 return true;
75 }
76
77 return false;
78 }