Skip to main content

libdd_telemetry/
info.rs

1// Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/
2// SPDX-License-Identifier: Apache-2.0
3
4pub mod os {
5    #[cfg(unix)]
6    use std::ffi::CStr;
7
8    // TODO: this function will call API's (fargate, k8s, etc) in the future to get to real host API
9    #[cfg(not(target_arch = "wasm32"))]
10    pub fn real_hostname() -> anyhow::Result<String> {
11        Ok(sys_info::hostname()?)
12    }
13
14    #[cfg(target_arch = "wasm32")]
15    pub fn real_hostname() -> anyhow::Result<String> {
16        anyhow::bail!("hostname not available on wasm")
17    }
18
19    pub const fn os_name() -> &'static str {
20        std::env::consts::OS
21    }
22
23    pub const fn architecture() -> &'static str {
24        std::env::consts::ARCH
25    }
26
27    #[cfg(not(target_arch = "wasm32"))]
28    pub fn os_version() -> anyhow::Result<String> {
29        sys_info::os_release().map_err(|e| e.into())
30    }
31
32    #[cfg(target_arch = "wasm32")]
33    pub fn os_version() -> anyhow::Result<String> {
34        anyhow::bail!("os_version not available on wasm")
35    }
36
37    #[cfg(not(target_arch = "wasm32"))]
38    pub fn os_type() -> Option<String> {
39        sys_info::os_type().ok()
40    }
41
42    #[cfg(target_arch = "wasm32")]
43    pub fn os_type() -> Option<String> {
44        None
45    }
46
47    #[cfg(not(target_arch = "wasm32"))]
48    pub fn os_release() -> Option<String> {
49        sys_info::os_release().ok()
50    }
51
52    #[cfg(target_arch = "wasm32")]
53    pub fn os_release() -> Option<String> {
54        None
55    }
56
57    /// Get string similar to `uname -a`'s output
58    ///
59    /// # Safety
60    ///   Unsafe because of FFI, libc's uname only fails if struct utsname is
61    ///   malformed, considering we `zeroed` it, it virtually cannot be
62    ///   malformed. All in all pretty safe
63    #[cfg(unix)]
64    pub unsafe fn uname() -> Option<String> {
65        let mut n = std::mem::zeroed();
66        match libc::uname(&mut n) {
67            0 => Some(
68                CStr::from_ptr(n.version.as_ptr())
69                    .to_string_lossy()
70                    .into_owned(),
71            ),
72            _ => None,
73        }
74    }
75}