From b34f0fbd5f1980e94511de9b709fa18e3b8288fb Mon Sep 17 00:00:00 2001
From: JesusPerez <jpl@jesusperez.pro>
Date: Sat, 16 Oct 2021 00:28:34 +0100
Subject: [PATCH] chore: add policy and rol + checkinfo out formats

---
 src/defs.rs            |  14 ++-
 src/handlers/h_home.rs | 233 +++++++++++++++++++++++------------------
 2 files changed, 142 insertions(+), 105 deletions(-)

diff --git a/src/defs.rs b/src/defs.rs
index 00ed410..175f758 100644
--- a/src/defs.rs
+++ b/src/defs.rs
@@ -1,4 +1,5 @@
-use std::collections::{BTreeMap};
+use serde::{Serialize, Deserialize};
+use std::collections::{HashMap, BTreeMap};
 use app_env::{appenv::AppEnv, AppStore};
 use app_auth::{AuthStore};
 use kloud::{defs::KloudStore, datacontext::DataContext};
@@ -11,6 +12,8 @@ use connectors::defs::{AppDataConn};
 use clds::clouds::defs::{
 	CloudEnv,
 	Cloud,
+  SrvcsHostInfOut,
+	InfoStatus,
 };
 use kloud::kloud::Kloud;
 
@@ -73,4 +76,13 @@ pub async fn load_key() -> String {
   }
   key
 }
+pub type MapCheckInfo =	BTreeMap<String,Vec<SrvcsHostInfOut>>;
+
+#[derive(Clone, Debug, Serialize,  Deserialize, Default)]
+pub struct KldCheck {
+	pub name: String,
+	pub cloud: HashMap<String, MapCheckInfo>,
+	pub apps: HashMap<String, MapCheckInfo>,
+	pub infos: Vec<InfoStatus>,
+}
 
diff --git a/src/handlers/h_home.rs b/src/handlers/h_home.rs
index 5be00a4..2336a54 100644
--- a/src/handlers/h_home.rs
+++ b/src/handlers/h_home.rs
@@ -13,109 +13,152 @@ use app_auth::{UserCtx};
 // 		KloudQueryConfigFilters,
 // 	},
 // };
-use clds::defs::{KloudCheckHome};
-use clds::clouds::defs::{Cloud,SrvcsHostInfo,App,AppsrvcInfo,TskSrvc,TsksrvcInfo};
-use crate::defs::{DataDBs}; // ,CollsData};
+use clds::defs::{KloudCheckHome,CloudCheckItem};
+use clds::status::{get_statusinfo_fileslist,load_statusinfo};
+use clds::clouds::defs::{Cloud,SrvcsHostInfOut,AppOut,AppsrvcInfo,AppsrvcInfOut, TskSrvcOut, TsksrvcInfo, TsksrvcInfOut};
+use crate::defs::{KldCheck, MapCheckInfo, DataDBs}; // ,CollsData};
 use clds::clouds::on_clouds::{get_cloud_check,get_apps_check};
+use app_env::appenv::{Rol,Policy};
 
