#![forbid(unsafe_code)]
use fastrand;
use log::trace;
use std::{
env,
iter::repeat_with,
path::{Path, PathBuf},
};
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Config {
pub plugin_name: String,
pub plugin_statedir: PathBuf,
pub plugin_cache: PathBuf,
pub dirtyconfig: bool,
pub daemonize: bool,
pub pidfile: PathBuf,
pub config_size: usize,
pub fetch_size: usize,
}
impl Config {
fn get_statedir() -> PathBuf {
PathBuf::from(env::var("MUNIN_PLUGSTATE").unwrap_or_else(|_| String::from("/tmp")))
}
pub fn new(plugin_name: String) -> Self {
Config::realnew(plugin_name, false)
}
pub fn new_daemon(plugin_name: String) -> Self {
Config::realnew(plugin_name, true)
}
fn realnew(plugin_name: String, daemonize: bool) -> Self {
trace!("Creating new config for plugin {plugin_name}, daemon: {daemonize}");
let pd = plugin_name.clone();
Self {
plugin_name,
daemonize: daemonize,
pidfile: Config::get_statedir().join(format!("{}.pid", pd)),
plugin_cache: Config::get_statedir().join(format!("munin.{}.value", pd)),
..Default::default()
}
}
}
impl Default for Config {
fn default() -> Self {
let statedir = Config::get_statedir();
let insert: String = repeat_with(fastrand::alphanumeric).take(10).collect();
let cachename = Path::new(&statedir).join(format!("munin.{}.value", insert));
Self {
plugin_name: String::from("Simple munin plugin in Rust"),
plugin_statedir: statedir.clone(),
plugin_cache: cachename,
dirtyconfig: match env::var("MUNIN_CAP_DIRTYCONFIG") {
Ok(val) => val.eq(&"1"),
Err(_) => false,
},
daemonize: false,
pidfile: statedir.join("munin-plugin.pid"),
config_size: 8192,
fetch_size: 8192,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn test_modconfig() {
let config = Config {
..Default::default()
};
assert_eq!(
config.plugin_name,
String::from("Simple munin plugin in Rust")
);
let mut config2 = Config {
plugin_name: String::from("Lala"),
..Default::default()
};
assert_eq!(config2.plugin_name, String::from("Lala"));
assert!(!config2.daemonize);
assert_eq!(config2.fetch_size, 8192);
config2.pidfile = PathBuf::new();
config2.pidfile.push(&config2.plugin_statedir);
config2.pidfile.push(String::from("Lala.pid"));
let config3 = Config::new(String::from("Lala"));
assert_ne!(config2, config3);
config2.plugin_cache = config2.plugin_statedir.join("munin.Lala.value");
assert_eq!(config2, config3);
}
#[test]
fn test_new_daemon() {
let config = Config::new_daemon(String::from("great-plugin"));
assert_eq!(config.plugin_name, String::from("great-plugin"));
assert_eq!(
config.plugin_cache,
PathBuf::from(String::from("/tmp/munin.great-plugin.value"))
);
assert!(config.daemonize);
}
}