Import current project code

This commit is contained in:
Your Name
2026-11-17 09:19:28 +02:00
parent 666ef42688
commit a09c4ba2cc
8 changed files with 251 additions and 27 deletions

12
.vscoded/settings.json Normal file
View File

@@ -0,0 +1,12 @@
{
"terminal.integrated.env.windows": {
"PQ_LIB_DIR": "D:\\vcpkg\\installed\\x64-windows\\lib",
"PQ_INCLUDE_DIR": "D:\\vcpkg\\installed\\x64-windows\\include",
"VCPKG_ROOT": "D:\\vcpkg",
"VCPKGRS_TRIPLET": "x64-windows",
"OPENSSL_DIR": "C:\\Program Files\\OpenSSL-Win64",
"OPENSSL_LIB_DIR": "C:\\Program Files\\OpenSSL-Win64\\lib\\VC\\x64\\MD",
"DEP_OPENSSL_ROOT": "C:\\Program Files\\OpenSSL-Win64",
"OPENSSL_INCLUDE_DIR": "C:\\Program Files\\OpenSSL-Win64\\include",
}
}

83
config copy.toml Normal file
View File

@@ -0,0 +1,83 @@
db_url = "postgres://my_database_user:password@localhost/my_database"
[default_logins]
username = "monitor"
password = "kLiMoniTor124!"
port = 8728
[[host]]
name = "KLI_P3"
ip = "10.5.7.103"
tags = ["v6"]
[[host]]
name = "KLI_P4"
ip = "10.5.7.164"
tags = ["v6"]
[[host]]
name = "KLI_VYTAUTAS"
ip = "10.5.7.132"
tags = ["v6"]
[[host]]
name = "KLI_5G_4"
ip = "10.5.7.107"
tags = ["v6"]
[[host]]
name = "KLI_I Riaubos g(5Ghz"
ip = "10.5.7.150"
tags = ["v6"]
[[host]]
name = "Besmegeniai_K1"
ip = "10.5.7.183"
tags = ["v6"]
[[host]]
name = "KLI_5G_5"
ip = "10.5.7.108"
tags = ["v6"]
[[host]]
name = "KLI_5G2"
ip = "10.5.7.135"
tags = ["v6"]
[[host]]
name = "Besmegeniai_D&G 40"
ip = "10.5.7.147"
tags = ["v6"]
[[host]]
name = "KLI_5G_DG_58"
ip = "10.5.7.118"
tags = ["v6"]
[[host]]
name = "KLI_M5_P2"
ip = "10.5.7.114"
tags = ["v6"]
[[host]]
name = "Besmegeniai_SODAS"
ip = "10.5.7.229"
tags = ["v6"]
[[host]]
name = "Besmegeniai_ANT"
ip = "10.5.7.230"
tags = ["v6"]
[[host]]
name = "Besmegeniai_DG"
ip = "10.5.7.14"
tags = ["v7"]
[[host]]
name = "KLI_siuncia Varkaliams"
ip = "10.5.9.36"
tags = ["v6"]

7
env.nu Normal file
View File

@@ -0,0 +1,7 @@
# $env.OPENSSL_DIR = "C:\\Program Files\\OpenSSL Library\\openssl-4.1"
$env.OPENSSL_DIR = "C:\\Program Files\\OpenSSL-Win64"
$env.OPENSSL_LIB_DIR = 'C:\Program Files\OpenSSL-Win64\lib\VC\x64\MD'
$env.DEP_OPENSSL_ROOT = $env.OPENSSL_DIR
$env.OPENSSL_LIB_DIR = ($env.OPENSSL_DIR | path join 'lib\VC\x64\MD')
$env.OPENSSL_INCLUDE_DIR = ($env.OPENSSL_DIR | path join 'include')
$env.PQ_LIB_DIR = 'D:\vcpkg\installed\x64-windows\lib'

View File

@@ -1,4 +1,4 @@
use std::collections::HashMap;
use std::collections::{BTreeMap, HashMap};
use std::ops::Deref;
use std::str::FromStr;
@@ -7,6 +7,7 @@ use diesel::query_builder::AsQuery;
use diesel::query_dsl::methods::{FilterDsl, SelectDsl};
use diesel::{ExpressionMethods, OptionalExtension, QueryResult, RunQueryDsl, sql_query};
use crate::config::cli::MtCommand;
use crate::config::{Config, ConfigHost};
use crate::db::DbConnection;
use crate::db::models::*;
@@ -50,8 +51,8 @@ pub async fn run_bes_wifi_collection(
.cloned()
.collect::<Vec<_>>();
let v6_cmd = "/interface/wireless/registration-table/print";
let v7_cmd = "/interface/wifi/registration-table/print";
let v6_cmd = MtCommand::new_basic("/interface/wireless/registration-table/print");
let v7_cmd = MtCommand::new_basic("/interface/wifi/registration-table/print");
let mut interval = tokio::time::interval(*interval);
@@ -82,9 +83,11 @@ pub async fn run_bes_wifi_collection(
}
}
let (v6_res, v7_res) = futures::join!(
crate::mt_commander::MtCommander::run_command_on_hosts(&v6_hosts, v6_cmd),
crate::mt_commander::MtCommander::run_command_on_hosts(&v7_hosts, v7_cmd),
crate::mt_commander::MtCommander::run_command_on_hosts(&v6_hosts, &v6_cmd),
crate::mt_commander::MtCommander::run_command_on_hosts(&v7_hosts, &v7_cmd),
);
let mut records = Vec::new();

