1
0
Fork 0
nixos-exporter/src/main.rs

260 lines
9.2 KiB
Rust
Raw Normal View History

2022-12-31 00:29:17 +01:00
use axum::{
2023-01-08 20:45:18 +01:00
extract::{State, Query},
2023-01-03 22:13:01 +01:00
http::StatusCode,
2023-03-23 18:43:09 +01:00
response::IntoResponse,
2023-01-03 22:13:01 +01:00
routing::get,
Router,
2022-12-31 00:29:17 +01:00
};
2023-01-04 01:10:30 +01:00
use std::collections::HashMap;
2022-12-31 00:29:17 +01:00
use std::net::SocketAddr;
use std::str::FromStr;
2023-03-25 13:42:58 +01:00
use std::path::PathBuf;
2022-12-31 00:29:17 +01:00
2023-01-08 20:45:18 +01:00
#[derive(Clone, PartialEq)]
2023-01-04 01:10:30 +01:00
enum OperationMode {
2023-01-08 18:07:05 +01:00
None,
2023-01-04 01:10:30 +01:00
Exporter,
Validator,
}
2023-01-08 20:45:18 +01:00
#[derive(Clone)]
struct AppState {
listen: String,
operationmode: OperationMode,
prometheus_url: String,
prometheus_query_tag_template: String,
hydra_url: String,
hydra_job_template: String,
}
impl AppState{
pub fn new() -> Self {
Self {
listen: String::from("[::]:9152"),
operationmode: OperationMode::None,
prometheus_url: String::from(""),
prometheus_query_tag_template: String::from("instance=\"{}\""),
hydra_url: String::from(""),
hydra_job_template: String::from("nixfiles/nixfiles/nixosConfigurations.{}"),
}
}
pub fn is_valid(self) -> bool {
let mut valid = true;
if self.operationmode == OperationMode::None {
println!("operationmode is not set");
valid = false;
}
2023-01-11 21:32:23 +01:00
if self.prometheus_url == String::from("") && self.operationmode == OperationMode::Validator {
2023-01-08 20:45:18 +01:00
println!("Prometheus url is not specified");
valid = false;
}
2023-01-11 21:32:23 +01:00
if self.hydra_url == String::from("") && self.operationmode == OperationMode::Validator {
2023-01-08 20:45:18 +01:00
println!("Hydra url is not specified");
valid = false;
}
return valid;
}
}
2023-03-25 13:42:58 +01:00
#[derive(Clone)]
struct NixStorePath {
hash: String,
name: String,
2023-01-04 01:10:30 +01:00
}
2023-03-25 13:42:58 +01:00
impl NixStorePath {
pub fn from_str_symlink(path: &str) -> Result<Self, String> {
Ok(Self::from_path_buf_symlink(PathBuf::from(path))?)
}
pub fn from_path_buf_symlink(path: PathBuf) -> Result<Self, String> {
Ok(Self::from_path_buf(path.read_link().map_err(|err| err.to_string())?)?)
}
pub fn from_path_buf(path: PathBuf) -> Result<Self, String> {
let store_path_name = path.iter().nth(3)
.ok_or_else(|| String::from("Can't read store path name"))?
.to_str()
.ok_or_else(|| String::from("Failed converting store path name to string"))?
.to_string();
Ok(Self::from_store_path_name(store_path_name)?)
}
pub fn from_store_path_name(store_path_name: String) -> Result<Self, String> {
let (hash, name) = store_path_name
.split_once("-")
.ok_or_else(|| String::from("Failed splitting store path name for hash and name"))?;
Ok(Self {
hash: hash.to_string(),
name: name.to_string(),
})
}
pub fn to_prometheus_metric(self, infix: String) -> Result<String, String> {
return Ok(format!("nixos_{}_hash{{hash=\"{}\"}} 1\nnixos_{}_name{{name=\"{}\"}} 1\n", infix, self.hash, infix, self.name));
}
}
2023-01-08 20:45:18 +01:00
2022-12-31 00:29:17 +01:00
#[tokio::main]
async fn main() {
2023-01-08 20:45:18 +01:00
let mut app_state = AppState::new();
2023-01-03 22:13:01 +01:00
let mut args = std::env::args();
2023-01-08 18:07:05 +01:00
let name = args.next().unwrap();
2023-01-03 22:13:01 +01:00
loop {
let arg = if let Some(arg) = args.next() {
arg
} else {
break;
};
2022-12-31 00:29:17 +01:00
2023-01-03 22:13:01 +01:00
match arg.as_str() {
"--help" | "-h" => {
println!("Prometheus exporter for NixOS systems");
println!("Use --listen <addr:port> bind the web service.");
println!("Output will be on /metrics endpoint. HTTP 500 if something broke while scraping.");
std::process::exit(0);
}
"--listen" => {
2023-01-08 20:45:18 +01:00
app_state.listen = args.next().unwrap();
}
"--prometheus-url" => {
app_state.prometheus_url = args.next().unwrap();
}
"--prometheus-query-tag-template" => {
app_state.prometheus_query_tag_template = args.next().unwrap();
}
"--hydra-url" => {
app_state.hydra_url = args.next().unwrap();
}
"--hydra-job-template" => {
app_state.hydra_job_template = args.next().unwrap();
2023-01-03 22:13:01 +01:00
}
2023-01-04 01:10:30 +01:00
"exporter" => {
2023-01-08 20:45:18 +01:00
app_state.operationmode = OperationMode::Exporter;
2023-01-04 01:10:30 +01:00
}
"validator" => {
2023-01-08 20:45:18 +01:00
app_state.operationmode = OperationMode::Validator;
2023-01-04 01:10:30 +01:00
}
2023-01-03 22:13:01 +01:00
unknown => {
println!("unknown option: {}", unknown);
std::process::exit(1)
}
}
2022-12-31 00:29:17 +01:00
}
2023-01-08 20:45:18 +01:00
if !app_state.clone().is_valid() {
std::process::exit(1);
}
2023-01-04 01:10:30 +01:00
let mut app = Router::new();
2023-01-08 20:45:18 +01:00
if app_state.operationmode == OperationMode::Exporter {
2023-01-04 01:10:30 +01:00
println!("Running NixOS Exporter in Exporter mode");
app = app.route("/metrics", get(metrics));
2023-01-08 20:45:18 +01:00
} else if app_state.operationmode == OperationMode::Validator {
2023-01-04 01:10:30 +01:00
println!("Running NixOS Exporter in Validator mode");
app = app.route("/metrics", get(check));
2023-01-08 18:07:05 +01:00
} else {
println!("Run mode not specified, do {} --help", name);
std::process::exit(1);
};
2022-12-31 00:29:17 +01:00
2023-01-08 20:45:18 +01:00
let app = app.with_state(app_state.clone());
let addr = SocketAddr::from_str(&app_state.listen.clone()).unwrap();
2023-01-03 22:13:01 +01:00
println!("listening on http://{}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
2022-12-31 00:29:17 +01:00
}
async fn metrics() -> Result<(StatusCode, impl IntoResponse), (StatusCode, impl IntoResponse)> {
2023-03-25 13:42:58 +01:00
let nix_store_paths = HashMap::from([
2023-03-25 16:18:36 +01:00
("current_system", NixStorePath::from_str_symlink("/run/current-system")
.map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err))?),
("current_system_kernel", NixStorePath::from_str_symlink("/run/current-system/kernel")
.map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err))?),
("booted_system", NixStorePath::from_str_symlink("/run/booted-system")
.map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err))?),
("booted_system_kernel", NixStorePath::from_str_symlink("/run/booted-system/kernel")
.map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err))?),
2023-03-25 13:42:58 +01:00
]);
let mut out = String::new();
2023-03-25 13:42:58 +01:00
for (infix, nix_store_path) in nix_store_paths.iter() {
out.push_str(nix_store_path.clone().to_prometheus_metric(infix.to_string())
.map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err))?.as_str());
}
2023-03-25 16:18:36 +01:00
out.push_str(format!("nixos_current_system_kernel_is_booted_system_kernel{{}} {}", (
nix_store_paths.get("current_system_kernel").ok_or_else(|| (StatusCode::INTERNAL_SERVER_ERROR, String::from("")))?.hash
== nix_store_paths.get("booted_system_kernel").ok_or_else(|| (StatusCode::INTERNAL_SERVER_ERROR, String::from("")))?.hash
) as i32).as_str()
);
2023-03-23 18:43:09 +01:00
return Ok((
2023-01-04 01:10:30 +01:00
StatusCode::OK,
out,
2023-03-23 18:43:09 +01:00
));
2023-01-04 01:10:30 +01:00
}
2023-03-23 18:43:09 +01:00
async fn check(State(app_state): State<AppState>, Query(params): Query<HashMap<String, String>>) -> Result<(StatusCode, impl IntoResponse), (StatusCode, impl IntoResponse)> {
let target = params.get("target")
.ok_or_else(|| (StatusCode::NOT_FOUND, "specify target"))?;
2023-01-04 01:10:30 +01:00
2023-01-08 20:45:18 +01:00
if target.contains("\"") {
2023-03-23 18:43:09 +01:00
return Err((StatusCode::INTERNAL_SERVER_ERROR, "Invalid target name"));
2023-01-08 20:45:18 +01:00
}
2023-01-04 01:10:30 +01:00
let client = reqwest::Client::new();
2023-03-23 18:43:09 +01:00
let prometheus_req = client.get(format!("{}/api/v1/query?query=nixos_current_system_hash{{{}}}", app_state.prometheus_url, app_state.prometheus_query_tag_template.clone().replace("{}", target)))
2023-01-04 01:10:30 +01:00
.header("Accept", "application/json")
2023-03-23 18:43:09 +01:00
.send().await
.map_err(|_err| (StatusCode::INTERNAL_SERVER_ERROR, "Promehteus can't get reached"))?;
2023-01-04 01:10:30 +01:00
2023-03-23 18:43:09 +01:00
if prometheus_req.status() != reqwest::StatusCode::OK {
return Err((StatusCode::NOT_FOUND, "Target does not exist in Hydra"));
2023-01-04 01:10:30 +01:00
}
2023-03-23 18:43:09 +01:00
let prometheus_body = prometheus_req.json::<serde_json::Value>().await
.map_err(|_err| (StatusCode::INTERNAL_SERVER_ERROR, "Invalid response from Hydra"))?;
2023-01-04 01:10:30 +01:00
2023-03-23 18:43:09 +01:00
let current_system_hash = prometheus_body["data"]["result"][0]["metric"]["hash"].as_str()
.ok_or_else(|| (StatusCode::INTERNAL_SERVER_ERROR, "No buildoutput found in Hydra"))?;
2023-01-04 01:10:30 +01:00
2023-03-23 18:43:09 +01:00
let hydra_req = client.get(format!("{}/job/{}/latest", app_state.hydra_url, app_state.hydra_job_template.clone().replace("{}", target)))
2023-01-04 01:10:30 +01:00
.header("Accept", "application/json")
2023-03-23 18:43:09 +01:00
.send().await
.map_err(|_err| (StatusCode::INTERNAL_SERVER_ERROR, "Hydra can't get reached"))?;
2023-01-04 01:10:30 +01:00
2023-03-23 18:43:09 +01:00
if hydra_req.status() != reqwest::StatusCode::OK {
return Err((StatusCode::NOT_FOUND, "Target does not exist in Hydra"));
2023-01-04 01:10:30 +01:00
}
2023-03-23 18:43:09 +01:00
let hydra_body = hydra_req.json::<serde_json::Value>().await
.map_err(|_err| (StatusCode::INTERNAL_SERVER_ERROR, "Invalid response from Hydra"))?;
2023-01-04 01:10:30 +01:00
2023-03-23 18:43:09 +01:00
let nix_store_path = hydra_body["buildoutputs"]["out"]["path"].as_str()
.ok_or_else(|| (StatusCode::INTERNAL_SERVER_ERROR, "No buildoutput found in Hydra"))?;
2023-01-04 01:10:30 +01:00
2023-03-25 13:42:58 +01:00
let hydra_system_hash = NixStorePath::from_path_buf(std::path::PathBuf::from(nix_store_path))
.map_err(|_err| (StatusCode::INTERNAL_SERVER_ERROR, "Invalid store path returned by Hydra"))?
.hash;
2023-01-04 01:10:30 +01:00
let mut status = "0";
if current_system_hash == hydra_system_hash {
status = "1";
}
2023-03-23 18:43:09 +01:00
return Ok((
2023-01-04 01:10:30 +01:00
StatusCode::OK,
2023-02-04 00:32:26 +01:00
format!("nixos_current_system_is_sync{{}} {}\n", status)
2023-03-23 18:43:09 +01:00
));
2022-12-31 00:29:17 +01:00
}