chore: syntax crate::defs and remove monitor_rules.rs

This commit is contained in:
Jesús Pérez Lorenzo 2021-09-16 22:28:24 +01:00
parent 159a3f3caa
commit 5bd6c74568
3 changed files with 21 additions and 287 deletions

View File

@ -1,4 +1,3 @@
pub mod defs;
pub mod on_clouds;
pub mod upcloud;
pub mod monitor_rules;
pub mod upcloud;

View File

@ -1,283 +0,0 @@
use std::collections::HashMap;
use serde::{Serialize,Deserialize,Deserializer};
use std::fmt;
use anyhow::{Result};
use kloud::utils::load_fs_content;
use crate::monitor::write_str_data;
#[derive(Eq, PartialEq, Clone, Serialize, Debug, Deserialize)]
pub enum RuleContext {
None,
Server(String),
Service(String),
Ip(String),
}
impl Default for RuleContext {
fn default() -> Self {
RuleContext::None
}
}
impl fmt::Display for RuleContext {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RuleContext::Server(c) => write!(f,"server: {}",c),
RuleContext::None => write!(f,"none"),
RuleContext::Service(c) => write!(f,"service: {}",c),
RuleContext::Ip(c) => write!(f,"ip: {}",c),
}
//write!(f, "{:?}", self)
}
}
impl RuleContext {
pub fn get_value(&self) -> String {
match self {
RuleContext::Server(c) => format!("{}",c),
RuleContext::None => format!(""),
RuleContext::Service(c) => format!("{}",c),
RuleContext::Ip(c) => format!("{}",c),
}
}
}
#[derive(Eq, PartialEq, Clone, Serialize, Debug, Deserialize)]
pub enum MonitorAction {
None,
Start(String,String,String),
Stop(String,String,String),
Restart(String,String,String),
Notify(String,String,String),
}
impl Default for MonitorAction {
fn default() -> Self {
MonitorAction::None
}
}
impl fmt::Display for MonitorAction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MonitorAction::None => write!(f,"none"),
MonitorAction::Start(v,p,a) => write!(f,"start: {} {} {}",v,p,a),
MonitorAction::Stop(v,p,a) => write!(f,"stop: {} {} {}",v,p,a),
MonitorAction::Restart(v,p,a) => write!(f,"restart: {} {} {}",v,p,a),
MonitorAction::Notify(v,p,a) => write!(f,"notify: {} {} {}",v,p,a),
}
//write!(f, "{:?}", self)
}
}
impl MonitorAction {
pub fn get_value(&self) -> String {
match self {
MonitorAction::None => format!(""),
MonitorAction::Start(v,p,a) => format!("{} {} {}",v,p,a),
MonitorAction::Stop(v,p,a) => format!("{} {} {}",v,p,a),
MonitorAction::Restart(v,p,a) => format!("{} {} {}",v,p,a),
MonitorAction::Notify(v,p,a) => format!("{} {} {}",v,p,a),
}
}
}
#[derive(Eq, PartialEq, Copy, Clone, Debug, Serialize, Deserialize)]
pub enum RuleSchedule {
None,
Check,
OnDemand,
}
impl Default for RuleSchedule {
fn default() -> Self {
RuleSchedule::None
}
}
impl fmt::Display for RuleSchedule {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RuleSchedule::None => write!(f,"none"),
RuleSchedule::Check=> write!(f,"chechk"),
RuleSchedule::OnDemand=> write!(f,"ondemand"),
}
}
}
#[derive(Eq, PartialEq, Copy, Clone, Debug, Serialize, Deserialize)]
pub enum RuleOperator {
None,
Equal,
NotEqual,
Contains,
NotContains,
}
impl Default for RuleOperator {
fn default() -> Self {
RuleOperator::None
}
}
impl fmt::Display for RuleOperator {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RuleOperator::None => write!(f,"none"),
RuleOperator::Equal => write!(f,"equal"),
RuleOperator::NotEqual=> write!(f,"not_equal"),
RuleOperator::Contains => write!(f,"matches"),
RuleOperator::NotContains => write!(f,"not_matches"),
}
}
}
fn deserialize_rulecontext<'de, D>(deserializer: D) -> Result<RuleContext, D::Error>
where D: Deserializer<'de> {
let buf = String::deserialize(deserializer)?;
// let res = String::from_str(&buf).unwrap_or_else(|e|{
// eprintln!("deserialize rulecontext error: {}",e);
// String::from("")
// });
// println!("buf: {}",&buf);
let v: Vec<&str> = buf.split(':').collect();
if v.len() > 1 {
Ok(match v[0] {
"Service" => RuleContext::Service(v[1].to_owned()),
"Server" => RuleContext::Server(v[1].to_owned()),
"Ip" => RuleContext::Ip(v[1].to_owned()),
_ => RuleContext::None
})
} else {
Ok(RuleContext::None)
}
}
fn deserialize_ruleactions<'de, D>(deserializer: D) -> Result<Vec<MonitorAction>, D::Error>
where D: Deserializer<'de> {
let buf = Vec::deserialize(deserializer)?;
let mut actions = Vec::new();
buf.iter().for_each(|it: &String| {
let v: Vec<&str> = it.split(':').collect();
if v.len() > 1 {
let arg: Vec<&str> = v[1].split(',').collect();
if arg.len() > 1 {
actions.push(match v[0] {
"Start" => MonitorAction::Start(arg[0].to_owned(),arg[1].to_owned(),arg[2].to_owned()),
"Stop" => MonitorAction::Stop(arg[0].to_owned(),arg[1].to_owned(),arg[2].to_owned()),
"Restart" => MonitorAction::Restart(arg[0].to_owned(),arg[1].to_owned(),arg[2].to_owned()),
"Notify" => MonitorAction::Notify(arg[0].to_owned(),arg[1].to_owned(),arg[2].to_owned()),
_ => MonitorAction::None
})
}
}
});
Ok(actions)
}
#[allow(clippy::missing_docs_in_private_items)]
#[allow(non_snake_case)]
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct MonitorRule {
pub id: String,
pub name: String,
pub description: String,
#[serde(deserialize_with = "deserialize_rulecontext")]
pub context: RuleContext,
pub command: String,
pub selector: HashMap<String,String>,
pub operator: RuleOperator,
pub value: String,
pub result: bool,
pub use_state: bool,
pub wait_checks: isize,
pub schedule: RuleSchedule,
#[serde(deserialize_with = "deserialize_ruleactions")]
pub actions: Vec<MonitorAction>,
}
#[allow(clippy::missing_docs_in_private_items)]
#[allow(non_snake_case)]
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct MonitorRules {
pub name: String,
pub description: String,
pub rules: Vec<MonitorRule>,
}
impl MonitorRules {
pub fn new(name: String, description: String, rules: Vec<MonitorRule> ) -> Self {
Self {
name,
description,
rules,
}
}
pub fn load(root: &str, path: &str, format: &str) -> Self {
let data_rules = load_fs_content(&root, &path, &format);
let err_load = |e|{
eprintln!("Error loading MonitorRules {}/{}.{}: {}",&root,&path,&format,e);
MonitorRules::default()
};
let res: MonitorRules;
if data_rules.is_empty() {
res = MonitorRules::default();
} else {
// println!("Parse Montior Rules as: {}",&format);
res = match format {
"json" => serde_json::from_str(&data_rules).unwrap_or_else(|e| err_load(format!("{}",e))),
"yaml" => serde_yaml::from_str(&data_rules).unwrap_or_else(|e| err_load(format!("{}",e))),
"toml" => toml::from_str(&data_rules).unwrap_or_else(|e| err_load(format!("{}",e))),
_ => MonitorRules::default(),
};
}
res
}
pub fn dump(&self, root: &str, path: &str, format: &str) -> Result<()> {
let err_load = |e| {
eprintln!("Error dump MonitorRules {}/{}.{}: {}",&root,&path,&format,e);
String::from("")
};
let data_str = match format {
"json" => serde_json::to_string(&self).unwrap_or_else(|e| err_load(format!("{}",e))),
"yaml" => serde_yaml::to_string(&self).unwrap_or_else(|e| err_load(format!("{}",e))),
"toml" => toml::to_string(&self).unwrap_or_else(|e| err_load(format!("{}",e))),
_ => String::from(""),
};
if ! data_str.is_empty() {
println!("Dump loading MonitorRules to {}/{}.{}",&root,&path,&format);
let output_path = format!("{}/{}.{}",&root,&path,&format);
write_str_data(output_path, data_str, "Monitor rules dump".to_string())?;
}
Ok(())
}
}
#[allow(clippy::missing_docs_in_private_items)]
#[allow(non_snake_case)]
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct MonitorStates {
pub when: String,
pub id: String,
pub data: String, // to save JSON info
}
impl MonitorStates {
pub fn load(root: &str, path: &str, format: &str) -> Self {
println!("Load Montior States ...");
let data_rules = load_fs_content(&root, &path, &format);
let res: MonitorStates = serde_json::from_str(&data_rules).unwrap_or_else(|e|{
eprintln!("Error loading MonitorStates {}/{}.{}: {}",&root,&path,&format,e);
MonitorStates::default()
});
res
}
pub fn dump(&self, root: &str, path: &str, format: &str) -> Result<()> {
println!("Dump Montior States ...");
let data_str = serde_json::to_string(&self).unwrap_or_else(|e| {
eprintln!("Error dump MonitorRules {}/{}.{}: {}",&root,&path,&format,e);
String::from("")
});
if ! data_str.is_empty() {
println!("Dump MonitorStates to {}/{}.{}",&root,&path,&format);
let output_path = format!("{}/{}.{}",&root,&path,&format);
write_str_data(output_path, data_str, "Monitor states dump".to_string())?;
}
Ok(())
}
}