View File

@@ -60,6 +60,12 @@ pub enum CliCommand {
/// Output format
#[arg(long, short = 'f')]
format: OutputFormat,
/// Filter command results (key=value)
#[arg(long, short = 'F', value_parser = parse_filter)]
filter: Vec<Filter>,
/// Add a command attribute (key=value or flag; repeatable)
#[arg(long, short = 'A', value_parser = parse_attribute)]
attributes: Vec<(String, Option<String>)>,
},
/// Run command continuosly
#[command(
@@ -142,3 +148,80 @@ pub enum OutputFormat {
Table,
Json,
}
#[derive(Debug, Clone, Copy)]
pub enum FilterOp {
Eq,
Gt,
Lt,
Neq,
Ge,
Le,
}
#[derive(Debug, Clone)]
pub struct Filter {
pub key: String,
pub op: FilterOp,
pub value: String,
}
#[derive(Debug, Clone)]
pub struct MtCommand {
pub cmd: String,
pub attr: Vec<(String, Option<String>)>,
pub filter: Vec<Filter>
}
impl MtCommand {
pub fn new(cmd: &str, attr: Vec<(String, Option<String>)>, filter: Vec<Filter>) -> Self {
Self {
cmd: cmd.to_string(),
attr, filter
}
}
pub fn new_basic(cmd: &str) -> Self {
Self {
cmd: cmd.to_string(),
attr: Default::default(),
filter: Default::default()
}
}
}
fn parse_filter(s: &str) -> Result<Filter, String> {
let (key, op, value) = [">=", "<=", "!=", "=", ">", "<"]
.into_iter()
.find_map(|op| {
s.split_once(op)
.map(|(key, value)| (key, op, value))
})
.ok_or_else(|| format!("invalid filter: {s}"))?;
let op = match op {
"=" => FilterOp::Eq,
"!=" => FilterOp::Neq,
">" => FilterOp::Gt,
"<" => FilterOp::Lt,
">=" => FilterOp::Ge,
"<=" => FilterOp::Le,
_ => unreachable!(),
};
Ok(Filter {
key: key.trim().to_string(),
op,
value: value.trim().to_string(),
})
}
fn parse_attribute(s: &str) -> Result<(String, Option<String>), String> {
let s = s.trim();
if let Some((key, value)) = s.split_once('=') {
Ok((key.trim().to_string(), Some(value.trim().to_string())))
} else if !s.is_empty() {
Ok((s.to_string(), None))
} else {
Err("empty attribute".to_string())
}
}

View File

@@ -66,6 +66,8 @@ pub struct HostDisplay {
pub username: String,
#[tabled(rename = "Pasword")]
pub password: String,
#[tabled(rename = "Tags")]
pub tags: String,
}
impl Config {
@@ -117,6 +119,7 @@ impl ConfigHost {
port: self.port(&cfg),
username: self.username(cfg).clone(),
password: self.password(cfg).clone(),
tags: self.tags.join(", ")
}
}
}

View File

