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    #[cfg(not(target_arch = "wasm32"))]
24    pub fn os_version() -> anyhow::Result<String> {
25        sys_info::os_release().map_err(|e| e.into())
26    }
27
28    #[cfg(target_arch = "wasm32")]
29    pub fn os_version() -> anyhow::Result<String> {
30        anyhow::bail!("os_version not available on wasm")
31    }
32
33    #[cfg(not(target_arch = "wasm32"))]
34    pub fn os_type() -> Option<String> {
35        sys_info::os_type().ok()
36    }
37
38    #[cfg(target_arch = "wasm32")]
39    pub fn os_type() -> Option<String> {
40        None
41    }
42
43    #[cfg(not(target_arch = "wasm32"))]
44    pub fn os_release() -> Option<String> {
45        sys_info::os_release().ok()
46    }
47
48    #[cfg(target_arch = "wasm32")]
49    pub fn os_release() -> Option<String> {
50        None
51    }
52
53    /// Get string similar to `uname -a`'s output
54    ///
55    /// # Safety
56    ///   Unsafe because of FFI, libc's uname only fails if struct utsname is
57    ///   malformed, considering we `zeroed` it, it virtually cannot be
58    ///   malformed. All in all pretty safe
59    #[cfg(unix)]
60    pub unsafe fn uname() -> Option<String> {
61        let mut n = std::mem::zeroed();
62        match libc::uname(&mut n) {
63            0 => Some(
64                CStr::from_ptr(n.version.as_ptr())
65                    .to_string_lossy()
66                    .into_owned(),
67            ),
68            _ => None,
69        }
70    }
71}