Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
RWDai committed Oct 25, 2023
1 parent eff1a31 commit a78bbbe
Show file tree
Hide file tree
Showing 9 changed files with 434 additions and 258 deletions.
2 changes: 1 addition & 1 deletion admin/src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ lazy_static! {
pub static ref TYPE_CONFIG_NAME_MAP: HashMap<&'static str, &'static str> = {
let mut map = HashMap::new();
map.insert(GATEWAY_TYPE, GATEWAY_CONFIG_NAME);
map.insert(TLS_CONFIG_TYPE,TLS_CONFIG_NAME)
map.insert(TLS_CONFIG_TYPE, TLS_CONFIG_NAME);
map.insert(PLUGIN_TYPE, PLUGIN_CONFIG_NAME);
map.insert(ROUTE_TYPE, ROUTE_CONFIG_NAME);
map.insert(BACKEND_REF_TYPE, BACKEND_REF_CONFIG_NAME);
Expand Down
2 changes: 1 addition & 1 deletion admin/src/model/vo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ pub trait Vo {
/// Get vo unique name
/// unique name is used to distinguish different instances of the same type
fn get_unique_name(&self) -> String;
}
}
14 changes: 12 additions & 2 deletions admin/src/model/vo/gateway_vo.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::model::vo::Vo;
use crate::{constants, model::vo::Vo};
use kernel_common::inner_model::gateway::{SgParameters, SgProtocol, SgTlsMode};
use serde::{Deserialize, Serialize};
use tardis::web::poem_openapi;
Expand All @@ -23,6 +23,16 @@ pub struct SgGatewayVO {
pub filters: Option<Vec<String>>,
}

impl Vo for SgGatewayVO {
fn get_vo_type() -> String {
constants::GATEWAY_TYPE.to_string()
}

fn get_unique_name(&self) -> String {
self.name.clone()
}
}

/// Listener embodies the concept of a logical endpoint where a Gateway accepts network connections.
#[derive(Default, Debug, Serialize, Deserialize, Clone, poem_openapi::Object)]
pub struct SgListenerVO {
Expand Down Expand Up @@ -54,7 +64,7 @@ pub struct SgTlsConfigVO {

impl Vo for SgTlsConfigVO {
fn get_vo_type() -> String {
todo!()
constants::TLS_CONFIG_TYPE.to_string()
}

fn get_unique_name(&self) -> String {
Expand Down
10 changes: 6 additions & 4 deletions admin/src/service/backend_ref_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@ use tardis::web::poem::delete;

pub struct BackendRefService;

impl BaseService<'_, BackendRefVO> for BackendRefService {}

impl BackendRefService {
pub(crate) async fn list(id: Option<String>, query: BackendRefQueryDto) -> TardisResult<Vec<BackendRefVO>> {
//todo query
BaseService::get_type_map::<BackendRefVO>()
Self::get_type_map()
.await?
.values()
.into_iter()
Expand All @@ -20,16 +22,16 @@ impl BackendRefService {
}

pub(crate) async fn add(add: BackendRefVO) -> TardisResult<()> {
BaseService::add::<BackendRefVO>(add).await?;
Self::add_vo(add).await?;
Ok(())
}
pub(crate) async fn update(update: BackendRefVO) -> TardisResult<()> {
BaseService::update::<BackendRefVO>(update).await?;
Self::update_vo(update).await?;
Ok(())
}

pub(crate) async fn delete(id: &str) -> TardisResult<()> {
BaseService::delete::<BackendRefVO>(&id).await?;
Self::delete_vo(&id).await?;
Ok(())
}
}
188 changes: 145 additions & 43 deletions admin/src/service/base_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,17 @@ use kube::api::PostParams;
use kube::Api;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tardis::async_trait::async_trait;
use tardis::basic::error::TardisError;
use tardis::basic::result::TardisResult;
use tardis::log;

pub struct BaseService;

impl BaseService {
#[cfg(feature = "k8s")]
pub async fn get_type_map<'a, T>() -> TardisResult<HashMap<String, String>>
where
T: Vo + Deserialize<'a>,
{
#[async_trait]
pub trait BaseService<'a, T>
where
T: Vo + Serialize + Deserialize<'a> + Sync + Send,
{
async fn get_type_map() -> TardisResult<HashMap<String, String>> {
if let Some(t_config) =
get_config_map_api().await?.get_opt(&get_config_name::<T>()).await.map_err(|e| TardisError::io_error(&format!("[SG.admin] Kubernetes client error: {e}"), ""))?
{
Expand All @@ -33,38 +32,27 @@ impl BaseService {
}
}


#[cfg(feature = "k8s")]
pub async fn get_by_id<'a, T>(id: &str) -> TardisResult<Option<(String.,T)>>
where
T: Vo + Serialize + Deserialize<'a>,
{
Self::get_type_map::<T>().await?.get(id)
async fn get_by_id(id: &str) -> TardisResult<String> {
if let Some(t_str) = Self::get_type_map().await?.remove(id) {
Ok(t_str)
} else {
Err(TardisError::not_found("", ""))
}
}

#[cfg(feature = "k8s")]
pub async fn add<'a, T>(config: T) -> TardisResult<T>
where
T: Vo + Serialize + Deserialize<'a>,
{
Self::add_or_update::<T>(config, true).await
async fn add_vo(config: T) -> TardisResult<T> {
Self::add_or_update_vo(config, true).await
}

#[cfg(feature = "k8s")]
pub async fn update<'a, T>(config: T) -> TardisResult<T>
where
T: Vo + Serialize + Deserialize<'a>,
{
Self::add_or_update::<T>(config, false).await
async fn update_vo(config: T) -> TardisResult<T> {
Self::add_or_update_vo(config, false).await
}

#[cfg(feature = "k8s")]
pub async fn add_or_update<'a, T>(config: T, add_only: bool) -> TardisResult<T>
where
T: Vo + Serialize + Deserialize<'a>,
{
async fn add_or_update_vo(config: T, add_only: bool) -> TardisResult<T> {
let id = config.get_unique_name();
let mut datas = Self::get_type_map::<T>().await?;
let mut datas = Self::get_type_map().await?;
if let Some(_) = datas.get(&id) {
if add_only {
return Err(TardisError::bad_request(&format!("[SG.admin] {}:{} already exists", T::get_vo_type(), id), ""));
Expand Down Expand Up @@ -98,12 +86,8 @@ impl BaseService {
Ok(config)
}

#[cfg(feature = "k8s")]
pub async fn delete<'a, T>(config_id: &str) -> TardisResult<()>
where
T: Vo + Serialize + Deserialize<'a>,
{
let mut datas = Self::get_type_map::<T>().await?;
async fn delete_vo(config_id: &str) -> TardisResult<()> {
let mut datas = Self::get_type_map().await?;
if let Some(_) = datas.remove(config_id) {
get_config_map_api()
.await?
Expand All @@ -128,6 +112,123 @@ impl BaseService {
}
}

// impl BaseService {
// #[cfg(feature = "k8s")]
// pub async fn get_type_map<'a, T>() -> TardisResult<HashMap<String, String>>
// where
// T: Vo + Deserialize<'a>,
// {
// if let Some(t_config) =
// get_config_map_api().await?.get_opt(&get_config_name::<T>()).await.map_err(|e| TardisError::io_error(&format!("[SG.admin] Kubernetes client error: {e}"), ""))?
// {
// if let Some(b_map) = t_config.data {
// Ok(b_map.into_iter().collect())
// } else {
// Ok(HashMap::new())
// }
// } else {
// init_config_map_by_t::<T>().await?;
// Ok(HashMap::new())
// }
// }

// pub async fn get_by_id<T>(id: &str) -> TardisResult<String>
// where
// T: Vo + Deserialize<'a>,
// {
// if let Some(t_str) = BaseService::get_type_map::<T>().await?.remove(id) {
// Ok(t_str)
// } else {
// Err(TardisError::not_found("", ""))
// }
// }

// #[cfg(feature = "k8s")]
// pub async fn add<'a, T>(config: T) -> TardisResult<T>
// where
// T: Vo + Serialize + Deserialize<'a>,
// {
// Self::add_or_update::<T>(config, true).await
// }

// #[cfg(feature = "k8s")]
// pub async fn update<'a, T>(config: T) -> TardisResult<T>
// where
// T: Vo + Serialize + Deserialize<'a>,
// {
// Self::add_or_update::<T>(config, false).await
// }

// #[cfg(feature = "k8s")]
// pub async fn add_or_update<'a, T>(config: T, add_only: bool) -> TardisResult<T>
// where
// T: Vo + Serialize + Deserialize<'a>,
// {
// let id = config.get_unique_name();
// let mut datas = Self::get_type_map::<T>().await?;
// if let Some(_) = datas.get(&id) {
// if add_only {
// return Err(TardisError::bad_request(&format!("[SG.admin] {}:{} already exists", T::get_vo_type(), id), ""));
// } else {
// log::debug!("[SG.admin] add_or_update {}:{} exists , will update", T::get_vo_type(), id);
// }
// } else {
// log::debug!("[SG.admin] add_or_update {}:{} not exists , will add", T::get_vo_type(), id);
// }

// datas.insert(
// id.clone(),
// serde_json::to_string(&config).map_err(|e| TardisError::bad_request(&format!("Serialization to json failed:{e}"), ""))?,
// );
// get_config_map_api()
// .await?
// .replace(
// &get_config_name::<T>(),
// &PostParams::default(),
// &ConfigMap {
// data: Some(datas.into_iter().collect()),
// metadata: ObjectMeta {
// name: Some(get_config_name::<T>()),
// ..Default::default()
// },
// ..Default::default()
// },
// )
// .await
// .map_err(|e| TardisError::io_error(&format!("[SG.admin] Kubernetes client error:{e}"), ""))?;
// Ok(config)
// }

// #[cfg(feature = "k8s")]
// pub async fn delete<'a, T>(config_id: &str) -> TardisResult<()>
// where
// T: Vo + Serialize + Deserialize<'a>,
// {
// let mut datas = Self::get_type_map::<T>().await?;
// if let Some(_) = datas.remove(config_id) {
// get_config_map_api()
// .await?
// .replace(
// &get_config_name::<T>(),
// &PostParams::default(),
// &ConfigMap {
// data: Some(datas.into_iter().collect()),
// metadata: ObjectMeta {
// name: Some(get_config_name::<T>()),
// ..Default::default()
// },
// ..Default::default()
// },
// )
// .await
// .map_err(|e| TardisError::io_error(&format!("[SG.admin] Kubernetes client error:{e}"), ""))?;
// } else {
// log::debug!("{}:{} already not exists", T::get_vo_type(), config_id);
// }
// Ok(())
// }
// }

#[cfg(feature = "k8s")]
pub async fn init_config_map_by_t<T>() -> TardisResult<()>
where
Expand Down Expand Up @@ -168,6 +269,7 @@ pub async fn get_config_map_api() -> TardisResult<Api<ConfigMap>> {
mod test {
use crate::model::vo::backend_vo::BackendRefVO;
use crate::model::vo::Vo;
use crate::service::backend_ref_service::BackendRefService;
use crate::service::base_service::BaseService;
use tardis::tokio;

Expand All @@ -185,18 +287,18 @@ mod test {
weight: None,
filters: None,
};
BaseService::add(add_o_1.clone()).await.unwrap();
assert!(BaseService::add(add_o_1.clone()).await.is_err());
BackendRefService::add_vo(add_o_1.clone()).await.unwrap();
assert!(BackendRefService::add_vo(add_o_1.clone()).await.is_err());

let get_o_1 = serde_json::from_str::<BackendRefVO>(&BaseService::get_type_map::<BackendRefVO>().await.unwrap().get(&add_o_1.get_unique_name()).unwrap()).unwrap();
let get_o_1 = serde_json::from_str::<BackendRefVO>(&BackendRefService::get_type_map().await.unwrap().get(&add_o_1.get_unique_name()).unwrap()).unwrap();
assert_eq!(get_o_1.port, add_o_1.port);

add_o_1.port = 1832;
BaseService::update(add_o_1.clone()).await.unwrap();
BaseService::update_vo(add_o_1.clone()).await.unwrap();

let get_o_1 = serde_json::from_str::<BackendRefVO>(&BaseService::get_type_map::<BackendRefVO>().await.unwrap().get(&add_o_1.get_unique_name()).unwrap()).unwrap();
let get_o_1 = serde_json::from_str::<BackendRefVO>(&BackendRefService::get_type_map().await.unwrap().get(&add_o_1.get_unique_name()).unwrap()).unwrap();
assert_eq!(get_o_1.port, add_o_1.port);

BaseService::delete::<BackendRefVO>(&add_o_1.get_unique_name()).await.unwrap();
BackendRefService::delete_vo(&add_o_1.get_unique_name()).await.unwrap();
}
}
Loading

0 comments on commit a78bbbe

Please sign in to comment.