View File

@ -17,7 +17,17 @@ use crate::clouds::defs::{
TskSrvc,
MainResourcesConfig,
};
use crate::defs::{KloudHome,KloudCheckHome,SSHAccess,Cntrllr,CloudGroup,CloudCheckGroup,CloudItem,CloudCheckItem};
use crate::defs::{
IsCritical,
KloudHome,
KloudCheckHome,
SSHAccess,
Cntrllr,
CloudGroup,
CloudCheckGroup,
CloudItem,
CloudCheckItem
};
use crate::clouds::defs::{TsksrvcInfo};
use crate::clouds::upcloud::{get_upcloud_info,run_on_upcloud};
@ -312,6 +322,7 @@ pub async fn parse_srvr_tsksrvcs(hostname: &str, sshaccess: &SSHAccess, tsksrvcs
}
pub async fn liveness_srvr_tsksrvcs(source: &str, cntrllrs: &Vec<Cntrllr>, tsksrvcs: &Vec<TskSrvc>, req_tsksrvc: &str) -> Vec<TsksrvcInfo> {
let mut tsksrvcs_info: Vec<TsksrvcInfo> = Vec::new();
let debug=envmnt::get_isize("DEBUG",0);
for tsksrvc in tsksrvcs.iter() {
match format!("{}",&tsksrvc.name).as_str() {
"pause" => continue,
@ -323,10 +334,17 @@ pub async fn liveness_srvr_tsksrvcs(source: &str, cntrllrs: &Vec<Cntrllr>, tsksr
continue;
}
let serverstring = format!("{}",&tsksrvc.liveness);
if debug > 2 {
println!("livenes: {} -> {}",&tsksrvc.name,&serverstring);
}
let res_info = match liveness_check(&source,&cntrllrs,&serverstring,&name).await {
Ok(_) => "ok",
Err(e) => {
eprint!("{}",e);
if tsksrvc.critical == IsCritical::yes {
let monitor_name = "WUJI_MONITOR";
println!("{} : critical livenes: {} -> {}",envmnt::get_or(&monitor_name,""),&tsksrvc.name,&serverstring);
}
eprint!("liveness_check error: {}",e);
"err"
},
};