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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
//! munin-plugin - Simple writing of plugins for munin in Rust
//!
//! SPDX-License-Identifier: LGPL-3.0-only
//!
//! Copyright (C) 2022 Joerg Jaspert <joerg@debian.org>
//!
//! # About
//! Simple way to write munin plugins. They can be _standard_ plugins
//! that run once every 5 minutes, when munin comes along to ask for
//! data. Or they can be so-called _streaming_ plugins - plugins that
//! fork themself into the background, continuously gathering data,
//! handing that data to munin when it comes around.
//!
//! Those _streaming_ plugins are needed/useful, when graphs with
//! resolutions down to the second, rather than the default 5 minutes,
//! should be created.
//!
//! # Repositories / plugins using this code
//! - [Simple munin plugin to graph load](https://github.com/Ganneff/munin-load)
//! - [Munin CPU graph with 1second resolution](https://github.com/Ganneff/cpu1sec/)
//! - [Munin Interface graph with 1second resolution](https://github.com/Ganneff/if1sec)
//!
//! # Usage
//! For a _standard_ plugin you use this library, create an empty
//! struct named for your plugin and implement MuninPlugin for this
//! struct. You need to provide the functions `config` and `fetch`,
//! the rest can be stubs with the magic `unimplemented!()` macro.
//! Within `config()` you output the munin graph configuration,
//! `fetch()` should collect the data and output it in
//! munin-compatible format. Finally you call the `start()` or even
//! `simple_start` function on it, and you are done.
//!
//! A streaming plugin is similar, except you also need to provide a
//! useful `acquire` function and fetch will no longer gather data -
//! that is done by `acquire`. `acquire` will be called once every
//! second, should collect the data and write it to a file within
//! [Config::plugin_statedir]. `fetch()` then has to write the
//! contents of this cachefile to the handle, when called.
//!
//! # Example
//! The following implements the **load** plugin from munin, graphing
//! the load average of the system, using the 5-minute value. As
//! implemented, it expects to be run by munin every 5 minutes,
//! usually munin will first run it with the config parameter,
//! followed by no parameter to fetch data. If munin-node supports it
//! and the capability _dirtyconfig_ is set, config will also print
//! out data.
//!
//! It is a shortened version of the plugin linked above (Simple munin
//! plugin to graph load), with things like logging dropped.
//!
//! For more example code look into the actual [MuninPlugin] trait and its function
//! definitions.
//!
//! ```rust
//! use anyhow::Result;
//! use munin_plugin::{config::Config, MuninPlugin};
//! use procfs::LoadAverage;
//! use std::io::{self, BufWriter, Write};
//!
//! // Our plugin struct
//! #[derive(Debug)]
//! struct LoadPlugin;
//!
//! // Implement the needed functions
//! impl MuninPlugin for LoadPlugin {
//! // Write out munin config. handle is setup as a bufwriter to stdout.
//! fn config<W: Write>(&self, handle: &mut BufWriter<W>) -> Result<()> {
//! writeln!(handle, "graph_title Load average")?;
//! writeln!(handle, "graph_args --base 1000 -l 0")?;
//! writeln!(handle, "graph_vlabel load")?;
//! writeln!(handle, "graph_scale no")?;
//! writeln!(handle, "graph_category system")?;
//! writeln!(handle, "load.label load")?;
//! writeln!(handle, "load.warning 10")?;
//! writeln!(handle, "load.critical 120")?;
//! writeln!(handle, "graph_info The load average of the machine describes how many processes are in the run-queue (scheduled to run immediately.")?;
//! writeln!(handle, "load.info Average load for the five minutes.")?;
//! Ok(())
//! }
//!
//! // Fetch and display data
//! fn fetch<W: Write>(&self, handle: &mut BufWriter<W>) -> Result<()> {
//! let load = (LoadAverage::new().unwrap().five * 100.0) as isize;
//! writeln!(handle, "load.value {}", load);
//! Ok(())
//! }
//!
//! // This plugin does not need any setup and will just work, so
//! // just auto-configure it, if asked for.
//! fn check_autoconf(&self) -> bool {
//! true
//! }
//!
//! // The acquire function is not needed for a simple plugin that
//! // only gathers data every 5 minutes (munin standard), but the
//! // trait requires a stub to be there.
//! fn acquire(&mut self, config: &Config) -> Result<()> {
//! unimplemented!()
//! }
//! }
//!
//! // The actual program start point
//! fn main() -> Result<()> {
//! // Get our Plugin
//! let mut load = LoadPlugin;
//! // And let it do the work.
//! load.simple_start(String::from("load"))?;
//! Ok(())
//! }
//! ```
//!
//! # Logging
//! This crate uses the default [log] crate to output log messages of
//! level trace or debug. No other levels will be used. If you want to
//! see them, select a log framework you like and ensure its level
//! will display trace/debug messages. See that frameworks
//! documentation on how to setup/include it.
//!
//! If you do not want/need log output, just do nothing.
// Tell us if we forget to document things
#![warn(missing_docs)]
// We do not want to write unsafe code
#![forbid(unsafe_code)]
pub mod config;
pub use crate::config::Config;
use anyhow::{anyhow, Result};
// daemonize
use daemonize::Daemonize;
// daemonize
use fs2::FileExt;
use log::{trace, warn};
// daemonize
use spin_sleep::LoopHelper;
use std::{
env,
io::{self, BufWriter, Write},
path::Path,
};
// daemonize
use std::{
fs::File,
process::{Command, Stdio},
thread,
time::Duration,
};
/// Defines a Munin Plugin and the needed functions
pub trait MuninPlugin {
/// Write out a munin config, read the [Developing
/// plugins](http://guide.munin-monitoring.org/en/latest/develop/plugins/index.html)
/// guide from munin for everything you can print out here.
///
/// Note that munin expects this to appear on stdout, so the
/// plugin gives you a handle to write to, which is setup as a
/// [std::io::BufWriter] to stdout. The [std::io::BufWriter]
/// capacity defaults to 8192 bytes, but if you need more, its
/// size can be set using [Config::cfgsize]. An example where this
/// may be useful is a munin multigraph plugin that outputs config
/// for a many graphs.
///
/// # When
/// This function is needed for every plugin.
///
/// # Example
/// ```rust
/// # pub use munin_plugin::*;
/// # use anyhow::{anyhow, Result};
/// # use std::{
/// # env,
/// # io::{self, BufWriter, Write},
/// # };
/// # struct LoadPlugin;
/// # impl MuninPlugin for LoadPlugin {
/// # fn acquire(&mut self, config: &Config) -> Result<()> { todo!() }
/// # fn fetch<W: Write>(&self, handle: &mut BufWriter<W>) -> Result<()> { todo!() }
/// fn config<W: Write>(&self, handle: &mut BufWriter<W>) -> Result<()> {
/// writeln!(handle, "graph_title Load average")?;
/// writeln!(handle, "graph_args --base 1000 -l 0")?;
/// writeln!(handle, "graph_vlabel load")?;
/// writeln!(handle, "graph_scale no")?;
/// writeln!(handle, "graph_category system")?;
/// writeln!(handle, "load.label load")?;
/// writeln!(handle, "load.warning 10")?;
/// writeln!(handle, "load.critical 120")?;
/// writeln!(handle, "graph_info The load average of the machine describes how many processes are in the run-queue (scheduled to run immediately.")?;
/// writeln!(handle, "load.info Average load for the five minutes.")?;
/// Ok(())
/// }
/// # }
/// ```
fn config<W: Write>(&self, handle: &mut BufWriter<W>) -> Result<()>;
/// Acquire data and store it for later fetching.
///
/// Acquire is called from [MuninPlugin::daemon] once every second
/// and is expected to do whatever is neccessary to gather the
/// data, the plugin is supposed to gather. It should then store
/// it somewhere, where [MuninPlugin::fetch] can read it.
/// [MuninPlugin::fetch] will be called from munin-node (usually)
/// every 5 minutes and is expected to output data to stdout, in a
/// munin compatible way.
///
/// # When
/// This function is only needed if [Config::daemonize] is true.
/// Simple plugins that are run every 5 minutes only by munin, and
/// do not gather data in the meantime, do not need to implement
/// it. For such plugins provide a stub (as seen on this docs main
/// page) that says ```unimplemented!()```.
///
/// # Example
/// ```rust
/// # pub use munin_plugin::*;
/// # use anyhow::{anyhow, Result};
/// # use std::{
/// # env,
/// # fs::{rename, OpenOptions},
/// # io::{self, BufWriter, Write},
/// # path::{Path, PathBuf},
/// # time::{SystemTime, UNIX_EPOCH},
/// # };
/// # struct InterfacePlugin {
/// # interface: String,
/// # cache: PathBuf,
/// # if_txbytes: PathBuf,
/// # if_rxbytes: PathBuf,
/// # };
/// # impl MuninPlugin for InterfacePlugin {
/// # fn fetch<W: Write>(&self, handle: &mut BufWriter<W>) -> Result<()> { todo!() }
/// # fn config<W: Write>(&self, handle: &mut BufWriter<W>) -> Result<()> { todo!() }
/// fn acquire(&mut self, config: &Config) -> Result<()> {
/// let cache = Path::new(&config.plugin_statedir).join("munin.if1sec.value");
/// let epoch = SystemTime::now()
/// .duration_since(UNIX_EPOCH)
/// .expect("Time gone broken, what?")
/// .as_secs(); // without the nanosecond part
/// // Read in the received and transferred bytes, store as u64
/// let rx: u64 = std::fs::read_to_string(&self.if_rxbytes)?.trim().parse()?;
/// let tx: u64 = std::fs::read_to_string(&self.if_txbytes)?.trim().parse()?;
/// // Open the munin cachefile to store our values,
/// // using a BufWriter to "collect" the two writeln
/// // together
/// let mut cachefd = BufWriter::new(
/// OpenOptions::new()
/// .create(true) // If not there, create
/// .write(true) // We want to write
/// .append(true) // We want to append
/// .open(&cache)?,
/// );
/// // And now write out values
/// writeln!(cachefd, "{0}_tx.value {1}:{2}", self.interface, epoch, tx)?;
/// writeln!(cachefd, "{0}_rx.value {1}:{2}", self.interface, epoch, rx)?;
/// Ok(())
/// }
/// # }
/// ```
fn acquire(&mut self, config: &Config) -> Result<()>;
/// Daemonize
///
/// This function will daemonize the process and then start a
/// loop, run once a second, calling [MuninPlugin::acquire].
fn daemon(&mut self, config: &Config) -> Result<()> {
// We want to run as daemon, so prepare
let daemonize = Daemonize::new()
.pid_file(&config.pidfile)
.chown_pid_file(true)
.working_directory("/tmp");
// And off into the background we go
daemonize.start()?;
// The loop helper makes it easy to repeat a loop once a second
let mut loop_helper = LoopHelper::builder().build_with_target_rate(1); // Only once a second
// We run forever
loop {
// Let loop helper prepare
loop_helper.loop_start();
self.acquire(config)?;
// Sleep for the rest of the second
loop_helper.loop_sleep();
}
}
/// Fetch delivers actual data to munin. This is called whenever
/// the plugin is called without an argument. If the
/// [config::Config::dirtyconfig] setting is true (auto-detected from
/// environment set by munin), this will also be called right
/// after having called [MuninPlugin::config].
///
/// A simple plugin may just gather data here too and then write it to the handle.
/// A plugin that daemonizes will gather data in [MuninPlugin::acquire] and cache
/// that in one or more cachefiles and just push it all to the handle (possibly using [std::io::copy]).
///
/// The size of the BufWriter is configurable from [Config::fetchsize].
///
/// # When
/// This function is needed for every plugin, simple plugins may
/// directly get the data in here and then write it to the handle,
/// while those that daemonize will typically write out the
/// contents of their cache file.
///
/// # Example 1 - Simple: Calculate some data, output
/// ```rust
/// # use munin_plugin::*;
/// # use anyhow::{anyhow, Result};
/// # use std::{
/// # env,
/// # io::{self, BufWriter, Write},
/// # };
/// use procfs::LoadAverage;
/// # struct LoadPlugin;
/// # impl MuninPlugin for LoadPlugin {
/// # fn acquire(&mut self, config: &Config) -> Result<()> { todo!() }
/// # fn config<W: Write>(&self, handle: &mut BufWriter<W>) -> Result<()> { todo!() }
/// fn fetch<W: Write>(&self, handle: &mut BufWriter<W>) -> Result<()> {
/// let load = (LoadAverage::new().unwrap().five * 100.0) as isize;
/// writeln!(handle, "load.value {}", load)?;
/// Ok(())
/// }
/// # }
/// ```
///
/// # Example 2 - Write out data gathered from [MuninPlugin::acquire]
/// ```rust
/// # pub use munin_plugin::*;
/// # use anyhow::{anyhow, Result};
/// # use std::{
/// # env,
/// # fs::{rename, OpenOptions},
/// # io::{self, BufWriter, Write},
/// # path::{Path, PathBuf},
/// # time::{SystemTime, UNIX_EPOCH},
/// # };
/// # use tempfile::NamedTempFile;
/// # struct InterfacePlugin {
/// # interface: String,
/// # cache: PathBuf,
/// # if_txbytes: PathBuf,
/// # if_rxbytes: PathBuf,
/// # };
/// # impl MuninPlugin for InterfacePlugin {
/// # fn config<W: Write>(&self, handle: &mut BufWriter<W>) -> Result<()> { todo!() }
/// # fn acquire(&mut self, config: &Config) -> Result<()> { todo!() }
/// fn fetch<W: Write>(&self, handle: &mut BufWriter<W>) -> Result<()> {
/// // We need a temporary file
/// let fetchpath = NamedTempFile::new_in(
/// self.cache
/// .parent()
/// .expect("Could not find useful temp path"),
/// )?;
/// // Rename the cache file, to ensure that acquire doesn't add data
/// // between us outputting data and deleting the file
/// rename(&self.cache, &fetchpath)?;
/// // Want to read the tempfile now
/// let mut fetchfile = std::fs::File::open(&fetchpath)?;
/// // And ask io::copy to just take it all and shove it into the handle
/// io::copy(&mut fetchfile, handle)?;
/// Ok(())
/// }
/// # }
/// ```
fn fetch<W: Write>(&self, handle: &mut BufWriter<W>) -> Result<()>;
/// Check whatever is neccessary to decide if the plugin can
/// auto-configure itself.
///
/// For example a network load plugin may check if network
/// interfaces exists and then return true, something presenting
/// values of a daemon like apache or ntp may check if that is
/// installed - and possibly if fetching values is possible.
///
/// If this function is not overwritten, it defaults to false.
fn check_autoconf(&self) -> bool {
false
}
/// Tell munin if the plugin supports autoconf.
///
/// Munin expects a simple yes or no on stdout, so we just print
/// it, depending on the return value of
/// [MuninPlugin::check_autoconf]. The default of that is a plain
/// false. If it is possible for your plugin to detect, if it can
/// autoconfigure itself, then implement the logic in
/// [MuninPlugin::check_autoconf] and have it return true.
#[cfg(not(tarpaulin_include))]
fn autoconf(&self) {
if self.check_autoconf() {
println!("yes")
} else {
println!("no")
}
}
/// A simplified start, only need a name, for the rest, defaults are fine.
///
/// This is just a tiny bit of "being lazy is good" and will
/// create the [MuninPlugin::config] with the given name, then
/// call the real start function. Only useful for plugins that do
/// not use daemonization or need other config changes to run
/// successfully..
fn simple_start(&mut self, name: String) -> Result<bool> {
trace!("Simple Start, setting up config");
let config = Config::new(name);
trace!("Plugin: {:#?}", config);
self.start(config)?;
Ok(true)
}
/// The main plugin function, this will deal with parsing
/// commandline arguments and doing what is expected of the plugin
/// (present config, fetch values, whatever).
fn start(&mut self, config: Config) -> Result<bool> {
trace!("Plugin start");
trace!("My plugin config: {config:#?}");
// Store arguments for (possible) later use
let args: Vec<String> = env::args().collect();
// Now go over the args and see what we are supposed to do
match args.len() {
// no arguments passed, print data
1 => {
trace!("No argument, assuming fetch");
// For daemonization we need to check if a copy of us
// already runs. We do this by trying to lock our
// pidfile. If that works, nothing is running, then we
// need to start us in the background.
if config.daemonize {
let lockfile = !Path::exists(&config.pidfile) || {
let lockedfile =
File::open(&config.pidfile).expect("Could not open pidfile");
lockedfile.try_lock_exclusive().is_ok()
};
// If we could lock, it appears that acquire isn't running. Start it.
if lockfile {
trace!("Could lock the pidfile, will spawn acquire now");
Command::new(&args[0])
.arg("acquire")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.expect("failed to execute acquire");
trace!("Spawned, sleep for 1s, then continue");
// Now we wait one second before going on, so the
// newly spawned process had a chance to generate us
// some data
thread::sleep(Duration::from_secs(1));
}
}
trace!("Calling fetch");
// We want to write a possibly large amount to stdout, take and lock it
let stdout = io::stdout();
// Buffered writer, to gather multiple small writes together
let mut handle = BufWriter::with_capacity(config.fetchsize, stdout.lock());
self.fetch(&mut handle)?;
trace!("Done");
// And flush the handle, so it can also deal with possible errors
handle.flush()?;
return Ok(true);
}
// Argument passed, check which one and act accordingly
2 => match args[1].as_str() {
"config" => {
// We want to write a possibly large amount to stdout, take and lock it
let stdout = io::stdout();
{
// Buffered writer, to gather multiple small writes together
let mut handle = BufWriter::with_capacity(config.cfgsize, stdout.lock());
self.config(&mut handle)?;
// And flush the handle, so it can also deal with possible errors
handle.flush()?;
}
// If munin supports dirtyconfig, send the data now
if config.dirtyconfig {
trace!("Munin supports dirtyconfig, sending data now");
let mut handle = BufWriter::with_capacity(config.fetchsize, stdout.lock());
self.fetch(&mut handle)?;
// And flush the handle, so it can also deal with possible errors
handle.flush()?;
}
return Ok(true);
}
"autoconf" => {
self.autoconf();
return Ok(true);
}
"acquire" => {
trace!("Called acquire to gather data");
// Will only ever process anything after this line, if
// one process has our pidfile already locked, ie. if
// another acquire is running. (Or if we can not
// daemonize for another reason).
if let Err(e) = self.daemon(&config) {
return Err(anyhow!(
"Could not start plugin {} in daemon mode to gather data: {}",
config.plugin_name,
e
));
};
}
&_ => trace!("Unsupported argument: {}", args[1]),
},
// Whatever else
_ => return Err(anyhow!("No argument given")),
}
Ok(true)
}
}
#[cfg(test)]
mod tests {
use super::*;
// Our plugin struct
#[derive(Debug)]
struct TestPlugin;
impl MuninPlugin for TestPlugin {
fn config<W: Write>(&self, handle: &mut BufWriter<W>) -> Result<()> {
writeln!(handle, "This is a test plugin")?;
writeln!(handle, "There is no config")?;
Ok(())
}
fn fetch<W: Write>(&self, handle: &mut BufWriter<W>) -> Result<()> {
writeln!(handle, "This is a value")?;
writeln!(handle, "And one more value")?;
Ok(())
}
fn check_autoconf(&self) -> bool {
true
}
fn acquire(&mut self, _config: &Config) -> Result<()> {
Ok(())
}
}
#[test]
fn test_config() {
let test = TestPlugin;
// We want to check the output of config contains our test string
// above, so have it "write" it to a variable, then check if
// the variable contains what we want
let checktext = Vec::new();
let mut handle = BufWriter::new(checktext);
test.config(&mut handle).unwrap();
handle.flush().unwrap();
// And now check what got "written" into the variable
let (recovered_writer, _buffered_data) = handle.into_parts();
let output = String::from_utf8(recovered_writer).unwrap();
assert_eq!(
output,
String::from("This is a test plugin\nThere is no config\n")
);
}
#[test]
fn test_fetch() {
let test = TestPlugin;
// We want to check the output of config contains our test string
// above, so have it "write" it to a variable, then check if
// the variable contains what we want
let checktext = Vec::new();
let mut handle = BufWriter::new(checktext);
test.fetch(&mut handle).unwrap();
handle.flush().unwrap();
// And now check what got "written" into the variable
let (recovered_writer, _buffered_data) = handle.into_parts();
let output = String::from_utf8(recovered_writer).unwrap();
assert_eq!(
output,
String::from("This is a value\nAnd one more value\n")
);
}
}