@@ -18,8 +18,7 @@ use serde_json::json;
use tokio::time::Duration;
use crate::config::{
Config, ConfigHost,
cli::{CliCommand, CliDeviceCommand, OutputFormat},
Config, ConfigHost, cli::{CliCommand, CliDeviceCommand, MtCommand, OutputFormat},
};
mod bes_wifi;
@@ -48,20 +47,23 @@ async fn main() -> anyhow::Result<()> {
mt_commander::MtCommander::init(cfg.clone())?;
match &cfg.cli.command {
match cfg.cli.command.clone() {
CliCommand::BesWifi {
interval,
cleanup_interval,
} => bes_wifi::run_bes_wifi_collection(interval, cleanup_interval, &cfg).await?,
} => bes_wifi::run_bes_wifi_collection(&interval, &cleanup_interval, &cfg).await?,
CliCommand::Run {
all,
devices,
command,
format,
attributes,
filter,
} => {
let hosts = get_devices(devices, *all, &cfg)?;
let out = mt_commander::MtCommander::run_command_on_hosts(&hosts, command).await?;
print_output(&cfg, &out, format)?;
let hosts = get_devices(&devices, all, &cfg)?;
let cmd = MtCommand::new(&command, attributes, filter);
let out = mt_commander::MtCommander::run_command_on_hosts(&hosts,&cmd).await?;
print_output(&cfg, &out, &format)?;
}
CliCommand::Monitor {
all,
@@ -70,16 +72,20 @@ async fn main() -> anyhow::Result<()> {
interval,
format,
} => {
let hosts = get_devices(devices, *all, &cfg)?;
let hosts = get_devices(&devices, all, &cfg)?;
loop {
let out = mt_commander::MtCommander::run_command_on_hosts(&hosts, command).await?;
print_output(&cfg, &out, format)?;
tokio::time::sleep(Duration::from_secs_f32(*interval)).await;
let cmd = MtCommand::new(&command, Vec::default(), Vec::default());
let out = mt_commander::MtCommander::run_command_on_hosts(&hosts, &cmd).await?;
print_output(&cfg, &out, &format)?;
tokio::time::sleep(Duration::from_secs_f32(interval)).await;
}
}
CliCommand::Device { command } => match command.clone() {
CliCommand::Device { command } => match command {
CliDeviceCommand::List => {
let devices = cfg.hosts.iter().map(|h| h.display_tabled(&cfg));
let hosts = cfg.hosts.clone();
let devices = hosts
.into_iter()
.map(|ref h| h.display_tabled(&cfg));
let table = tabled::Table::new(devices);
println!("{}", table);
@@ -103,7 +109,7 @@ async fn main() -> anyhow::Result<()> {
}
CliDeviceCommand::Remove { name } => {
for (i, host) in cfg.hosts.iter().enumerate() {
if host.name == name {
if host.name == *name {
cfg.hosts.remove(i);
cfg.save()?;
return Ok(());

View File

@@ -9,15 +9,14 @@
use core::panic;
use std::{
collections::HashMap,
sync::{Arc, Mutex},
collections::{BTreeMap, HashMap}, sync::{Arc, Mutex},
};
use anyhow::bail;
use futures::future::join_all;
use mikrotik_rs::{CommandBuilder, Event, MikrotikDevice};
use mikrotik_rs::{CommandBuilder, Event, MikrotikDevice, QueryOperator, proto::word::Word::Attribute};
use crate::config::{Config, ConfigHost};
use crate::config::{Config, ConfigHost, cli::{FilterOp, MtCommand}};
lazy_static::lazy_static! {
static ref MTC: Arc<Mutex<MtCommanderInternal>> = MtCommanderInternal::new_mutex();
@@ -38,7 +37,7 @@ impl MtCommander {
pub fn run_command_on_hosts(
hosts: &[ConfigHost],
command: &str,
command: &MtCommand
) -> impl Future<
Output = anyhow::Result<
HashMap<ConfigHost, anyhow::Result<Vec<HashMap<String, Option<String>>>>>,
@@ -57,7 +56,7 @@ impl MtCommander {
}
pub async fn run_command_on_host(
host: &ConfigHost,
command: &str,
command: &MtCommand
) -> anyhow::Result<Vec<HashMap<String, Option<String>>>> {
let mtc = {
MTC.lock()
@@ -124,7 +123,7 @@ impl MtCommanderInternal {
async fn run_command(
&self,
host: &ConfigHost,
cmd: &str,
command: &MtCommand
) -> anyhow::Result<Vec<HashMap<String, Option<String>>>> {
let addr = format!("{}:{}", &host.ip, host.port(&self.cfg()));
let dev_res = MikrotikDevice::builder(&addr)
@@ -143,8 +142,36 @@ impl MtCommanderInternal {
}
};
let mut cmd = CommandBuilder::new().command(&command.cmd);
for filter in &command.filter {
cmd = match filter.op {
FilterOp::Eq => cmd.query_equal(&filter.key, &filter.value),
FilterOp::Neq => cmd
.query_equal(&filter.key, &filter.value)
.query_operations([QueryOperator::Not].into_iter()),
FilterOp::Le => cmd
.query_lt(&filter.key, &filter.value)
.query_equal(&filter.key, &filter.value)
.query_operations([QueryOperator::Or].into_iter()),
FilterOp::Ge => cmd
.query_gt(&filter.key, &filter.value)
.query_equal(&filter.key, &filter.value)
.query_operations([QueryOperator::Or].into_iter()),
FilterOp::Lt => cmd.query_lt(&filter.key, &filter.value),
FilterOp::Gt => cmd.query_gt(&filter.key, &filter.value),
}
}
for (attr_k, attr_v) in &command.attr {
cmd=cmd.attribute(attr_k, attr_v.as_deref())
}
let cmd = cmd.build();
log::debug!("Query with filters: {:?}", cmd);
let mut rx = dev
.send_command(CommandBuilder::new().command(cmd).build())
.send_command(cmd)
.await?;
let mut res = Vec::new();