/* * Copyright (c) 2026 MCorange. * All rights reserved. * * Unauthorized copying, modification, distribution, or use of this * software, in whole or in part, is prohibited without prior written * permission. */ use core::panic; use std::{ collections::HashMap, sync::{Arc, Mutex}, }; use anyhow::bail; use futures::future::join_all; use mikrotik_rs::{CommandBuilder, Event, MikrotikDevice, QueryOperator}; use crate::config::{Config, ConfigHost, cli::{FilterOp, MtCommand}}; lazy_static::lazy_static! { static ref MTC: Arc> = MtCommanderInternal::new_mutex(); } pub struct MtCommander; #[derive(Debug, Clone)] struct MtCommanderInternal { cfg: Option, } impl MtCommander { pub fn init(cfg: Config) -> anyhow::Result<()> { let mut mtc = MTC.lock().map_err(|e| anyhow::anyhow!(e.to_string()))?; mtc.cfg = Some(cfg); Ok(()) } pub fn run_command_on_hosts( hosts: &[ConfigHost], command: &MtCommand ) -> impl Future< Output = anyhow::Result< HashMap>>>>, >, > { async move { let results = join_all(hosts.iter().map(|host| async move { let res = Self::run_command_on_host(host, command).await; (host.clone(), res) })) .await; 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) } } pub async fn run_command_on_host( host: &ConfigHost, command: &MtCommand ) -> anyhow::Result>>> { let mtc = { MTC.lock() .map_err(|e| anyhow::anyhow!(e.to_string()))? .clone() }; mtc.run_command(host, &command).await } /*pub async fn run_command_on_hosts_and_parse_re( hosts: &[ConfigHost], command: &str, parse_re: &Regex, ) -> anyhow::Result>> { let mut res_map = HashMap::new(); for host in hosts { let res = Self::run_command_on_host_and_parse_re(host, command, parse_re).await?; res_map.insert(host.clone(), res); } Ok(res_map) }*/ /*pub async fn run_command_on_host_and_parse_re( host: &ConfigHost, command: &str, parse_re: &Regex, ) -> anyhow::Result> { let mtc = MTC.lock().map_err(|e| anyhow::anyhow!(e.to_string()))?; let res = mtc.run_command(host, &command).await?; let out = parse_re .find_iter(&res) .map(|s| s.as_str().to_string()) .collect(); Ok(out) }*/ } #[allow(dead_code)] impl MtCommanderInternal { fn new(cfg: Config) -> Self { Self { cfg: Some(cfg) } } fn new_mutex() -> Arc> { Arc::new(Mutex::new(Self { cfg: None })) } fn init(&mut self, cfg: Config) -> anyhow::Result<()> { self.cfg = Some(cfg); self.spawn_watcher_thread()?; Ok(()) } fn cfg(&self) -> &Config { if let Some(cfg) = &self.cfg { cfg } else { panic!(); } } fn spawn_watcher_thread(&mut self) -> anyhow::Result<()> { async fn watcher() {} tokio::spawn(watcher()); Ok(()) } async fn run_command( &self, host: &ConfigHost, command: &MtCommand ) -> anyhow::Result>>> { let addr = format!("{}:{}", &host.ip, host.port(&self.cfg())); let dev_res = MikrotikDevice::builder(&addr) .credentials(&host.username(self.cfg()), Some(&host.password(self.cfg()))) .connect() .await; let dev = match dev_res { Ok(dev) => { log::debug!("({addr}) Connected successfully!"); dev } Err(e) => { log::error!("Failed to connect to {addr}: {e}"); bail!(e); } }; 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]), FilterOp::Le => cmd .query_lt(&filter.key, &filter.value) .query_equal(&filter.key, &filter.value) .query_operations(&[QueryOperator::Or]), FilterOp::Ge => cmd .query_gt(&filter.key, &filter.value) .query_equal(&filter.key, &filter.value) .query_operations(&[QueryOperator::Or]), 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(cmd) .await?; let mut res = Vec::new(); let mut size = 0; while let Some(event) = rx.recv().await { match event { Event::Reply { response, tag: _ } => { log::debug!("({}) {:?}", &host.ip, response.attributes); size += response .attributes .values() .flatten() .map(|v| v.len()) .sum::(); res.push(response.attributes); } Event::Done { .. } => { break; } Event::Trap { response, .. } => { log::error!("({}) {:?}", &host.ip, response.message); } other => println!("{other:?}"), } } log::info!("({addr}) Command `{command}` finished, read {size} bytes"); Ok(res) } }