Support for friendly_json comment (#55)

* upgrading deps

* tst

* fixed tests

* Json exposed as strings

* fixed double quote

* bumped version

* corrected semantic version bump

* updated README
This commit is contained in:
Francesco Cogno 2021-03-25 14:17:41 +01:00 committed by GitHub
parent 33c5372b41
commit a07a3d0170
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 550 additions and 841 deletions

971
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
[package] [package]
name = "prometheus_wireguard_exporter" name = "prometheus_wireguard_exporter"
version = "3.4.2" version = "3.5.0"
authors = ["Francesco Cogno <francesco.cogno@outlook.com>"] authors = ["Francesco Cogno <francesco.cogno@outlook.com>"]
description = "Prometheus WireGuard Exporter" description = "Prometheus WireGuard Exporter"
edition = "2018" edition = "2018"
@ -15,15 +15,15 @@ keywords = ["prometheus", "exporter", "wireguard"]
categories = ["database"] categories = ["database"]
[dependencies] [dependencies]
log = "0.4.6" log = "0.4.8"
env_logger = "0.6.1" env_logger = "0.7.1"
clap = "2.33.0" clap = "2.33.0"
serde_json = "1.0.39" serde_json = "1.0"
serde = "1.0.91" serde = "1.0"
serde_derive = "1.0.91" serde_derive = "1.0"
failure = "0.1.5" thiserror = "1.0"
hyper = { version = "0.13.0-alpha.4" , features = ["unstable-stream"] } hyper = { version = "0.14", features = ["stream"] }
http = "0.1.17" http = "0.2"
tokio = "0.2.0-alpha.6" tokio = { version = "1.0", features = ["macros", "rt"] }
prometheus_exporter_base = { version = "0.30.2" } prometheus_exporter_base = { version = "1.2", features = ["hyper_server"] }
regex = "1.3.1" regex = "1.3.1"

View file

@ -4,11 +4,11 @@
[![Crate](https://img.shields.io/crates/v/prometheus_wireguard_exporter.svg)](https://crates.io/crates/prometheus_wireguard_exporter) [![cratedown](https://img.shields.io/crates/d/prometheus_wireguard_exporter.svg)](https://crates.io/crates/prometheus_wireguard_exporter) [![cratelastdown](https://img.shields.io/crates/dv/prometheus_wireguard_exporter.svg)](https://crates.io/crates/prometheus_wireguard_exporter) [![Crate](https://img.shields.io/crates/v/prometheus_wireguard_exporter.svg)](https://crates.io/crates/prometheus_wireguard_exporter) [![cratedown](https://img.shields.io/crates/d/prometheus_wireguard_exporter.svg)](https://crates.io/crates/prometheus_wireguard_exporter) [![cratelastdown](https://img.shields.io/crates/dv/prometheus_wireguard_exporter.svg)](https://crates.io/crates/prometheus_wireguard_exporter)
[![release](https://img.shields.io/github/release/MindFlavor/prometheus_wireguard_exporter.svg)](https://github.com/MindFlavor/prometheus_wireguard_exporter/tree/3.4.2) [![release](https://img.shields.io/github/release/MindFlavor/prometheus_wireguard_exporter.svg)](https://github.com/MindFlavor/prometheus_wireguard_exporter/tree/3.5.0)
[![tag](https://img.shields.io/github/tag/mindflavor/prometheus_wireguard_exporter.svg)](https://github.com/MindFlavor/prometheus_wireguard_exporter/tree/3.4.2) [![tag](https://img.shields.io/github/tag/mindflavor/prometheus_wireguard_exporter.svg)](https://github.com/MindFlavor/prometheus_wireguard_exporter/tree/3.5.0)
[![Rust build](https://github.com/mindflavor/prometheus_wireguard_exporter/workflows/Rust/badge.svg)](https://github.com/mindflavor/prometheus_wireguard_exporter/actions?query=workflow%3ARust) [![Rust build](https://github.com/mindflavor/prometheus_wireguard_exporter/workflows/Rust/badge.svg)](https://github.com/mindflavor/prometheus_wireguard_exporter/actions?query=workflow%3ARust)
[![commitssince](https://img.shields.io/github/commits-since/mindflavor/prometheus_wireguard_exporter/3.4.2.svg)](https://img.shields.io/github/commits-since/mindflavor/prometheus_wireguard_exporter/3.4.2.svg) [![commitssince](https://img.shields.io/github/commits-since/mindflavor/prometheus_wireguard_exporter/3.5.0.svg)](https://img.shields.io/github/commits-since/mindflavor/prometheus_wireguard_exporter/3.5.0.svg)
![Docker build](https://github.com/MindFlavor/prometheus_wireguard_exporter/workflows/Buildx%20latest/badge.svg) ![Docker build](https://github.com/MindFlavor/prometheus_wireguard_exporter/workflows/Buildx%20latest/badge.svg)
@ -22,6 +22,7 @@ A Prometheus exporter for [WireGuard](https://www.wireguard.com), written in Rus
## Changelog ## Changelog
* From release [3.5.0](https://github.com/MindFlavor/prometheus_wireguard_exporter/releases/tag/3.5.0) the exporter supports the `friendly_json` tag. Entries prepended with the `friendly_json` tag will output all the entries in the specificed json as Prometheus attributes. Thanks to [DrProxyProSupport](https://github.com/iqdoctor) for the idea.
* From release [3.4.1](https://github.com/MindFlavor/prometheus_wireguard_exporter/releases/tag/3.4.0) the exporter supports prepending `sudo` to the `wg` command. This allows to run the exporter as a non root user (although sudoer without password). Thanks to [Jonas Seydel](https://github.com/Thor77) for the idea. * From release [3.4.1](https://github.com/MindFlavor/prometheus_wireguard_exporter/releases/tag/3.4.0) the exporter supports prepending `sudo` to the `wg` command. This allows to run the exporter as a non root user (although sudoer without password). Thanks to [Jonas Seydel](https://github.com/Thor77) for the idea.
* **BREAKING** From release [3.4.0](https://github.com/MindFlavor/prometheus_wireguard_exporter/releases/tag/3.4.0) the exporter requires you to specify the friendly names in a specific format (only if you want to use them of course). This allows you to use arbitrary comments in the file while keeping the friendly name functionality. Thank you [Miloš Bunčić](https://github.com/psyhomb) for this. This also paves the way for future metadata. In order to migrate you can use this sed command: `sed -i 's/#/# friendly_name=/' peers.conf`. Please make sure to do a backup before using it! * **BREAKING** From release [3.4.0](https://github.com/MindFlavor/prometheus_wireguard_exporter/releases/tag/3.4.0) the exporter requires you to specify the friendly names in a specific format (only if you want to use them of course). This allows you to use arbitrary comments in the file while keeping the friendly name functionality. Thank you [Miloš Bunčić](https://github.com/psyhomb) for this. This also paves the way for future metadata. In order to migrate you can use this sed command: `sed -i 's/#/# friendly_name=/' peers.conf`. Please make sure to do a backup before using it!
* From release [3.3.1](https://github.com/MindFlavor/prometheus_wireguard_exporter/releases/tag/3.3.1) the exporter accepts multiple interfaces in the command line options. Just pass the `-i` parameter multiple times. Note the not specifying the interface is equivalent to specifying every one of them (the exporter will pass the `all` parameter to `wg show` command). * From release [3.3.1](https://github.com/MindFlavor/prometheus_wireguard_exporter/releases/tag/3.3.1) the exporter accepts multiple interfaces in the command line options. Just pass the `-i` parameter multiple times. Note the not specifying the interface is equivalent to specifying every one of them (the exporter will pass the `all` parameter to `wg show` command).
@ -31,7 +32,7 @@ A Prometheus exporter for [WireGuard](https://www.wireguard.com), written in Rus
## Prerequisites ## Prerequisites
* You need [Rust](https://www.rust-lang.org/) to compile this code. Simply follow the instructions on Rust's website to install the toolchain. If you get weird errors while compiling please try and update your Rust version first (I have developed it on `rustc 1.42.0 (b8cedc004 2020-03-09)`). Alternatively you can build the docker image or use the prebuilt one. * You need [Rust](https://www.rust-lang.org/) to compile this code. Simply follow the instructions on Rust's website to install the toolchain. If you get weird errors while compiling please try and update your Rust version first (I have developed it on `rustc 1.53.0-nightly (f82664191 2021-03-21)`). Alternatively you can build the docker image or use the prebuilt one.
* You need [WireGuard](https://www.wireguard.com) *and* the `wg` CLI in the path. The tool will call `wg show <interface(s)>|all dump` and of course will fail if the `wg` executable is not found. If you want I can add the option of specifying the `wg` path in the command line, just open an issue for it. * You need [WireGuard](https://www.wireguard.com) *and* the `wg` CLI in the path. The tool will call `wg show <interface(s)>|all dump` and of course will fail if the `wg` executable is not found. If you want I can add the option of specifying the `wg` path in the command line, just open an issue for it.
Alternatively, as long as you have Wireguard on your host kernel with some Wireguard interfaces running, you can use Docker. For example: Alternatively, as long as you have Wireguard on your host kernel with some Wireguard interfaces running, you can use Docker. For example:
@ -74,16 +75,16 @@ Start the binary with `-h` to get the complete syntax. The parameters are:
| `-a` | no | <switch> | | No | Prepends sudo to `wg` commands. | `-a` | no | <switch> | | No | Prepends sudo to `wg` commands.
| `-l` | no | any valid ip address | 0.0.0.0 | No | Specify the service address. This is the address your Prometheus instance should point to. | `-l` | no | any valid ip address | 0.0.0.0 | No | Specify the service address. This is the address your Prometheus instance should point to.
| `-p` | no | any valid port number | 9586 | No | Specify the service port. This is the port your Prometheus instance should point to. | `-p` | no | any valid port number | 9586 | No | Specify the service port. This is the port your Prometheus instance should point to.
| `-n` | no | path to the wireguard configuration file | | No | This flag adds the *friendly_name* attribute to the exported entries. See [Friendly names](#friendly-names) for more details. | `-n` | no | path to the wireguard configuration file | | No | This flag adds the *friendly_name* attribute or the *friendly_json* attributes to the exported entries. See [Friendly tags](#friendly-tags) for more details.
| `-s` | no | <switch> | off | No | Enable the allowed ip + subnet split mode for the labels. | `-s` | no | <switch> | off | No | Enable the allowed ip + subnet split mode for the labels.
| `-r` | no | <switch> | off | No | Exports peer's remote ip and port as labels (if available). | `-r` | no | <switch> | off | No | Exports peer's remote ip and port as labels (if available).
| `-i` | no | your interface name(s) | `all` | Yes | Specifies the interface(s) passed to the `wg show <interface> dump` parameter. Multiple parameters are allowed. | `-i` | no | your interface name(s) | `all` | Yes | Specifies the interface(s) passed to the `wg show <interface> dump` parameter. Multiple parameters are allowed.
Once started, the tool will listen on the specified port (or the default one, 9586, if not specified) and return a Prometheus valid response at the url `/metrics`. So to check if the tool is working properly simply browse the `http://localhost:9586/metrics` (or whichever port you choose). Once started, the tool will listen on the specified port (or the default one, 9586, if not specified) and return a Prometheus valid response at the url `/metrics`. So to check if the tool is working properly simply browse the `http://localhost:9586/metrics` (or whichever port you choose).
## Friendly Names ## Friendly Tags
Starting from version 1.2 you can instruct the exporter to append a *friendly name* to the exported entries. This can make the output more understandable than using the public keys. For example this is the standard output: Starting from version 3.5 you can instruct the exporter to append a *friendly name* or a *friendly_json* to the exported entries. This can make the output more understandable than using the public keys. For example this is the standard output:
``` ```
# HELP wireguard_sent_bytes_total Bytes sent to the peer # HELP wireguard_sent_bytes_total Bytes sent to the peer
@ -148,7 +149,10 @@ wireguard_latest_handshake_seconds{interface="wg0",public_key="wTjv6hS6fKfNK+SzO
``` ```
In order for this to work, you need to add the `friendly_name` key value to the comments preceding a peer a specific metadata (in your wireguard configuration file). See below the `[Peer]` definition for an example. In order for this to work, you need to add the `friendly_name` key value to the comments preceding a peer a specific metadata (in your wireguard configuration file). See below the `[Peer]` definition for an example.
The tag is called `friendly_name` and it will be added to the entry exported to Prometheus. Note that this is not a standard but, since it's a comment, will not interfere with WireGuard in any way. For example this is how you edit your WireGuard configuration file: The tag is called `friendly_name` and it will be added to the entry exported to Prometheus. Note that this is not a standard but, since it's a comment, will not interfere with WireGuard in any way.
From version [3.5.0](https://github.com/MindFlavor/prometheus_wireguard_exporter/releases/tag/3.5.0) you can optionally specify a `friendly_json` tag followed by a flat json (that is, a json with only top level, simple entries). If a `friendly_json` tag will be found every entry will be used as attribute in the exported Prometheus instance. No compliance check will be done. Also, numbers will be converted to strings (as it's expected for a Prometheus attribute).
For example this is how you edit your WireGuard configuration file:
```toml ```toml
[Peer] [Peer]

View file

@ -1,40 +1,54 @@
#[derive(Debug, Fail)] use thiserror::Error;
pub enum PeerEntryParseError {
#[fail(display = "PublicKey entry not found in lines: {:?}", lines)]
PublicKeyNotFound { lines: Vec<String> },
#[fail(display = "AllowedIPs entry not found in lines: {:?}", lines)] #[derive(Error, Debug)]
AllowedIPsEntryNotFound { lines: Vec<String> }, pub enum FriendlyDescritionParseError {
#[error("unsupported header")]
UnsupportedHeader(String),
#[error("json parse error")]
SerdeJsonError(#[from] serde_json::Error),
} }
#[derive(Debug, Fail)] #[derive(Debug, Error)]
pub enum PeerEntryParseError {
#[error("PublicKey entry not found in lines: {:?}", lines)]
PublicKeyNotFound { lines: Vec<String> },
#[error("AllowedIPs entry not found in lines: {:?}", lines)]
AllowedIPsEntryNotFound { lines: Vec<String> },
#[error("Friendly description parse error")]
FriendlyDescritionParseError(#[from] FriendlyDescritionParseError),
}
#[derive(Debug, Error)]
pub enum ExporterError { pub enum ExporterError {
#[allow(dead_code)] #[allow(dead_code)]
#[fail(display = "Generic error")] #[error("Generic error")]
Generic {}, Generic {},
#[fail(display = "Hyper error: {}", e)] #[error("Hyper error: {}", e)]
Hyper { e: hyper::error::Error }, Hyper { e: hyper::Error },
#[fail(display = "http error: {}", e)] #[error("http error: {}", e)]
Http { e: http::Error }, Http { e: http::Error },
#[fail(display = "UTF-8 error: {}", e)] #[error("UTF-8 error: {}", e)]
UTF8 { e: std::string::FromUtf8Error }, UTF8 { e: std::string::FromUtf8Error },
#[fail(display = "JSON format error: {}", e)] #[error("JSON format error: {}", e)]
JSON { e: serde_json::error::Error }, JSON { e: serde_json::error::Error },
#[fail(display = "IO Error: {}", e)] #[error("IO Error: {}", e)]
IO { e: std::io::Error }, IO { e: std::io::Error },
#[fail(display = "UTF8 conversion error: {}", e)] #[error("UTF8 conversion error: {}", e)]
Utf8 { e: std::str::Utf8Error }, Utf8 { e: std::str::Utf8Error },
#[fail(display = "int conversion error: {}", e)] #[error("int conversion error: {}", e)]
ParseInt { e: std::num::ParseIntError }, ParseInt { e: std::num::ParseIntError },
#[fail(display = "PeerEntry parse error: {}", e)] #[error("PeerEntry parse error: {}", e)]
PeerEntryParseError { e: PeerEntryParseError }, PeerEntryParseError { e: PeerEntryParseError },
} }
@ -50,8 +64,8 @@ impl From<std::io::Error> for ExporterError {
} }
} }
impl From<hyper::error::Error> for ExporterError { impl From<hyper::Error> for ExporterError {
fn from(e: hyper::error::Error) -> Self { fn from(e: hyper::Error) -> Self {
ExporterError::Hyper { e } ExporterError::Hyper { e }
} }
} }

View file

@ -0,0 +1,31 @@
use crate::exporter_error::FriendlyDescritionParseError;
use std::borrow::Cow;
use std::collections::HashMap;
use std::convert::TryFrom;
#[derive(Debug, Clone, PartialEq)]
pub enum FriendlyDescription<'a> {
Name(Cow<'a, str>),
Json(HashMap<&'a str, serde_json::Value>),
}
impl<'a> TryFrom<(&'a str, &'a str)> for FriendlyDescription<'a> {
type Error = FriendlyDescritionParseError;
fn try_from((header_name, value): (&'a str, &'a str)) -> Result<Self, Self::Error> {
Ok(match header_name {
"friendly_name" => FriendlyDescription::Name(value.into()),
"friendly_json" => {
let ret: HashMap<&str, serde_json::Value> = serde_json::from_str(value)?;
FriendlyDescription::Json(ret)
}
other => {
return Err(FriendlyDescritionParseError::UnsupportedHeader(format!(
"{} is not a supported tag",
other
)))
}
})
}
}

View file

@ -1,6 +1,4 @@
extern crate serde_json; //extern crate serde_json;
#[macro_use]
extern crate failure;
use clap::{crate_authors, crate_name, crate_version, Arg}; use clap::{crate_authors, crate_name, crate_version, Arg};
use hyper::{Body, Request}; use hyper::{Body, Request};
use log::{debug, info, trace}; use log::{debug, info, trace};
@ -10,20 +8,20 @@ use options::Options;
mod wireguard; mod wireguard;
use std::convert::TryFrom; use std::convert::TryFrom;
use std::process::Command; use std::process::Command;
use std::string::String; mod friendly_description;
pub use friendly_description::*;
use wireguard::WireGuard; use wireguard::WireGuard;
mod exporter_error; mod exporter_error;
mod wireguard_config; mod wireguard_config;
use wireguard_config::peer_entry_hashmap_try_from;
extern crate prometheus_exporter_base;
use prometheus_exporter_base::render_prometheus; use prometheus_exporter_base::render_prometheus;
use std::net::IpAddr; use std::net::IpAddr;
use std::sync::Arc; use std::sync::Arc;
use wireguard_config::peer_entry_hashmap_try_from;
async fn perform_request( async fn perform_request(
_req: Request<Body>, _req: Request<Body>,
options: Arc<Options>, options: Arc<Options>,
) -> Result<String, failure::Error> { ) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
let interfaces_to_handle = match &options.interfaces { let interfaces_to_handle = match &options.interfaces {
Some(interfaces_str) => interfaces_str.clone(), Some(interfaces_str) => interfaces_str.clone(),
None => vec!["all".to_owned()], None => vec!["all".to_owned()],
@ -110,8 +108,8 @@ async fn perform_request(
} }
} }
#[tokio::main] #[tokio::main(flavor = "current_thread")]
async fn main() { async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let matches = clap::App::new(crate_name!()) let matches = clap::App::new(crate_name!())
.version(crate_version!()) .version(crate_version!())
.author(crate_authors!("\n")) .author(crate_authors!("\n"))
@ -202,4 +200,6 @@ async fn main() {
Box::pin(perform_request(request, options)) Box::pin(perform_request(request, options))
}) })
.await; .await;
Ok(())
} }

View file

@ -1,7 +1,8 @@
use crate::exporter_error::ExporterError; use crate::exporter_error::ExporterError;
use crate::wireguard_config::PeerEntryHashMap; use crate::wireguard_config::PeerEntryHashMap;
use crate::FriendlyDescription;
use log::{debug, trace}; use log::{debug, trace};
use prometheus_exporter_base::{MetricType, PrometheusMetric}; use prometheus_exporter_base::{MetricType, PrometheusInstance, PrometheusMetric};
use regex::Regex; use regex::Regex;
use std::collections::HashMap; use std::collections::HashMap;
use std::convert::TryFrom; use std::convert::TryFrom;
@ -147,35 +148,21 @@ impl WireGuard {
debug!("WireGuard::render_with_names(self == {:?}, pehm == {:?}, split_allowed_ips == {:?}, export_remote_ip_and_port == {:?} called", self, pehm, split_allowed_ips,export_remote_ip_and_port); debug!("WireGuard::render_with_names(self == {:?}, pehm == {:?}, split_allowed_ips == {:?}, export_remote_ip_and_port == {:?} called", self, pehm, split_allowed_ips,export_remote_ip_and_port);
// these are the exported counters // these are the exported counters
let pc_sent_bytes_total = PrometheusMetric::new( let mut pc_sent_bytes_total = PrometheusMetric::build()
"wireguard_sent_bytes_total", .with_name("wireguard_sent_bytes_total")
MetricType::Counter, .with_metric_type(MetricType::Counter)
"Bytes sent to the peer", .with_help("Bytes sent to the peer")
); .build();
let pc_received_bytes_total = PrometheusMetric::new( let mut pc_received_bytes_total = PrometheusMetric::build()
"wireguard_received_bytes_total", .with_name("wireguard_received_bytes_total")
MetricType::Counter, .with_metric_type(MetricType::Counter)
"Bytes received from the peer", .with_help("Bytes received from the peer")
); .build();
let pc_latest_handshake = PrometheusMetric::new( let mut pc_latest_handshake = PrometheusMetric::build()
"wireguard_latest_handshake_seconds", .with_name("wireguard_latest_handshake_seconds")
MetricType::Gauge, .with_metric_type(MetricType::Gauge)
"Seconds from the last handshake", .with_help("Seconds from the last handshake")
); .build();
// these 3 vectors will hold the intermediate
// values. We use the vector in order to traverse
// the interfaces slice only once: since we need to output
// the values grouped by counter we populate the vectors here
// and then reorder during the final string creation phase.
let mut s_sent_bytes_total = Vec::new();
s_sent_bytes_total.push(pc_sent_bytes_total.render_header());
let mut s_received_bytes_total = Vec::new();
s_received_bytes_total.push(pc_received_bytes_total.render_header());
let mut s_latest_handshake = Vec::new();
s_latest_handshake.push(pc_latest_handshake.render_header());
// Here we make sure we process the interfaces in the // Here we make sure we process the interfaces in the
// lexicographical order. // lexicographical order.
@ -240,9 +227,40 @@ impl WireGuard {
// let's add the friendly_name attribute if present // let's add the friendly_name attribute if present
// and has meaniningful value // and has meaniningful value
if let Some(pehm) = pehm { if let Some(pehm) = pehm {
if let Some(ep_friendly_name) = pehm.get(&ep.public_key as &str) { if let Some(ep_friendly_description) = pehm.get(&ep.public_key as &str) {
if let Some(ep_friendly_name) = ep_friendly_name.name { if let Some(friendly_description) =
attributes.push(("friendly_name", &ep_friendly_name)); &ep_friendly_description.friendly_description
{
match friendly_description {
FriendlyDescription::Name(name) => {
attributes.push(("friendly_name", name));
}
FriendlyDescription::Json(json) => {
// let's put them in a intermediate vector and then sort it
let mut v_temp = Vec::new();
json.iter().for_each(|(header, value)| {
//attributes_owned
v_temp.push((
header.to_string(),
match value {
serde_json::Value::Number(number) => {
number.to_string()
}
serde_json::Value::String(s) => s.to_owned(),
serde_json::Value::Bool(b) => b.to_string(),
_ => panic!("unsupported json value"),
},
));
});
v_temp.sort_by(|(k0, _), (k1, _)| k0.cmp(k1));
v_temp
.into_iter()
.for_each(|item| attributes_owned.push(item));
}
}
} }
} }
} }
@ -260,31 +278,32 @@ impl WireGuard {
attributes.push((label, val)); attributes.push((label, val));
} }
s_sent_bytes_total let mut instance = PrometheusInstance::new();
.push(pc_sent_bytes_total.render_sample(Some(&attributes), ep.sent_bytes)); for (h, v) in attributes {
s_received_bytes_total.push( instance = instance.with_label(h, v);
pc_received_bytes_total.render_sample(Some(&attributes), ep.received_bytes), }
);
s_latest_handshake.push( pc_sent_bytes_total
pc_latest_handshake.render_sample(Some(&attributes), ep.latest_handshake), .render_and_append_instance(&instance.clone().with_value(ep.sent_bytes))
.render();
pc_received_bytes_total
.render_and_append_instance(&instance.clone().with_value(ep.received_bytes))
.render();
pc_latest_handshake.render_and_append_instance(
&instance.with_value(ep.latest_handshake.into()),
); );
} }
} }
} }
// now let's join the results and return it to the caller format!(
let mut s = String::with_capacity(s_latest_handshake.len() * 64 * 3); "{}\n{}\n{}",
for item in s_sent_bytes_total { pc_sent_bytes_total.render(),
s.push_str(&item); pc_received_bytes_total.render(),
} pc_latest_handshake.render()
for item in s_received_bytes_total { )
s.push_str(&item);
}
for item in s_latest_handshake {
s.push_str(&item);
}
s
} }
} }
@ -379,6 +398,7 @@ wireguard_sent_bytes_total{interface=\"wg0\",public_key=\"yZOoC2t6pBcXvoczuiJqrQ
wireguard_sent_bytes_total{interface=\"wg0\",public_key=\"yjeBkrZqUThSSHySFzWCjxAH8cxtiWSI2I8JFD6t1UM=\",remote_ip=\"10.211.123.126\",allowed_ip_0=\"10.90.0.5\",allowed_subnet_0=\"32\",remote_port=\"51820\"} 10642564136 wireguard_sent_bytes_total{interface=\"wg0\",public_key=\"yjeBkrZqUThSSHySFzWCjxAH8cxtiWSI2I8JFD6t1UM=\",remote_ip=\"10.211.123.126\",allowed_ip_0=\"10.90.0.5\",allowed_subnet_0=\"32\",remote_port=\"51820\"} 10642564136
wireguard_sent_bytes_total{interface=\"wg0\",public_key=\"HtOSi37ALMnSkeAFqeWYZqlBnZqAJERhb5o/i3ZPEFI=\",remote_ip=\"10.211.123.127\",allowed_ip_0=\"10.90.0.17\",allowed_subnet_0=\"32\",remote_port=\"51820\"} 1439257868 wireguard_sent_bytes_total{interface=\"wg0\",public_key=\"HtOSi37ALMnSkeAFqeWYZqlBnZqAJERhb5o/i3ZPEFI=\",remote_ip=\"10.211.123.127\",allowed_ip_0=\"10.90.0.17\",allowed_subnet_0=\"32\",remote_port=\"51820\"} 1439257868
wireguard_sent_bytes_total{interface=\"wg0\",public_key=\"sUsR6xufQQ8Tf0FuyY9tfEeYdhVMeFelr4ZMUrj+B0E=\",remote_ip=\"10.211.123.128\",allowed_ip_0=\"10.90.0.18\",allowed_subnet_0=\"32\",remote_port=\"51820\"} 1624251784 wireguard_sent_bytes_total{interface=\"wg0\",public_key=\"sUsR6xufQQ8Tf0FuyY9tfEeYdhVMeFelr4ZMUrj+B0E=\",remote_ip=\"10.211.123.128\",allowed_ip_0=\"10.90.0.18\",allowed_subnet_0=\"32\",remote_port=\"51820\"} 1624251784
# HELP wireguard_received_bytes_total Bytes received from the peer # HELP wireguard_received_bytes_total Bytes received from the peer
# TYPE wireguard_received_bytes_total counter # TYPE wireguard_received_bytes_total counter
wireguard_received_bytes_total{interface=\"wg0\",public_key=\"923V/iAdcz8BcqB0Xo6pDJzARGBJCQ6fWe+peixQyB4=\",remote_ip=\"10.211.123.112\",allowed_ip_0=\"10.90.0.10\",allowed_subnet_0=\"32\",allowed_ip_1=\"10.0.1.0\",allowed_subnet_1=\"24\",remote_port=\"51820\"} 0 wireguard_received_bytes_total{interface=\"wg0\",public_key=\"923V/iAdcz8BcqB0Xo6pDJzARGBJCQ6fWe+peixQyB4=\",remote_ip=\"10.211.123.112\",allowed_ip_0=\"10.90.0.10\",allowed_subnet_0=\"32\",allowed_ip_1=\"10.0.1.0\",allowed_subnet_1=\"24\",remote_port=\"51820\"} 0
@ -398,6 +418,7 @@ wireguard_received_bytes_total{interface=\"wg0\",public_key=\"yZOoC2t6pBcXvoczui
wireguard_received_bytes_total{interface=\"wg0\",public_key=\"yjeBkrZqUThSSHySFzWCjxAH8cxtiWSI2I8JFD6t1UM=\",remote_ip=\"10.211.123.126\",allowed_ip_0=\"10.90.0.5\",allowed_subnet_0=\"32\",remote_port=\"51820\"} 18576788764 wireguard_received_bytes_total{interface=\"wg0\",public_key=\"yjeBkrZqUThSSHySFzWCjxAH8cxtiWSI2I8JFD6t1UM=\",remote_ip=\"10.211.123.126\",allowed_ip_0=\"10.90.0.5\",allowed_subnet_0=\"32\",remote_port=\"51820\"} 18576788764
wireguard_received_bytes_total{interface=\"wg0\",public_key=\"HtOSi37ALMnSkeAFqeWYZqlBnZqAJERhb5o/i3ZPEFI=\",remote_ip=\"10.211.123.127\",allowed_ip_0=\"10.90.0.17\",allowed_subnet_0=\"32\",remote_port=\"51820\"} 62592693520 wireguard_received_bytes_total{interface=\"wg0\",public_key=\"HtOSi37ALMnSkeAFqeWYZqlBnZqAJERhb5o/i3ZPEFI=\",remote_ip=\"10.211.123.127\",allowed_ip_0=\"10.90.0.17\",allowed_subnet_0=\"32\",remote_port=\"51820\"} 62592693520
wireguard_received_bytes_total{interface=\"wg0\",public_key=\"sUsR6xufQQ8Tf0FuyY9tfEeYdhVMeFelr4ZMUrj+B0E=\",remote_ip=\"10.211.123.128\",allowed_ip_0=\"10.90.0.18\",allowed_subnet_0=\"32\",remote_port=\"51820\"} 75066288152 wireguard_received_bytes_total{interface=\"wg0\",public_key=\"sUsR6xufQQ8Tf0FuyY9tfEeYdhVMeFelr4ZMUrj+B0E=\",remote_ip=\"10.211.123.128\",allowed_ip_0=\"10.90.0.18\",allowed_subnet_0=\"32\",remote_port=\"51820\"} 75066288152
# HELP wireguard_latest_handshake_seconds Seconds from the last handshake # HELP wireguard_latest_handshake_seconds Seconds from the last handshake
# TYPE wireguard_latest_handshake_seconds gauge # TYPE wireguard_latest_handshake_seconds gauge
wireguard_latest_handshake_seconds{interface=\"wg0\",public_key=\"923V/iAdcz8BcqB0Xo6pDJzARGBJCQ6fWe+peixQyB4=\",remote_ip=\"10.211.123.112\",allowed_ip_0=\"10.90.0.10\",allowed_subnet_0=\"32\",allowed_ip_1=\"10.0.1.0\",allowed_subnet_1=\"24\",remote_port=\"51820\"} 0 wireguard_latest_handshake_seconds{interface=\"wg0\",public_key=\"923V/iAdcz8BcqB0Xo6pDJzARGBJCQ6fWe+peixQyB4=\",remote_ip=\"10.211.123.112\",allowed_ip_0=\"10.90.0.10\",allowed_subnet_0=\"32\",allowed_ip_1=\"10.0.1.0\",allowed_subnet_1=\"24\",remote_port=\"51820\"} 0
@ -451,7 +472,7 @@ wireguard_latest_handshake_seconds{interface=\"wg0\",public_key=\"sUsR6xufQQ8Tf0
#[test] #[test]
fn test_render_to_prometheus_simple() { fn test_render_to_prometheus_simple() {
const REF : &str= "# HELP wireguard_sent_bytes_total Bytes sent to the peer\n# TYPE wireguard_sent_bytes_total counter\nwireguard_sent_bytes_total{interface=\"Pippo\",public_key=\"test\",allowed_ips=\"to_change\",remote_ip=\"remote_ip\",remote_port=\"100\"} 1000\n# HELP wireguard_received_bytes_total Bytes received from the peer\n# TYPE wireguard_received_bytes_total counter\nwireguard_received_bytes_total{interface=\"Pippo\",public_key=\"test\",allowed_ips=\"to_change\",remote_ip=\"remote_ip\",remote_port=\"100\"} 5000\n# HELP wireguard_latest_handshake_seconds Seconds from the last handshake\n# TYPE wireguard_latest_handshake_seconds gauge\nwireguard_latest_handshake_seconds{interface=\"Pippo\",public_key=\"test\",allowed_ips=\"to_change\",remote_ip=\"remote_ip\",remote_port=\"100\"} 500\n"; const REF : &str= "# HELP wireguard_sent_bytes_total Bytes sent to the peer\n# TYPE wireguard_sent_bytes_total counter\nwireguard_sent_bytes_total{interface=\"Pippo\",public_key=\"test\",allowed_ips=\"to_change\",remote_ip=\"remote_ip\",remote_port=\"100\"} 1000\n\n# HELP wireguard_received_bytes_total Bytes received from the peer\n# TYPE wireguard_received_bytes_total counter\nwireguard_received_bytes_total{interface=\"Pippo\",public_key=\"test\",allowed_ips=\"to_change\",remote_ip=\"remote_ip\",remote_port=\"100\"} 5000\n\n# HELP wireguard_latest_handshake_seconds Seconds from the last handshake\n# TYPE wireguard_latest_handshake_seconds gauge\nwireguard_latest_handshake_seconds{interface=\"Pippo\",public_key=\"test\",allowed_ips=\"to_change\",remote_ip=\"remote_ip\",remote_port=\"100\"} 500\n";
let re = Endpoint::Remote(RemoteEndpoint { let re = Endpoint::Remote(RemoteEndpoint {
public_key: "test".to_owned(), public_key: "test".to_owned(),
@ -480,11 +501,13 @@ wireguard_latest_handshake_seconds{interface=\"wg0\",public_key=\"sUsR6xufQQ8Tf0
fn test_render_to_prometheus_complex() { fn test_render_to_prometheus_complex() {
use crate::wireguard_config::PeerEntry; use crate::wireguard_config::PeerEntry;
const REF :&'static str = "# HELP wireguard_sent_bytes_total Bytes sent to the peer\n# TYPE wireguard_sent_bytes_total counter\nwireguard_sent_bytes_total{interface=\"Pippo\",public_key=\"test\",allowed_ips=\"10.0.0.2/32,fd86:ea04:::4/128\",remote_ip=\"remote_ip\",remote_port=\"100\"} 1000\nwireguard_sent_bytes_total{interface=\"Pippo\",public_key=\"second_test\",allowed_ips=\"10.0.0.4/32,fd86:ea04:::4/128,192.168.0.0/16\",friendly_name=\"this is my friendly name\",remote_ip=\"remote_ip\",remote_port=\"100\"} 14\n# HELP wireguard_received_bytes_total Bytes received from the peer\n# TYPE wireguard_received_bytes_total counter\nwireguard_received_bytes_total{interface=\"Pippo\",public_key=\"test\",allowed_ips=\"10.0.0.2/32,fd86:ea04:::4/128\",remote_ip=\"remote_ip\",remote_port=\"100\"} 5000\nwireguard_received_bytes_total{interface=\"Pippo\",public_key=\"second_test\",allowed_ips=\"10.0.0.4/32,fd86:ea04:::4/128,192.168.0.0/16\",friendly_name=\"this is my friendly name\",remote_ip=\"remote_ip\",remote_port=\"100\"} 1000000000\n# HELP wireguard_latest_handshake_seconds Seconds from the last handshake\n# TYPE wireguard_latest_handshake_seconds gauge\nwireguard_latest_handshake_seconds{interface=\"Pippo\",public_key=\"test\",allowed_ips=\"10.0.0.2/32,fd86:ea04:::4/128\",remote_ip=\"remote_ip\",remote_port=\"100\"} 500\nwireguard_latest_handshake_seconds{interface=\"Pippo\",public_key=\"second_test\",allowed_ips=\"10.0.0.4/32,fd86:ea04:::4/128,192.168.0.0/16\",friendly_name=\"this is my friendly name\",remote_ip=\"remote_ip\",remote_port=\"100\"} 50\n"; const REF :&'static str = "# HELP wireguard_sent_bytes_total Bytes sent to the peer\n# TYPE wireguard_sent_bytes_total counter\nwireguard_sent_bytes_total{interface=\"Pippo\",public_key=\"test\",allowed_ips=\"10.0.0.2/32,fd86:ea04:::4/128\",remote_ip=\"remote_ip\",remote_port=\"100\"} 1000\nwireguard_sent_bytes_total{interface=\"Pippo\",public_key=\"second_test\",allowed_ips=\"10.0.0.4/32,fd86:ea04:::4/128,192.168.0.0/16\",friendly_name=\"this is my friendly name\",remote_ip=\"remote_ip\",remote_port=\"100\"} 14\n\n# HELP wireguard_received_bytes_total Bytes received from the peer\n# TYPE wireguard_received_bytes_total counter\nwireguard_received_bytes_total{interface=\"Pippo\",public_key=\"test\",allowed_ips=\"10.0.0.2/32,fd86:ea04:::4/128\",remote_ip=\"remote_ip\",remote_port=\"100\"} 5000\nwireguard_received_bytes_total{interface=\"Pippo\",public_key=\"second_test\",allowed_ips=\"10.0.0.4/32,fd86:ea04:::4/128,192.168.0.0/16\",friendly_name=\"this is my friendly name\",remote_ip=\"remote_ip\",remote_port=\"100\"} 1000000000\n\n# HELP wireguard_latest_handshake_seconds Seconds from the last handshake\n# TYPE wireguard_latest_handshake_seconds gauge\nwireguard_latest_handshake_seconds{interface=\"Pippo\",public_key=\"test\",allowed_ips=\"10.0.0.2/32,fd86:ea04:::4/128\",remote_ip=\"remote_ip\",remote_port=\"100\"} 500\nwireguard_latest_handshake_seconds{interface=\"Pippo\",public_key=\"second_test\",allowed_ips=\"10.0.0.4/32,fd86:ea04:::4/128,192.168.0.0/16\",friendly_name=\"this is my friendly name\",remote_ip=\"remote_ip\",remote_port=\"100\"} 50\n";
const REF_SPLIT :&'static str = "# HELP wireguard_sent_bytes_total Bytes sent to the peer\n# TYPE wireguard_sent_bytes_total counter\nwireguard_sent_bytes_total{interface=\"Pippo\",public_key=\"test\",remote_ip=\"remote_ip\",allowed_ip_0=\"10.0.0.2\",allowed_subnet_0=\"32\",allowed_ip_1=\"fd86:ea04:::4\",allowed_subnet_1=\"128\",remote_port=\"100\"} 1000\nwireguard_sent_bytes_total{interface=\"Pippo\",public_key=\"second_test\",friendly_name=\"this is my friendly name\",remote_ip=\"remote_ip\",allowed_ip_0=\"10.0.0.4\",allowed_subnet_0=\"32\",allowed_ip_1=\"fd86:ea04:::4\",allowed_subnet_1=\"128\",allowed_ip_2=\"192.168.0.0\",allowed_subnet_2=\"16\",remote_port=\"100\"} 14\n# HELP wireguard_received_bytes_total Bytes received from the peer\n# TYPE wireguard_received_bytes_total counter\nwireguard_received_bytes_total{interface=\"Pippo\",public_key=\"test\",remote_ip=\"remote_ip\",allowed_ip_0=\"10.0.0.2\",allowed_subnet_0=\"32\",allowed_ip_1=\"fd86:ea04:::4\",allowed_subnet_1=\"128\",remote_port=\"100\"} 5000\nwireguard_received_bytes_total{interface=\"Pippo\",public_key=\"second_test\",friendly_name=\"this is my friendly name\",remote_ip=\"remote_ip\",allowed_ip_0=\"10.0.0.4\",allowed_subnet_0=\"32\",allowed_ip_1=\"fd86:ea04:::4\",allowed_subnet_1=\"128\",allowed_ip_2=\"192.168.0.0\",allowed_subnet_2=\"16\",remote_port=\"100\"} 1000000000\n# HELP wireguard_latest_handshake_seconds Seconds from the last handshake\n# TYPE wireguard_latest_handshake_seconds gauge\nwireguard_latest_handshake_seconds{interface=\"Pippo\",public_key=\"test\",remote_ip=\"remote_ip\",allowed_ip_0=\"10.0.0.2\",allowed_subnet_0=\"32\",allowed_ip_1=\"fd86:ea04:::4\",allowed_subnet_1=\"128\",remote_port=\"100\"} 500\nwireguard_latest_handshake_seconds{interface=\"Pippo\",public_key=\"second_test\",friendly_name=\"this is my friendly name\",remote_ip=\"remote_ip\",allowed_ip_0=\"10.0.0.4\",allowed_subnet_0=\"32\",allowed_ip_1=\"fd86:ea04:::4\",allowed_subnet_1=\"128\",allowed_ip_2=\"192.168.0.0\",allowed_subnet_2=\"16\",remote_port=\"100\"} 50\n"; const REF_SPLIT :&'static str = "# HELP wireguard_sent_bytes_total Bytes sent to the peer\n# TYPE wireguard_sent_bytes_total counter\nwireguard_sent_bytes_total{interface=\"Pippo\",public_key=\"test\",remote_ip=\"remote_ip\",allowed_ip_0=\"10.0.0.2\",allowed_subnet_0=\"32\",allowed_ip_1=\"fd86:ea04:::4\",allowed_subnet_1=\"128\",remote_port=\"100\"} 1000\nwireguard_sent_bytes_total{interface=\"Pippo\",public_key=\"second_test\",friendly_name=\"this is my friendly name\",remote_ip=\"remote_ip\",allowed_ip_0=\"10.0.0.4\",allowed_subnet_0=\"32\",allowed_ip_1=\"fd86:ea04:::4\",allowed_subnet_1=\"128\",allowed_ip_2=\"192.168.0.0\",allowed_subnet_2=\"16\",remote_port=\"100\"} 14\n\n# HELP wireguard_received_bytes_total Bytes received from the peer\n# TYPE wireguard_received_bytes_total counter\nwireguard_received_bytes_total{interface=\"Pippo\",public_key=\"test\",remote_ip=\"remote_ip\",allowed_ip_0=\"10.0.0.2\",allowed_subnet_0=\"32\",allowed_ip_1=\"fd86:ea04:::4\",allowed_subnet_1=\"128\",remote_port=\"100\"} 5000\nwireguard_received_bytes_total{interface=\"Pippo\",public_key=\"second_test\",friendly_name=\"this is my friendly name\",remote_ip=\"remote_ip\",allowed_ip_0=\"10.0.0.4\",allowed_subnet_0=\"32\",allowed_ip_1=\"fd86:ea04:::4\",allowed_subnet_1=\"128\",allowed_ip_2=\"192.168.0.0\",allowed_subnet_2=\"16\",remote_port=\"100\"} 1000000000\n\n# HELP wireguard_latest_handshake_seconds Seconds from the last handshake\n# TYPE wireguard_latest_handshake_seconds gauge\nwireguard_latest_handshake_seconds{interface=\"Pippo\",public_key=\"test\",remote_ip=\"remote_ip\",allowed_ip_0=\"10.0.0.2\",allowed_subnet_0=\"32\",allowed_ip_1=\"fd86:ea04:::4\",allowed_subnet_1=\"128\",remote_port=\"100\"} 500\nwireguard_latest_handshake_seconds{interface=\"Pippo\",public_key=\"second_test\",friendly_name=\"this is my friendly name\",remote_ip=\"remote_ip\",allowed_ip_0=\"10.0.0.4\",allowed_subnet_0=\"32\",allowed_ip_1=\"fd86:ea04:::4\",allowed_subnet_1=\"128\",allowed_ip_2=\"192.168.0.0\",allowed_subnet_2=\"16\",remote_port=\"100\"} 50\n";
const REF_SPLIT_NO_REMOTE :&'static str = "# HELP wireguard_sent_bytes_total Bytes sent to the peer\n# TYPE wireguard_sent_bytes_total counter\nwireguard_sent_bytes_total{interface=\"Pippo\",public_key=\"test\",allowed_ip_0=\"10.0.0.2\",allowed_subnet_0=\"32\",allowed_ip_1=\"fd86:ea04:::4\",allowed_subnet_1=\"128\"} 1000\nwireguard_sent_bytes_total{interface=\"Pippo\",public_key=\"second_test\",friendly_name=\"this is my friendly name\",allowed_ip_0=\"10.0.0.4\",allowed_subnet_0=\"32\",allowed_ip_1=\"fd86:ea04:::4\",allowed_subnet_1=\"128\",allowed_ip_2=\"192.168.0.0\",allowed_subnet_2=\"16\"} 14\n# HELP wireguard_received_bytes_total Bytes received from the peer\n# TYPE wireguard_received_bytes_total counter\nwireguard_received_bytes_total{interface=\"Pippo\",public_key=\"test\",allowed_ip_0=\"10.0.0.2\",allowed_subnet_0=\"32\",allowed_ip_1=\"fd86:ea04:::4\",allowed_subnet_1=\"128\"} 5000\nwireguard_received_bytes_total{interface=\"Pippo\",public_key=\"second_test\",friendly_name=\"this is my friendly name\",allowed_ip_0=\"10.0.0.4\",allowed_subnet_0=\"32\",allowed_ip_1=\"fd86:ea04:::4\",allowed_subnet_1=\"128\",allowed_ip_2=\"192.168.0.0\",allowed_subnet_2=\"16\"} 1000000000\n# HELP wireguard_latest_handshake_seconds Seconds from the last handshake\n# TYPE wireguard_latest_handshake_seconds gauge\nwireguard_latest_handshake_seconds{interface=\"Pippo\",public_key=\"test\",allowed_ip_0=\"10.0.0.2\",allowed_subnet_0=\"32\",allowed_ip_1=\"fd86:ea04:::4\",allowed_subnet_1=\"128\"} 500\nwireguard_latest_handshake_seconds{interface=\"Pippo\",public_key=\"second_test\",friendly_name=\"this is my friendly name\",allowed_ip_0=\"10.0.0.4\",allowed_subnet_0=\"32\",allowed_ip_1=\"fd86:ea04:::4\",allowed_subnet_1=\"128\",allowed_ip_2=\"192.168.0.0\",allowed_subnet_2=\"16\"} 50\n"; const REF_SPLIT_NO_REMOTE :&'static str = "# HELP wireguard_sent_bytes_total Bytes sent to the peer\n# TYPE wireguard_sent_bytes_total counter\nwireguard_sent_bytes_total{interface=\"Pippo\",public_key=\"test\",allowed_ip_0=\"10.0.0.2\",allowed_subnet_0=\"32\",allowed_ip_1=\"fd86:ea04:::4\",allowed_subnet_1=\"128\"} 1000\nwireguard_sent_bytes_total{interface=\"Pippo\",public_key=\"second_test\",friendly_name=\"this is my friendly name\",allowed_ip_0=\"10.0.0.4\",allowed_subnet_0=\"32\",allowed_ip_1=\"fd86:ea04:::4\",allowed_subnet_1=\"128\",allowed_ip_2=\"192.168.0.0\",allowed_subnet_2=\"16\"} 14\n\n# HELP wireguard_received_bytes_total Bytes received from the peer\n# TYPE wireguard_received_bytes_total counter\nwireguard_received_bytes_total{interface=\"Pippo\",public_key=\"test\",allowed_ip_0=\"10.0.0.2\",allowed_subnet_0=\"32\",allowed_ip_1=\"fd86:ea04:::4\",allowed_subnet_1=\"128\"} 5000\nwireguard_received_bytes_total{interface=\"Pippo\",public_key=\"second_test\",friendly_name=\"this is my friendly name\",allowed_ip_0=\"10.0.0.4\",allowed_subnet_0=\"32\",allowed_ip_1=\"fd86:ea04:::4\",allowed_subnet_1=\"128\",allowed_ip_2=\"192.168.0.0\",allowed_subnet_2=\"16\"} 1000000000\n\n# HELP wireguard_latest_handshake_seconds Seconds from the last handshake\n# TYPE wireguard_latest_handshake_seconds gauge\nwireguard_latest_handshake_seconds{interface=\"Pippo\",public_key=\"test\",allowed_ip_0=\"10.0.0.2\",allowed_subnet_0=\"32\",allowed_ip_1=\"fd86:ea04:::4\",allowed_subnet_1=\"128\"} 500\nwireguard_latest_handshake_seconds{interface=\"Pippo\",public_key=\"second_test\",friendly_name=\"this is my friendly name\",allowed_ip_0=\"10.0.0.4\",allowed_subnet_0=\"32\",allowed_ip_1=\"fd86:ea04:::4\",allowed_subnet_1=\"128\",allowed_ip_2=\"192.168.0.0\",allowed_subnet_2=\"16\"} 50\n";
const REF_JSON :&'static str = "# HELP wireguard_sent_bytes_total Bytes sent to the peer\n# TYPE wireguard_sent_bytes_total counter\nwireguard_sent_bytes_total{interface=\"Pippo\",public_key=\"test\",allowed_ips=\"10.0.0.2/32,fd86:ea04:::4/128\",remote_ip=\"remote_ip\",remote_port=\"100\"} 1000\nwireguard_sent_bytes_total{interface=\"Pippo\",public_key=\"second_test\",allowed_ips=\"10.0.0.4/32,fd86:ea04:::4/128,192.168.0.0/16\",remote_ip=\"remote_ip\",auth_date=\"1614869789\",first_name=\"Coordinator\",id=\"482217555\",last_name=\"DrProxy.me\",username=\"DrProxyMeCoordinator\",remote_port=\"100\"} 14\n\n# HELP wireguard_received_bytes_total Bytes received from the peer\n# TYPE wireguard_received_bytes_total counter\nwireguard_received_bytes_total{interface=\"Pippo\",public_key=\"test\",allowed_ips=\"10.0.0.2/32,fd86:ea04:::4/128\",remote_ip=\"remote_ip\",remote_port=\"100\"} 5000\nwireguard_received_bytes_total{interface=\"Pippo\",public_key=\"second_test\",allowed_ips=\"10.0.0.4/32,fd86:ea04:::4/128,192.168.0.0/16\",remote_ip=\"remote_ip\",auth_date=\"1614869789\",first_name=\"Coordinator\",id=\"482217555\",last_name=\"DrProxy.me\",username=\"DrProxyMeCoordinator\",remote_port=\"100\"} 1000000000\n\n# HELP wireguard_latest_handshake_seconds Seconds from the last handshake\n# TYPE wireguard_latest_handshake_seconds gauge\nwireguard_latest_handshake_seconds{interface=\"Pippo\",public_key=\"test\",allowed_ips=\"10.0.0.2/32,fd86:ea04:::4/128\",remote_ip=\"remote_ip\",remote_port=\"100\"} 500\nwireguard_latest_handshake_seconds{interface=\"Pippo\",public_key=\"second_test\",allowed_ips=\"10.0.0.4/32,fd86:ea04:::4/128,192.168.0.0/16\",remote_ip=\"remote_ip\",auth_date=\"1614869789\",first_name=\"Coordinator\",id=\"482217555\",last_name=\"DrProxy.me\",username=\"DrProxyMeCoordinator\",remote_port=\"100\"} 50\n";
let re1 = Endpoint::Remote(RemoteEndpoint { let re1 = Endpoint::Remote(RemoteEndpoint {
public_key: "test".to_owned(), public_key: "test".to_owned(),
@ -520,9 +543,11 @@ wireguard_latest_handshake_seconds{interface=\"wg0\",public_key=\"sUsR6xufQQ8Tf0
let pe = PeerEntry { let pe = PeerEntry {
public_key: "second_test", public_key: "second_test",
allowed_ips: "ignored", allowed_ips: "ignored",
name: Some("this is my friendly name"), friendly_description: Some(FriendlyDescription::Name(
"this is my friendly name".into(),
)),
}; };
pehm.insert(pe.public_key, pe); pehm.insert(pe.public_key, pe.clone());
let prometheus = wg.render_with_names(Some(&pehm), false, true); let prometheus = wg.render_with_names(Some(&pehm), false, true);
assert_eq!(prometheus, REF); assert_eq!(prometheus, REF);
@ -532,5 +557,33 @@ wireguard_latest_handshake_seconds{interface=\"wg0\",public_key=\"sUsR6xufQQ8Tf0
let prometheus = wg.render_with_names(Some(&pehm), true, false); let prometheus = wg.render_with_names(Some(&pehm), true, false);
assert_eq!(prometheus, REF_SPLIT_NO_REMOTE); assert_eq!(prometheus, REF_SPLIT_NO_REMOTE);
// second test
let mut pehm = PeerEntryHashMap::new();
let mut hm = HashMap::new();
hm.insert(
"username",
serde_json::Value::String("DrProxyMeCoordinator".to_owned()),
);
hm.insert("id", serde_json::Value::Number(482217555.into()));
hm.insert(
"first_name",
serde_json::Value::String("Coordinator".to_owned()),
);
hm.insert(
"last_name",
serde_json::Value::String("DrProxy.me".to_owned()),
);
hm.insert("auth_date", serde_json::Value::Number(1614869789.into()));
let pe = PeerEntry {
public_key: "second_test",
allowed_ips: "ignored",
friendly_description: Some(FriendlyDescription::Json(hm)),
};
pehm.insert(pe.public_key, pe.clone());
let prometheus = wg.render_with_names(Some(&pehm), false, true);
assert_eq!(prometheus, REF_JSON);
} }
} }

View file

@ -1,13 +1,15 @@
use crate::exporter_error::PeerEntryParseError; use crate::exporter_error::PeerEntryParseError;
use crate::FriendlyDescription;
use log::debug; use log::debug;
use std::collections::HashMap; use std::collections::HashMap;
use std::convert::TryFrom; use std::convert::TryFrom;
use std::convert::TryInto;
#[derive(Debug, Default, Clone)] #[derive(Debug, Default, Clone)]
pub(crate) struct PeerEntry<'a> { pub(crate) struct PeerEntry<'a> {
pub public_key: &'a str, pub public_key: &'a str,
pub allowed_ips: &'a str, pub allowed_ips: &'a str,
pub name: Option<&'a str>, pub friendly_description: Option<FriendlyDescription<'a>>,
} }
fn after_char(s: &str, c_split: char) -> &str { fn after_char(s: &str, c_split: char) -> &str {
@ -55,7 +57,7 @@ impl<'a> TryFrom<&[&'a str]> for PeerEntry<'a> {
let mut public_key = ""; let mut public_key = "";
let mut allowed_ips = ""; let mut allowed_ips = "";
let mut name = None; let mut friendly_description = None;
for line in lines { for line in lines {
let line_lowercase = line.to_lowercase(); let line_lowercase = line.to_lowercase();
@ -71,11 +73,9 @@ impl<'a> TryFrom<&[&'a str]> for PeerEntry<'a> {
// if it's a supported key, let' map it. // if it's a supported key, let' map it.
// we support one key now but this way // we support one key now but this way
// we can support more in the future // we can support more in the future
#[allow(clippy::single_match)]
match key { match key {
"friendly_name" => { "friendly_name" => friendly_description = Some((key, value).try_into()?),
name = Some(value); "friendly_json" => friendly_description = Some((key, value).try_into()?),
}
_ => {} _ => {}
} }
} }
@ -97,7 +97,7 @@ impl<'a> TryFrom<&[&'a str]> for PeerEntry<'a> {
let pe = PeerEntry { let pe = PeerEntry {
public_key, public_key,
allowed_ips, allowed_ips,
name, // name can be None friendly_description, // name can be None
}; };
debug!("PeerEntry::TryFrom returning PeerEntryHasMap == {:?}", pe); debug!("PeerEntry::TryFrom returning PeerEntryHasMap == {:?}", pe);
Ok(pe) Ok(pe)
@ -157,6 +157,7 @@ pub(crate) fn peer_entry_hashmap_try_from(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::FriendlyDescription;
use super::*; use super::*;
const TEXT: &'static str = " const TEXT: &'static str = "
@ -197,6 +198,50 @@ AllowedIPs = 10.70.0.50/32
PublicKey = lqYcojJMsIZXMUw1heAFbQHBoKjCEaeo7M1WXDh/KWc= # other comment PublicKey = lqYcojJMsIZXMUw1heAFbQHBoKjCEaeo7M1WXDh/KWc= # other comment
AllowedIPs = 10.70.0.40/32 AllowedIPs = 10.70.0.40/32
[Peer]
#friendly_name = OnePlus 5T
PublicKey = 928vO9Lf4+Mo84cWu4k1oRyzf0AR7FTGoPKHGoTMSHk=
AllowedIPs = 10.70.0.80/32
";
const TEXT_JSON: &'static str = "
ListenPort = 51820
PrivateKey = my_super_secret_private_key
# PreUp = iptables -t nat -A POSTROUTING -s 10.70.0.0/24 -o enp7s0 -j MASQUERADE
# PostDown = iptables -t nat -D POSTROUTING -s 10.70.0.0/24 -o enp7s0 -j MASQUERADE
[Peer]
# This is a comment
# friendly_name=OnePlus 6T
# This is a comment
# This is a comment
# This is a comment
# This is a comment
PublicKey = 2S7mA0vEMethCNQrJpJKE81/JmhgtB+tHHLYQhgM6kk=
AllowedIPs = 10.70.0.2/32 # this is a comment in AllowedIPs line
[Peer]
# friendly_name=varch.local (laptop)
PublicKey = qnoxQoQI8KKMupLnSSureORV0wMmH7JryZNsmGVISzU=
AllowedIPs = 10.70.0.3/32
[Peer]
# friendly_json={\"id\":482217555,\"username\":\"DrProxyMeCoordinator\", \"first_name\": \"Coordinator\", \"last_name\": \"DrProxy.me\" ,\"auth_date\":1614869789}
PublicKey = L2UoJZN7RmEKsMmqaJgKG0m1S2Zs2wd2ptAf+kb3008=
AllowedIPs = 10.70.0.4/32
[Peer]
# frcognoarch
PublicKey = MdVOIPKt9K2MPj/sO2NlWQbOnFJ6L/qX80mmhQwsUlA=
AllowedIPs = 10.70.0.50/32
[Peer]
# This is a comment
# friendly_name = frcognowin10
# This is something
PublicKey = lqYcojJMsIZXMUw1heAFbQHBoKjCEaeo7M1WXDh/KWc= # other comment
AllowedIPs = 10.70.0.40/32
[Peer] [Peer]
#friendly_name = OnePlus 5T #friendly_name = OnePlus 5T
PublicKey = 928vO9Lf4+Mo84cWu4k1oRyzf0AR7FTGoPKHGoTMSHk= PublicKey = 928vO9Lf4+Mo84cWu4k1oRyzf0AR7FTGoPKHGoTMSHk=
@ -278,25 +323,62 @@ PublicKey = L2UoJZN7RmEKsMmqaJgKG0m1S2Zs2wd2ptAf+kb3008=
} }
#[test] #[test]
fn test_parse_friendly_name() { fn test_parse_friendly_description_json() {
let a: PeerEntryHashMap = peer_entry_hashmap_try_from(TEXT_JSON).unwrap();
let entry = a.get("L2UoJZN7RmEKsMmqaJgKG0m1S2Zs2wd2ptAf+kb3008=");
let entry = entry.expect("this should have been Some (with json!)!");
let mut hm = HashMap::new();
hm.insert(
"username",
serde_json::Value::String("DrProxyMeCoordinator".to_owned()),
);
hm.insert("id", serde_json::Value::Number(482217555.into()));
hm.insert(
"first_name",
serde_json::Value::String("Coordinator".to_owned()),
);
hm.insert(
"last_name",
serde_json::Value::String("DrProxy.me".to_owned()),
);
hm.insert("auth_date", serde_json::Value::Number(1614869789.into()));
assert_eq!(
Some(FriendlyDescription::Json(hm)),
entry.friendly_description
);
}
#[test]
fn test_parse_friendly_description_name() {
let a: PeerEntryHashMap = peer_entry_hashmap_try_from(TEXT).unwrap(); let a: PeerEntryHashMap = peer_entry_hashmap_try_from(TEXT).unwrap();
let entry = a.get("lqYcojJMsIZXMUw1heAFbQHBoKjCEaeo7M1WXDh/KWc="); let entry = a.get("lqYcojJMsIZXMUw1heAFbQHBoKjCEaeo7M1WXDh/KWc=");
let entry = entry.expect("this should have been Some (frcognowin10)!"); let entry = entry.expect("this should have been Some (frcognowin10)!");
assert_eq!(Some("frcognowin10"), entry.name); assert_eq!(
Some(FriendlyDescription::Name("frcognowin10".into())),
entry.friendly_description
);
let entry = a.get("2S7mA0vEMethCNQrJpJKE81/JmhgtB+tHHLYQhgM6kk="); let entry = a.get("2S7mA0vEMethCNQrJpJKE81/JmhgtB+tHHLYQhgM6kk=");
let entry = entry.expect("this should have been Some!"); let entry = entry.expect("this should have been Some!");
assert_eq!(Some("OnePlus 6T"), entry.name); assert_eq!(
Some(FriendlyDescription::Name("OnePlus 6T".into())),
entry.friendly_description
);
assert_eq!(entry.allowed_ips, "10.70.0.2/32"); assert_eq!(entry.allowed_ips, "10.70.0.2/32");
let entry = a.get("928vO9Lf4+Mo84cWu4k1oRyzf0AR7FTGoPKHGoTMSHk="); let entry = a.get("928vO9Lf4+Mo84cWu4k1oRyzf0AR7FTGoPKHGoTMSHk=");
let entry = entry.expect("this should have been Some!"); let entry = entry.expect("this should have been Some!");
assert_eq!(Some("OnePlus 5T"), entry.name); assert_eq!(
Some(FriendlyDescription::Name("OnePlus 5T".into())),
entry.friendly_description
);
let entry = a.get("MdVOIPKt9K2MPj/sO2NlWQbOnFJ6L/qX80mmhQwsUlA="); let entry = a.get("MdVOIPKt9K2MPj/sO2NlWQbOnFJ6L/qX80mmhQwsUlA=");
let entry = entry.expect("this should have been Some!"); let entry = entry.expect("this should have been Some!");
assert_eq!(None, entry.name); assert_eq!(None, entry.friendly_description);
} }
#[test] #[test]