Apache Mesos
bootid.hpp
Go to the documentation of this file.
1 // Licensed under the Apache License, Version 2.0 (the "License");
2 // you may not use this file except in compliance with the License.
3 // You may obtain a copy of the License at
4 //
5 // http://www.apache.org/licenses/LICENSE-2.0
6 //
7 // Unless required by applicable law or agreed to in writing, software
8 // distributed under the License is distributed on an "AS IS" BASIS,
9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 // See the License for the specific language governing permissions and
11 // limitations under the License.
12 
13 #ifndef __STOUT_OS_POSIX_BOOTID_HPP__
14 #define __STOUT_OS_POSIX_BOOTID_HPP__
15 
16 #include <string>
17 
18 #include <sys/time.h>
19 
20 #include <stout/error.hpp>
21 #include <stout/stringify.hpp>
22 #include <stout/strings.hpp>
23 #include <stout/try.hpp>
24 
25 #include <stout/os/read.hpp>
26 #if defined(__APPLE__) || defined(__FreeBSD__)
27 #include <stout/os/sysctl.hpp>
28 #endif // __APPLE__ || __FreeBSD__
29 
30 
31 namespace os {
32 
34 {
35 #ifdef __linux__
36  Try<std::string> read = os::read("/proc/sys/kernel/random/boot_id");
37  if (read.isError()) {
38  return read;
39  }
40  return strings::trim(read.get());
41 #elif defined(__APPLE__) || defined(__FreeBSD__)
42  // For OS X, we use the boot time in seconds as a unique boot id.
43  // Although imperfect, this works quite well in practice. NOTE: we can't use
44  // milliseconds here instead of seconds because the relatively high
45  // imprecision of millisecond resolution would cause `bootId` to return a
46  // different number nearly every time it was called.
47  Try<timeval> boot_time = os::sysctl(CTL_KERN, KERN_BOOTTIME).time();
48  if (boot_time.isError()) {
49  return Error(boot_time.error());
50  }
51  return stringify(boot_time->tv_sec);
52 #else
53  return Error("Not implemented");
54 #endif
55 }
56 
57 } // namespace os {
58 
59 #endif // __STOUT_OS_POSIX_BOOTID_HPP__
Try< std::string > bootId()
Definition: bootid.hpp:33
Definition: errorbase.hpp:36
T & get()&
Definition: try.hpp:80
Definition: check.hpp:33
Definition: posix_signalhandler.hpp:23
Result< std::string > read(int_fd fd, size_t size)
Definition: read.hpp:55
bool isError() const
Definition: try.hpp:78
Definition: sysctl.hpp:59
std::string stringify(int flags)
std::string trim(const std::string &from, Mode mode=ANY, const std::string &chars=WHITESPACE)
Definition: strings.hpp:67
Try< timeval > time() const
Definition: sysctl.hpp:218