aboutsummaryrefslogtreecommitdiff
path: root/src/config.rs
blob: 5a92a9adea55eae0267d2c400b87cc8467757de2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use std::sync::LazyLock;

use anyhow::Result;
use confique::Config;
use opentelemetry_otlp::Protocol;
use crate::s_log::*;

#[derive(Config)]
pub struct CspyConfig {
	#[config(env = "CSPY_DOCKER_SOCKET")]
	pub docker_socket: Option<String>,

	#[config(env = "CSPY_OTLP_PROTO", default = "httpbinary", deserialize_with = crate::config::deser_protocol)]
	pub otlp_protocol: Protocol,

	#[config(env = "CSPY_OTLP_ENDPOINT")]
	pub otlp_endpoint: Option<String>,

	#[config(env = "CSPY_OTLP_INTERVAL")]
	pub otlp_export_interval: Option<u64>,
}

pub static CONFIG: LazyLock<CspyConfig> = LazyLock::new(|| {
	let cfg_loc = std::env::var("CSPY_CONFIG");
	let cfg_loc = cfg_loc
		.as_deref()
		.ok()
		.unwrap_or("/etc/containerspy/config.json");

	let cfg = CspyConfig::builder().env().file(cfg_loc).load().unwrap();

	info("Loaded config at startup", [
		("docker_socket", &*format!("{:?}", cfg.docker_socket)),
		("otlp_protocol", &*format!("{:?}", cfg.otlp_protocol)),
		("otlp_endpoint", &*format!("{:?}", cfg.otlp_endpoint)),
		("otlp_export_interval", &*format!("{:?}", cfg.otlp_export_interval)),
	]);
	
	cfg
});

/// deserialization boilerplate
struct ProtoDeserVisitor;

/// deserialization boilerplate
impl confique::serde::de::Visitor<'_> for ProtoDeserVisitor {
	type Value = Protocol;

	fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
		formatter.write_str(r#""httpbinary", "httpjson", or "grpc"."#)
	}

	fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
	where
		E: confique::serde::de::Error,
	{
		Ok(match v {
			"httpbinary" => Protocol::HttpBinary,
			"httpjson" => Protocol::HttpJson,
			"grpc" => Protocol::Grpc,
			&_ => {
				return Err(E::custom(format!(
					"{v} is not a valid OTLP protocol, valid options are httpbinary, httpjson, or grpc."
				)))
			}
		})
	}
}

/// deserialization boilerplate
fn deser_protocol<'de, D: confique::serde::Deserializer<'de>>(d: D) -> Result<Protocol, D::Error> {
	d.deserialize_str(ProtoDeserVisitor)
}