Added filtering and attribute flags, improved bes_wifi by adding ssids

and tags to the equasion
This commit is contained in:
2026-11-17 15:04:56 +02:00
parent a09c4ba2cc
commit 2306d5f586
11 changed files with 213 additions and 73 deletions

112
Cargo.lock generated
View File

@@ -250,9 +250,9 @@ checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "darling"
version = "0.21.3"
version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9cdf337090841a411e2a7f3deb9187445851f91b309c0c0a29e05f74a00a48c0"
checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"
dependencies = [
"darling_core",
"darling_macro",
@@ -260,27 +260,26 @@ dependencies = [
[[package]]
name = "darling_core"
version = "0.21.3"
version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1247195ecd7e3c85f83c8d2a366e4210d588e802133e1e355180a9870b517ea4"
checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"
dependencies = [
"fnv",
"ident_case",
"proc-macro2",
"quote",
"strsim",
"syn 2.0.118",
"syn 3.0.3",
]
[[package]]
name = "darling_macro"
version = "0.21.3"
version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d38308df82d1080de0afee5d069fa14b0326a88c14f15c5ccda35b4a6c414c81"
checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"
dependencies = [
"darling_core",
"quote",
"syn 2.0.118",
"syn 3.0.3",
]
[[package]]
@@ -317,9 +316,9 @@ dependencies = [
[[package]]
name = "diesel"
version = "2.3.12"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "715377c6e464cb44bb89bd8487584240516c8d5052bc645d6babc50bb8be46c3"
checksum = "9824c36a57a17ece4c8883baed41dc3eb81b2b949364c174750acc462e19b5ec"
dependencies = [
"bitflags 2.13.0",
"byteorder",
@@ -330,27 +329,41 @@ dependencies = [
"mysqlclient-sys",
"percent-encoding",
"pq-sys",
"serde_json",
"sqlstate",
"url",
]
[[package]]
name = "diesel_derives"
version = "2.3.9"
name = "diesel_attribute_parser"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d1817b7f4279b947fc4cafddec12b0e5f8727141706561ce3ac94a60bddd1cf5"
checksum = "de6c008369e0bc4e26f385874b8d1da517112b4ebe2f8e6b1e3331c781039d71"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.3",
]
[[package]]
name = "diesel_derives"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90c0b085880f70a6668dd2365040f4dd07aaf6ebe9e6b8626528efcb0553a780"
dependencies = [
"diesel_attribute_parser",
"diesel_table_macro_syntax",
"dsl_auto_type",
"proc-macro2",
"quote",
"syn 2.0.118",
"syn 3.0.3",
]
[[package]]
name = "diesel_migrations"
version = "2.3.2"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28d0f4a98124ba6d4ca75da535f65984badec16a003b6e2f94a01e31a79490b8"
checksum = "08c9f048650c19d17cbe5918afd81d21a5c1c92f5f37dd9a66846958cd81c3c0"
dependencies = [
"diesel",
"migrations_internals",
@@ -359,11 +372,11 @@ dependencies = [
[[package]]
name = "diesel_table_macro_syntax"
version = "0.3.0"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe2444076b48641147115697648dc743c2c00b61adade0f01ce67133c7babe8c"
checksum = "d05c7977b58892eda3f17d46fd57fb23e865d1e54f59b224a6cc09935013747c"
dependencies = [
"syn 2.0.118",
"syn 3.0.3",
]
[[package]]
@@ -385,16 +398,16 @@ checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc"
[[package]]
name = "dsl_auto_type"
version = "0.2.0"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd122633e4bef06db27737f21d3738fb89c8f6d5360d6d9d7635dda142a7757e"
checksum = "cc51ea5a4c1cfac05a51e51cdbb6a5471bbb88091fcb045a27ff13b38e9a3204"
dependencies = [
"darling",
"either",
"heck",
"proc-macro2",
"quote",
"syn 2.0.118",
"syn 3.0.3",
]
[[package]]
@@ -843,23 +856,24 @@ checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4"
[[package]]
name = "migrations_internals"
version = "2.3.0"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36c791ecdf977c99f45f23280405d7723727470f6689a5e6dbf513ac547ae10d"
checksum = "ec54a4ea92c533f8ed6b8c80dc4bbd60f5b578b173399d92f19bfb5a34bd99a3"
dependencies = [
"serde",
"toml 0.9.12+spec-1.1.0",
"toml",
]
[[package]]
name = "migrations_macros"
version = "2.3.0"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36fc5ac76be324cfd2d3f2cf0fdf5d5d3c4f14ed8aaebadb09e304ba42282703"
checksum = "befb6974b8d7e9d8c48865f5f38f170f0db42faacdbc54682846bee108e0ef81"
dependencies = [
"migrations_internals",
"proc-macro2",
"quote",
"syn 3.0.3",
]
[[package]]
@@ -1317,6 +1331,12 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "sqlstate"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "858cea190fe7555971c35a5eb336858f1bf962a2bd7ceb8704fb1759b36af2cd"
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
@@ -1472,19 +1492,6 @@ dependencies = [
"tokio",
]
[[package]]
name = "toml"
version = "0.9.12+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863"
dependencies = [
"serde_core",
"serde_spanned",
"toml_datetime 0.7.5+spec-1.1.0",
"toml_parser",
"winnow 0.7.15",
]
[[package]]
name = "toml"
version = "1.1.2+spec-1.1.0"
@@ -1494,19 +1501,10 @@ dependencies = [
"indexmap",
"serde_core",
"serde_spanned",
"toml_datetime 1.1.1+spec-1.1.0",
"toml_datetime",
"toml_parser",
"toml_writer",
"winnow 1.0.3",
]
[[package]]
name = "toml_datetime"
version = "0.7.5+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347"
dependencies = [
"serde_core",
"winnow",
]
[[package]]
@@ -1524,7 +1522,7 @@ version = "1.1.2+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526"
dependencies = [
"winnow 1.0.3",
"winnow",
]
[[package]]
@@ -1623,7 +1621,7 @@ dependencies = [
"serde_json",
"tabled",
"tokio",
"toml 1.1.2+spec-1.1.0",
"toml",
]
[[package]]
@@ -1818,12 +1816,6 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "winnow"
version = "0.7.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
[[package]]
name = "winnow"
version = "1.0.3"

View File

@@ -13,7 +13,7 @@ camino = { version = "1.2.4", features = ["serde1"] }
chrono = "0.4.45"
clap = { version = "4.6.1", features = ["derive"] }
diesel = { version = "2.3.12", features = ["chrono", "postgres", "mysql"] }
diesel_migrations = "2.3.2"
diesel_migrations = "2.4.0"
mysqlclient-sys = { version = "0.5", features = ["bundled"] }
env_logger = "0.11.11"
futures = "0.3.34"

View File

@@ -0,0 +1,8 @@
ALTER TABLE client_statistics
DROP COLUMN ssid;
ALTER TABLE client_readings
DROP COLUMN ssid;
ALTER TABLE antennas
DROP COLUMN tags;

View File

@@ -0,0 +1,8 @@
ALTER TABLE client_statistics
ADD COLUMN ssid VARCHAR(32) NULL;
ALTER TABLE client_readings
ADD COLUMN ssid VARCHAR(32) NULL;
ALTER TABLE antennas
ADD COLUMN tags TEXT;

View File

@@ -1,11 +1,9 @@
use std::collections::{BTreeMap, HashMap};
use std::ops::Deref;
use std::str::FromStr;
use std::collections::HashMap;
use std::fmt::Debug;
use chrono::{Duration, NaiveDateTime, Utc};
use diesel::query_builder::AsQuery;
use diesel::query_dsl::methods::{FilterDsl, SelectDsl};
use diesel::{ExpressionMethods, OptionalExtension, QueryResult, RunQueryDsl, sql_query};
use diesel::{ExpressionMethods, OptionalExtension, RunQueryDsl};
use crate::config::cli::MtCommand;
use crate::config::{Config, ConfigHost};
@@ -25,12 +23,14 @@ pub async fn run_bes_wifi_collection(
.values(&NewAntenna {
name: host.name.clone(),
ip: host.ip.to_string(),
tags: host.tags.join(", "),
error: None,
})
.on_conflict(diesel::dsl::DuplicatedKeys)
.do_update()
.set((
antennas::name.eq(host.name.clone()),
antennas::tags.eq(host.tags.join(", ")),
antennas::error.eq(&None as &Option<String>),
))
.execute(&mut conn)
@@ -40,14 +40,14 @@ pub async fn run_bes_wifi_collection(
let v6_hosts = cfg
.hosts
.iter()
.filter(|v| v.tags.contains(&"v6".to_string()))
.filter(|v| v.tags.contains(&"ros_ver=6".to_string()))
.cloned()
.collect::<Vec<_>>();
let v7_hosts = cfg
.hosts
.iter()
.filter(|v| v.tags.contains(&"v7".to_string()))
.filter(|v| v.tags.contains(&"ros_ver=7".to_string()))
.cloned()
.collect::<Vec<_>>();
@@ -93,7 +93,8 @@ pub async fn run_bes_wifi_collection(
for (antenna, res) in v6_res?.iter().chain(v7_res?.iter()) {
match res {
Ok(vals) if antenna.tags.contains(&"v7".to_string()) => {
Ok(vals) if antenna.tags.contains(&"ros_ver=7".to_string()) => {
// log::error!("v7: {vals:#?}");
for val in vals {
records.push(NewClientReadingTimed {
ip: Default::default(),
@@ -114,11 +115,16 @@ pub async fn run_bes_wifi_collection(
.cloned()
.ok(),
read_at: Utc::now().naive_utc(),
ssid: get_val_from_cmd_output(antenna, val, "ssid")
.cloned()
.ok(),
});
}
}
Ok(vals) if antenna.tags.contains(&"v6".to_string()) => {
Ok(vals) if antenna.tags.contains(&"ros_ver=6".to_string()) => {
for val in vals {
// log::error!("v6: {:#?}", val.get("last-ip"));
records.push(NewClientReadingTimed {
ip: get_val_from_cmd_output(antenna, val, "last-ip")
.cloned()
@@ -152,6 +158,24 @@ pub async fn run_bes_wifi_collection(
.cloned()
.ok(),
read_at: Utc::now().naive_utc(),
ssid: {
let wlan_if = get_val_from_cmd_output(antenna, val, "interface")
.cloned()
.ok().expect("No wireless interface provided");
let ssid_cmd = MtCommand::builder("/interface/wireless/print")
.attribute(".proplist=name,ssid")?
.filter(&format!("name={wlan_if}"))?
.build();
let mut _vals = crate::mt_commander::MtCommander::run_command_on_host(antenna, &ssid_cmd).await?;
let mut ssid = None;
for _val in _vals {
ssid = get_val_from_cmd_output(antenna, &_val, "ssid")
.cloned()
.ok();
}
ssid
}
});
}
}
@@ -174,11 +198,13 @@ pub async fn run_bes_wifi_collection(
}
}
fn get_val_from_cmd_output<'a, T>(
fn get_val_from_cmd_output<'a, T: Debug>(
antenna: &ConfigHost,
command_output: &'a HashMap<String, Option<T>>,
key: &str,
) -> anyhow::Result<&'a T> {
// log::error!("in1 {:?}", command_output);
// log::error!("in1 {:?}", command_output.get("last-ip"));
match command_output.get(key) {
Some(Some(val)) => Ok(val),
Some(None) => {

View File

@@ -10,6 +10,7 @@
use std::net::IpAddr;
use clap::ArgGroup;
use serde::de::value;
#[derive(Debug, Clone, clap::Parser, Default)]
#[command(
@@ -172,6 +173,8 @@ pub struct MtCommand {
pub filter: Vec<Filter>
}
pub struct MtCommandBuilder(MtCommand);
impl MtCommand {
pub fn new(cmd: &str, attr: Vec<(String, Option<String>)>, filter: Vec<Filter>) -> Self {
Self {
@@ -179,6 +182,13 @@ impl MtCommand {
attr, filter
}
}
pub fn builder(cmd: &str) -> MtCommandBuilder {
MtCommandBuilder(Self {
cmd: cmd.to_string(),
attr: Default::default(),
filter: Default::default()
})
}
pub fn new_basic(cmd: &str) -> Self {
Self {
cmd: cmd.to_string(),
@@ -188,6 +198,72 @@ impl MtCommand {
}
}
impl MtCommandBuilder {
pub fn attribute_raw(mut self, key: String, value: Option<String>) -> Self {
self.0.attr.push((key, value));
self
}
pub fn filter_raw(mut self, key: String, op: FilterOp, value: String) -> Self {
self.0.filter.push(Filter { key, op, value });
self
}
pub fn attribute(self, s: &str) -> anyhow::Result<Self> {
let (key, value) = parse_attribute(&s).map_err(|e| anyhow::anyhow!(e))?;
Ok(self.attribute_raw(key, value))
}
pub fn filter(self, s: &str) -> anyhow::Result<Self> {
let Filter{key, op, value} = parse_filter(&s).map_err(|e| anyhow::anyhow!(e))?;
Ok(self.filter_raw(key, op, value))
}
pub fn build(self) -> MtCommand {
self.0
}
}
impl std::fmt::Display for MtCommand {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.cmd)?;
let mut words = Vec::new();
for filter in &self.filter {
let (operator, negate) = match filter.op {
FilterOp::Eq => ('=', false),
FilterOp::Neq => ('=', true),
FilterOp::Gt => ('>', false),
FilterOp::Lt => ('<', false),
FilterOp::Ge => ('<', true),
FilterOp::Le => ('>', true),
};
let prefix = match operator {
'>' => ">",
'<' => "<",
_ => "",
};
words.push(format!("?{prefix}{}={}", filter.key, filter.value));
if negate {
words.push("?#!".to_string());
}
}
for (key, value) in &self.attr {
words.push(match value {
Some(value) => format!("&={key}={value}"),
None => format!("&={key}"),
});
}
if !words.is_empty() {
write!(f, "{}", words.join(""))?;
}
Ok(())
}
}
fn parse_filter(s: &str) -> Result<Filter, String> {
let (key, op, value) = [">=", "<=", "!=", "=", ">", "<"]
.into_iter()

View File

@@ -9,6 +9,7 @@ pub struct Antenna {
pub name: String,
pub ip: String,
pub error: Option<String>,
pub tags: String
}
#[derive(Debug, Insertable)]
@@ -17,4 +18,5 @@ pub struct NewAntenna {
pub name: String,
pub ip: String,
pub error: Option<String>,
pub tags: String
}

View File

@@ -19,6 +19,7 @@ pub struct ClientReading {
pub radio_name: Option<String>,
pub tx_rate: Option<String>,
pub rx_rate: Option<String>,
pub ssid: Option<String>
}
#[derive(Debug, Clone, Insertable)]
@@ -33,6 +34,7 @@ pub struct NewClientReading {
pub radio_name: Option<String>,
pub tx_rate: Option<String>,
pub rx_rate: Option<String>,
pub ssid: Option<String>
}
#[derive(Debug, Clone, Insertable)]
#[diesel(table_name = crate::db::schema::client_readings)]
@@ -47,6 +49,7 @@ pub struct NewClientReadingTimed {
pub radio_name: Option<String>,
pub tx_rate: Option<String>,
pub rx_rate: Option<String>,
pub ssid: Option<String>
}
impl Into<NewClientReading> for NewClientReadingTimed {
@@ -61,6 +64,7 @@ impl Into<NewClientReading> for NewClientReadingTimed {
radio_name: self.radio_name,
tx_rate: self.tx_rate,
rx_rate: self.rx_rate,
ssid: self.ssid
}
}
}
@@ -78,6 +82,7 @@ impl Into<NewClientStatisticWithTime> for NewClientReadingTimed {
radio_name: self.radio_name,
tx_rate: self.tx_rate,
rx_rate: self.rx_rate,
ssid: self.ssid
}
}
}

View File

@@ -17,6 +17,7 @@ pub struct ClientStatistics {
pub radio_name: Option<String>,
pub tx_rate: Option<String>,
pub rx_rate: Option<String>,
pub ssid: Option<String>
}
#[derive(Debug, Clone, Insertable)]
@@ -31,6 +32,7 @@ pub struct NewClientStatistic {
pub radio_name: Option<String>,
pub tx_rate: Option<String>,
pub rx_rate: Option<String>,
pub ssid: Option<String>
}
#[derive(Debug, Clone, Insertable)]
@@ -46,4 +48,5 @@ pub struct NewClientStatisticWithTime {
pub radio_name: Option<String>,
pub tx_rate: Option<String>,
pub rx_rate: Option<String>,
pub ssid: Option<String>
}

View File

@@ -2,17 +2,20 @@
diesel::table! {
antennas (id) {
#[auto_increment]
id -> Bigint,
name -> Text,
#[max_length = 15]
ip -> Varchar,
error -> Nullable<Text>,
last_error_t -> Nullable<Timestamp>,
tags -> Text,
}
}
diesel::table! {
client_readings (id) {
#[auto_increment]
id -> Bigint,
#[max_length = 15]
ip -> Nullable<Varchar>,
@@ -30,11 +33,14 @@ diesel::table! {
tx_rate -> Nullable<Varchar>,
#[max_length = 50]
rx_rate -> Nullable<Varchar>,
#[max_length = 32]
ssid -> Nullable<Varchar>,
}
}
diesel::table! {
client_statistics (id) {
#[auto_increment]
id -> Bigint,
#[max_length = 15]
ip -> Nullable<Varchar>,
@@ -52,11 +58,14 @@ diesel::table! {
tx_rate -> Nullable<Varchar>,
#[max_length = 50]
rx_rate -> Nullable<Varchar>,
#[max_length = 32]
ssid -> Nullable<Varchar>,
}
}
diesel::table! {
wara (id) {
#[auto_increment]
id -> Bigint,
last_client_reading_cleanup -> Nullable<Timestamp>,
}

View File

@@ -50,7 +50,18 @@ impl MtCommander {
}))
.await;
let res_map: HashMap<_, _> = results.into_iter().collect();
let res_map: HashMap<_, _> = results
.into_iter()
.filter_map(|(h, res)| {
match &res {
Ok(_) => Some((h, res)),
Err(e) => {
log::error!("(Almost Fatal) Error running command: {e}");
None
}
}
})
.collect();
Ok(res_map)
}
}
@@ -197,7 +208,7 @@ impl MtCommanderInternal {
other => println!("{other:?}"),
}
}
log::info!("({addr}) Command finished, read {size} bytes");
log::info!("({addr}) Command `{command}` finished, read {size} bytes");
Ok(res)
}
}