redup_bootstrap/telemetry/
service.rs1#[derive(Debug, Clone, PartialEq, Eq, Hash)]
8pub struct Service {
9 name: String,
10 version: String,
11}
12
13impl Service {
14 pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
17 Self {
18 name: name.into(),
19 version: version.into(),
20 }
21 }
22
23 pub fn name(&self) -> &str {
25 &self.name
26 }
27
28 pub fn version(&self) -> &str {
30 &self.version
31 }
32
33 pub(crate) fn metric_prefix(&self) -> String {
36 let mut prefix = String::with_capacity(self.name.len());
37 for character in self.name.chars() {
38 if character.is_ascii_alphanumeric() {
39 prefix.push(character.to_ascii_lowercase());
40 } else {
41 prefix.push('_');
42 }
43 }
44 prefix
45 }
46}
47
48pub(crate) fn hostname() -> String {
50 for path in ["/proc/sys/kernel/hostname", "/etc/hostname"] {
51 if let Ok(name) = std::fs::read_to_string(path)
52 && let Some(name) = name.split_whitespace().next()
53 && !name.is_empty()
54 {
55 return name.to_owned();
56 }
57 }
58 std::env::var("HOSTNAME").unwrap_or_else(|_| "unknown".to_owned())
59}
60
61#[cfg(test)]
62mod tests {
63 use super::{Service, hostname};
64
65 #[test]
66 fn prefix_is_lower_case_with_underscores() {
67 assert_eq!(
68 Service::new("blobpacker", "1").metric_prefix(),
69 "blobpacker"
70 );
71 assert_eq!(
72 Service::new("Distributed.HashIndex", "1").metric_prefix(),
73 "distributed_hashindex"
74 );
75 assert_eq!(
76 Service::new("task-controller", "1").metric_prefix(),
77 "task_controller"
78 );
79 assert_eq!(
80 Service::new("Text Checker", "1").metric_prefix(),
81 "text_checker"
82 );
83 }
84
85 #[test]
86 fn service_keeps_name_and_version() {
87 let service = Service::new("trial", "1.2.3");
88 assert_eq!(service.name(), "trial");
89 assert_eq!(service.version(), "1.2.3");
90 }
91
92 #[test]
93 fn hostname_is_not_empty() {
94 assert!(!hostname().is_empty());
95 }
96}