-pub async fn get_tsks_apps_check(reqenv: &ReqEnv, cld_indx: usize, _auth: UserCtx, role: &str) -> String {
+pub fn tsks_info_on_role(role: String, tsksrvcs: Vec<TsksrvcInfo>) -> Vec<TsksrvcInfOut> {
+	tsksrvcs.into_iter().map(|tsk| {
+		let srvc = match role.as_str() {
+			"admin" => 
+				TskSrvcOut {
+					name: tsk.srvc.name.to_owned(),
+					path: tsk.srvc.path.to_owned(),
+					req: tsk.srvc.req.to_owned(),
+					target: tsk.srvc.target.to_owned(),
+					liveness: tsk.srvc.liveness.to_owned(),
+					critical: tsk.srvc.critical.to_owned(),
+				},
+			_ => 
+				TskSrvcOut {
+					name: tsk.srvc.name.to_owned(),
+					path: String::from(""),
+					req: String::from(""),
+					target: tsk.srvc.target.to_owned(),
+					liveness: String::from(""),
+					critical: tsk.srvc.critical.to_owned(),
+				},
+		};
+		TsksrvcInfOut {
+			name: tsk.name.to_owned(),
+			info: tsk.info.to_owned(),
+			srvc
+		}
+	}).collect()
+}
+pub fn app_info_on_role(role: String, appsrvcs: Vec<AppsrvcInfo>) -> Vec<AppsrvcInfOut> {
+	appsrvcs.into_iter().map(|app| {
+		let srvc = match role.as_str() {
+      "admin" => 
+				AppOut {
+					name: app.srvc.name.to_owned(),
+					path: app.srvc.path.to_owned(),
+					req: app.srvc.req.to_owned(),
+					target: app.srvc.target.to_owned(),
+					liveness: app.srvc.liveness.to_owned(),
+					critical: app.srvc.critical.to_owned(),
+				},
+			_ => 
+				AppOut {
+					name: app.srvc.name.to_owned(),
+					path: String::from(""),
+					req: String::from(""),
+					target: app.srvc.target.to_owned(),
+					liveness: String::from(""),
+					critical: app.srvc.critical.to_owned(),
+				},
+		};
+		AppsrvcInfOut {
+			name: app.name.to_owned(),
+			info: app.info.to_owned(),
+			srvc
+		}
+	}).collect()
+}
+pub fn collect_clouds_check_items(role: &str, items: &Vec<CloudCheckItem> ) -> BTreeMap<String,Vec<SrvcsHostInfOut>> {
+	let mut m_items = BTreeMap::new();
+	items.iter().for_each(|itm| {
+		let liveness: Vec<SrvcsHostInfOut>;
+		liveness = itm.liveness.to_owned().into_iter().map(|it| { 
+			SrvcsHostInfOut {
+				hostname: format!("{}",&it.hostname),
+				tsksrvcs:  tsks_info_on_role(role.to_owned(), it.tsksrvcs),
+				appsrvcs: app_info_on_role(role.to_owned(), it.appsrvcs),
+			}
+		}).collect();
+		m_items.insert(format!("{}",&itm.name),liveness);
+	});
+	m_items
+}
+pub async fn get_tsks_apps_check(reqenv: &ReqEnv,_auth: UserCtx, role: &str) -> String {
 	let result_apps = get_apps_check(&reqenv).await;
 	// println!("Result apps: {}",&result_apps);
   let res_apps: Vec<KloudCheckHome> = serde_json::from_str(&result_apps).unwrap_or_else(|e| {
 		println!("Error serde apps json: {}",e);
 	 	Vec::new()
 	});
-	// let mut list_groups = String::from("");
-  let mut grp_apps_hash: HashMap<String, BTreeMap<String,Vec<SrvcsHostInfo>>> = HashMap::new();
-	if let Some(kld) = res_apps.get(cld_indx) {
-		for grp in &kld.groups {
-			// if !list_groups.is_empty() {
-      //   list_groups.push(',');
-      // }
-      // list_groups.push_str(&grp.name);
-			let mut m_items = BTreeMap::new();
-      for itm in &grp.items {
-				let liveness: Vec<SrvcsHostInfo>;
-				if role.is_empty() {
-					liveness = itm.liveness.to_owned().into_iter().map(|it| { 
-					  SrvcsHostInfo {
-							hostname: format!("{}",&it.hostname),
-							tsksrvcs: it.tsksrvcs.to_owned(),
-							appsrvcs: it.appsrvcs.into_iter().map(|ap| {
-								AppsrvcInfo {
-									name: ap.name.to_owned(),
-									info: ap.info.to_owned(),
-									srvc: App {
-									  name: ap.srvc.name.to_owned(),
-										path: String::from(""),
-										req: String::from(""),
-										target: ap.srvc.target.to_owned(),
-										liveness: String::from(""),
-										critical: ap.srvc.critical.to_owned(),
-									}
-								}
-							}).collect()
-						}
-					}).collect();
-				} else {
-					liveness = itm.liveness.to_owned();
-				}
-        m_items.insert(format!("{}",&itm.name),liveness);
-			}
-      grp_apps_hash.insert(format!("{}",grp.name),m_items);
-		}
-  }
 	let result_cloud = get_cloud_check(&reqenv).await;
 	// println!("Result cloud: {}",&result_cloud);
   let res_cloud: Vec<KloudCheckHome> = serde_json::from_str(&result_cloud).unwrap_or_else(|e| {
 		println!("Error serde apps json: {}",e);
 	 	Vec::new()
 	});
-	let mut grp_cloud_hash: HashMap<String, BTreeMap<String,Vec<SrvcsHostInfo>>> = HashMap::new();
-	if let Some(kld) = res_cloud.get(cld_indx) {
-		for grp in &kld.groups {
-			let mut m_items = BTreeMap::new();
-      for itm in &grp.items {
-				let liveness: Vec<SrvcsHostInfo>;
-				if role.is_empty() {
-					liveness = itm.liveness.to_owned().into_iter().map(|it| { 
-					  SrvcsHostInfo {
-							hostname: format!("{}",&it.hostname),
-							appsrvcs: it.appsrvcs.to_owned(),
-							tsksrvcs: it.tsksrvcs.into_iter().map(|tsk| {
-								TsksrvcInfo {
-									name: tsk.name.to_owned(),
-									info: tsk.info.to_owned(),
-									srvc: TskSrvc {
-									  name: tsk.srvc.name.to_owned(),
-										path: String::from(""),
-										req: String::from(""),
-										target: tsk.srvc.target.to_owned(),
-										liveness: String::from(""),
-										critical: tsk.srvc.critical.to_owned(),
-									}
-								}
-							}).collect()
-						}
-					}).collect();
-				} else {
-					liveness = itm.liveness.to_owned();
+	let mut kld_check: Vec<KldCheck> = Vec::new();
+	res_apps.iter().for_each(|kld| {
+	  // let mut list_groups = String::from("");
+    let mut grp_check_hash: HashMap<String, MapCheckInfo> = HashMap::new();
+	  kld.groups.iter().for_each(|grp| {
+			// if !list_groups.is_empty() {
+      //   list_groups.push(',');
+      // }
+      // list_groups.push_str(&grp.name);
+      grp_check_hash.insert(format!("{}",grp.name),collect_clouds_check_items(&role,&grp.items));
+		});
+		kld_check.push(KldCheck {
+			name: kld.name.to_owned(),
+			cloud: HashMap::new(),
+			apps: grp_check_hash,
+			infos: Vec::new(),
+		});
+  });
+	for kld in res_cloud {
+    let mut grp_check_hash: HashMap<String, MapCheckInfo> = HashMap::new();
+		kld.groups.iter().for_each(|grp| {
+      grp_check_hash.insert(format!("{}",grp.name),collect_clouds_check_items(&role,&grp.items));
+		});
+		let kld_statusinfo_files: Vec<String> = get_statusinfo_fileslist(&reqenv.config().state_path,&kld.name).await.unwrap_or_else(|e|{
+			println!("Error on infos {}: {}",&kld.name,e);
+			Vec::new()
+		});
+		// dbg!(&kld_statusinfo_files);
+	  let infos = load_statusinfo(&format!("{}/{}",&reqenv.config().state_path,&kld.name), kld_statusinfo_files).await;
+		//dbg!(&infos);
+		if kld_check.len() == 0 {
+			kld_check.push(KldCheck {
+				name: kld.name.to_owned(),
+				apps: HashMap::new(),
+				cloud: grp_check_hash,
+				infos, 
+			});
+		} else {
+			let mut kldix = 0;
+			kld_check.iter().enumerate().for_each(|(idx,k)| {
+				if k.name == kld.name {
+			     kldix = idx;
 				}
-        m_items.insert(format!("{}",&itm.name),liveness.to_owned());
-			}
-      grp_cloud_hash.insert(format!("{}",grp.name),m_items);
+			});
+			kld_check[kldix].cloud = grp_check_hash.to_owned();
+			kld_check[kldix].infos = infos.to_owned();
 		}
-  }
- 	// ctx.insert("groups_cloud".to_string(),&grp_cloud_hash);
-	let res_apps_json=serde_json::to_string(&grp_apps_hash).unwrap_or_else(|e|{
+  };
+	// let result = format!("{}:{}{}:{}{}",r#"{"group_apps""#,&res_apps_json,r#","group_cloud""#,&res_cloud_json,r#"}"#);
+	let result=serde_json::to_string(&kld_check).unwrap_or_else(|e|{
 		println!("Error serde from value: {}",e);
 		String::from("")
 	});
-	let res_cloud_json=serde_json::to_string(&grp_cloud_hash).unwrap_or_else(|e|{
-		println!("Error serde from value: {}",e);
-		String::from("")
-	});
-	let result = format!("{}:{}{}:{}{}",r#"{"group_apps""#,&res_apps_json,r#","group_cloud""#,&res_cloud_json,r#"}"#);
   result.to_owned()
 }
 pub async fn home(
@@ -145,7 +188,7 @@ pub async fn home(
 			//  dbg!("LANG: {} - {}",language, lang);
       let role = reqenv.req.user_role().await;
 			// reqenv.is_admin()
-			let result = get_tsks_apps_check(&reqenv,1,auth,&role).await;
+			let result = get_tsks_apps_check(&reqenv,auth,&role).await;
 			// let mut path = format!("{}/profiles/{}/{}/defs.yaml",reqenv.websrvr().resources_path,&prfx,&auth.user_id);
 			// if ! std::path::Path::new(&path).exists() {
 			// 	path = format!("{}/profiles/{}/defs.yaml",reqenv.websrvr().resources_path,&prfx);
@@ -164,32 +207,14 @@ pub async fn home(
 			Ok(warp::http::Response::builder()
 			.body(result.to_string())
 			.into_response())
-			/*
-			Ok(warp::reply::with_header(
-					warp::http::Response::new(result),
-						"Access-Control-Allow-Origin",
-						&allow_origin))
-			*/
-			//  warp::reply::json(&res),
-			// Ok(warp::reply::with_header(
-			//  warp::http::Response::new(result),
-			//    "Access-Control-Allow-Origin",
-			//    &allow_origin))
-			// Ok(warp::reply::json(&result))
 		},
 		Err(_e) => {
 			// let result = format!("Error: no credentials found");
 			// println!("{}",e);
-			let result = get_tsks_apps_check(&reqenv,1,UserCtx::default(),"").await;
+			let result = get_tsks_apps_check(&reqenv,UserCtx::default(),"").await;
 			Ok(warp::http::Response::builder()
 			.body(result.to_string())
 			.into_response())
-			/*
-			Ok(warp::reply::with_header(
-			warp::http::Response::new(result),
-			"Access-Control-Allow-Origin",
-			&allow_origin))
-			*/
 		}
 	}
 }