Skip to content

Commit

Permalink
update admin
Browse files Browse the repository at this point in the history
  • Loading branch information
RWDai committed Oct 24, 2023
1 parent 4461e09 commit 74de04d
Show file tree
Hide file tree
Showing 23 changed files with 259 additions and 49 deletions.
54 changes: 27 additions & 27 deletions admin/src/api/gateway_api.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::dto::query_dto::GatewayQueryDto;
use crate::model::query_dto::GatewayQueryDto;
use crate::service::gateway_service::GatewayService;
use kernel_common::inner_model::gateway::SgGateway;
use tardis::web::poem_openapi;
Expand All @@ -13,32 +13,32 @@ pub struct GatewayApi;
#[poem_openapi::OpenApi(prefix_path = "/gateway")]
impl GatewayApi {
/// Get Gateway List
#[oai(path = "/", method = "get")]
async fn list(
&self,
name: Query<Option<String>>,
namespace: Query<Option<String>>,
port: Query<Option<u16>>,
hostname: Query<Option<String>>,
) -> TardisApiResult<Vec<SgGateway>> {
let result = GatewayService::list(
namespace.0.clone(),
GatewayQueryDto {
name: name.0,
namespace: namespace.0,
port: port.0,
hostname: hostname.0,
},
)
.await?;
TardisResp::ok(result)
}

/// Add Gateway
#[oai(path = "/", method = "post")]
async fn add(&self, namespace: Query<Option<String>>, gateway: Json<SgGateway>) -> TardisApiResult<SgGateway> {
TardisResp::ok(GatewayService::add(namespace.0, gateway.0).await?)
}
// #[oai(path = "/", method = "get")]
// async fn list(
// &self,
// name: Query<Option<String>>,
// namespace: Query<Option<String>>,
// port: Query<Option<u16>>,
// hostname: Query<Option<String>>,
// ) -> TardisApiResult<Vec<SgGateway>> {
// let result = GatewayService::list(
// namespace.0.clone(),
// GatewayQueryDto {
// name: name.0,
// namespace: namespace.0,
// port: port.0,
// hostname: hostname.0,
// },
// )
// .await?;
// TardisResp::ok(result)
// }
//
// /// Add Gateway
// #[oai(path = "/", method = "post")]
// async fn add(&self, namespace: Query<Option<String>>, gateway: Json<SgGateway>) -> TardisApiResult<SgGateway> {
// TardisResp::ok(GatewayService::add(namespace.0, gateway.0).await?)
// }

/// Delete Gateway
#[oai(path = "/", method = "delete")]
Expand Down
2 changes: 1 addition & 1 deletion admin/src/api/plugin_api.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::dto::query_dto::PluginQueryDto;
use crate::model::query_dto::PluginQueryDto;
use crate::service::plugin_service::PluginService;
use tardis::web::poem_openapi;
use tardis::web::poem_openapi::param::Query;
Expand Down
3 changes: 3 additions & 0 deletions admin/src/helper.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
use k8s_gateway_api::Gateway;
use k8s_openapi::api::core::v1::ConfigMap;
use kube::Api;
#[cfg(feature = "k8s")]
use kube::Client;
use tardis::basic::error::TardisError;
Expand Down
2 changes: 1 addition & 1 deletion admin/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ use tardis::{basic::result::TardisResult, tokio, TardisFuns};
mod api;
mod config;
mod constants;
mod dto;
mod helper;
mod initializer;
mod model;
mod service;

#[tokio::main]
Expand Down
4 changes: 2 additions & 2 deletions admin/src/dto.rs → admin/src/model.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
pub mod base_dto;
pub mod filter_dto;
pub mod query_dto;

pub mod vo;
pub mod vo_converter;
#[cfg(feature = "k8s")]
pub trait ToFields {
fn to_fields_vec(&self) -> Vec<String>;
Expand Down
5 changes: 0 additions & 5 deletions admin/src/dto/base_dto.rs → admin/src/model/base_dto.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
pub struct CommonPageDto {
pub page_size: u32,
pub page_number: u32,
}

pub struct TargetRefDTO {
pub name: String,
pub kind: Option<String>,
Expand Down
File renamed without changes.
4 changes: 2 additions & 2 deletions admin/src/dto/query_dto.rs → admin/src/model/query_dto.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::dto::base_dto::TargetRefDTO;
use crate::model::base_dto::TargetRefDTO;
#[cfg(feature = "k8s")]
use crate::dto::ToFields;
use crate::model::ToFields;

#[derive(Default)]
pub struct GatewayQueryDto {
Expand Down
4 changes: 4 additions & 0 deletions admin/src/model/vo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
pub mod backend_vo;
pub mod gateway_vo;
pub mod http_route_vo;
pub mod plugin_vo;
25 changes: 25 additions & 0 deletions admin/src/model/vo/backend_vo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use kernel_common::inner_model::gateway::SgProtocol;
use serde::{Deserialize, Serialize};
use tardis::web::poem_openapi;

/// BackendRef defines how a HTTPRoute should forward an HTTP request.
#[derive(Default, Debug, Serialize, Deserialize, Clone, poem_openapi::Object)]
pub struct BackendRefVO {
/// Name is the kubernetes service name OR url host.
pub name_or_host: String,
/// Namespace is the kubernetes namespace
pub namespace: Option<String>,
/// Port specifies the destination port number to use for this resource.
pub port: u16,
/// Timeout specifies the timeout for requests forwarded to the referenced backend.
pub timeout_ms: Option<u64>,
// Protocol specifies the protocol used to talk to the referenced backend.
pub protocol: Option<SgProtocol>,
/// Weight specifies the proportion of requests forwarded to the referenced backend.
/// This is computed as weight/(sum of all weights in this BackendRefs list).
/// For non-zero values, there may be some epsilon from the exact proportion defined here depending on the precision an implementation supports.
/// Weight is not a percentage and the sum of weights does not need to equal 100.
pub weight: Option<u16>,
/// [crate::model::vo::plugin_vo::SgFilterVO]'s id
pub filters: Option<Vec<String>>,
}
51 changes: 51 additions & 0 deletions admin/src/model/vo/gateway_vo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use kernel_common::inner_model::gateway::{SgParameters, SgProtocol, SgTlsMode};
use serde::{Deserialize, Serialize};
use tardis::web::poem_openapi;

/// Gateway represents an instance of a service-traffic handling infrastructure
/// by binding Listeners to a set of IP addresses.
///
/// Reference: [Kubernetes Gateway](https://gateway-api.sigs.k8s.io/references/spec/#gateway.networking.k8s.io/v1beta1.Gateway)
#[derive(Default, Debug, Serialize, Deserialize, Clone, poem_openapi::Object)]
pub struct SgGatewayVO {
/// Name of the Gateway. Global Unique.
///
/// In k8s mode, this name MUST be unique within a namespace.
/// format see [k8s_helper::format_k8s_obj_unique]
pub name: String,
/// Some parameters necessary for the gateway.
pub parameters: SgParameters,
/// Listeners associated with this Gateway. Listeners define logical endpoints
/// that are bound on this Gateway’s addresses.
pub listeners: Vec<SgListenerVO>,
/// [crate::model::vo::plugin_vo::SgFilterVO]'s id
pub filters: Option<Vec<String>>,
}

/// 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 {
/// Name is the name of the Listener. This name MUST be unique within a Gateway.
pub name: String,
/// Ip bound to the Listener. Default is 0.0.0.0
pub ip: Option<String>,
/// Port is the network port. Multiple listeners may use the same port, subject
/// to the Listener compatibility rules.
pub port: u16,
/// Protocol specifies the network protocol this listener expects to receive.
pub protocol: SgProtocol,
/// SgTlsConfig's id refers to the TLS configuration.
pub tls: Option<String>,
/// `HostName` is used to define the host on which the listener accepts requests.
pub hostname: Option<String>,
}

/// GatewayTLSConfig describes a TLS configuration.
/// unique by id
#[derive(Debug, Serialize, Deserialize, Clone, poem_openapi::Object)]
pub struct SgTlsConfigVO {
pub id: String,
pub mode: SgTlsMode,
pub key: String,
pub cert: String,
}
31 changes: 31 additions & 0 deletions admin/src/model/vo/http_route_vo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
use kernel_common::inner_model::http_route::SgHttpRouteMatch;
use serde::{Deserialize, Serialize};
use tardis::web::poem_openapi;

/// HTTPRoute provides a way to route HTTP requests.
///
/// Reference: [Kubernetes Gateway](https://gateway-api.sigs.k8s.io/references/spec/#gateway.networking.k8s.io%2fv1beta1.HTTPRoute)
#[derive(Default, Debug, Serialize, Deserialize, Clone, poem_openapi::Object)]
pub struct SgHttpRoute {
/// Associated gateway name.
pub gateway_name: String,
/// Hostnames defines a set of hostname that should match against the HTTP Host header to select a HTTPRoute to process the request.
pub hostnames: Option<Vec<String>>,
/// [crate::model::vo::plugin_vo::SgFilterVO]'s id
pub filters: Option<Vec<String>>,
/// Rules are a list of HTTP matchers, filters and actions.
pub rules: Option<Vec<SgHttpRouteRuleVO>>,
}

/// HTTPRouteRule defines semantics for matching an HTTP request based on conditions (matches), processing it (filters), and forwarding the request to an API object
#[derive(Default, Debug, Serialize, Deserialize, Clone, poem_openapi::Object)]
pub struct SgHttpRouteRuleVO {
/// Matches define conditions used for matching the rule against incoming HTTP requests. Each match is independent, i.e. this rule will be matched if any one of the matches is satisfied.
pub matches: Option<Vec<SgHttpRouteMatch>>,
/// [crate::model::vo::plugin_vo::SgFilterVO]'s id
pub filters: Option<Vec<String>>,
/// [crate::model::vo::backend_vo::BackendRefVO]'s id
pub backends: Option<Vec<String>>,
/// Timeout define the timeout for requests that match this rule.
pub timeout_ms: Option<u64>,
}
22 changes: 22 additions & 0 deletions admin/src/model/vo/plugin_vo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tardis::web::poem_openapi;

/// RouteFilter defines processing steps that must be completed during the request or response lifecycle.
///
/// There are four levels of filters
/// 1. Global level, which works on all requests under the same gateway service
/// 2. Routing level, which works on all requests under the same gateway route
/// 3. Rule level, which works on all requests under the same gateway routing rule
/// 4. Backend level, which works on all requests under the same backend
#[derive(Default, Debug, Serialize, Deserialize, Clone, poem_openapi::Object)]
pub struct SgFilterVO {
pub id: String,
/// Filter code, Used to match the corresponding filter.
pub code: String,
/// Filter name. If the name of the same filter exists at different levels of configuration,
/// only the child nodes take effect(Backend Level > Rule Level > Routing Level > Global Level)
pub name: Option<String>,
/// filter parameters.
pub spec: Value,
}
Empty file added admin/src/model/vo_converter.rs
Empty file.
3 changes: 3 additions & 0 deletions admin/src/service.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
pub(crate) mod backend_ref_service;
pub(crate) mod base_service;
pub(crate) mod gateway_service;
pub(crate) mod plugin_service;
pub(crate) mod route_service;
Empty file.
58 changes: 58 additions & 0 deletions admin/src/service/base_service.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
use crate::helper::get_k8s_client;
use k8s_openapi::api::core::v1::ConfigMap;
use k8s_openapi::merge_strategies::list;
use kube::api::ListParams;
use kube::Api;
use serde::Deserialize;
use serde_json::Value;
use std::collections::HashMap;
use tardis::basic::error::TardisError;
use tardis::basic::result::TardisResult;

pub const GATEWAY_CONFIG_NAME: &str = "gateway_config";
pub const PLUGIN_CONFIG_NAME: &str = "plugin_config";
pub const ROUTE_CONFIG_NAME: &str = "route_config";
pub const BACKEND_REF_CONFIG_NAME: &str = "backend_ref_config";

pub trait GetConfigMapName {
fn get_config_map_name() -> String;
}

pub struct BaseService;

impl BaseService {
#[cfg(feature = "k8s")]
pub async fn list<'a, T>() -> TardisResult<HashMap<String, String>>
where
T: GetConfigMapName + Deserialize<'a>,
{
let mut items = get_config_map_api()
.await?
.list(&ListParams::default().fields(&format!("metadata.name={}", T::get_config_map_name())))
.await
.map_err(|e| TardisError::io_error(&format!("err:{e}"), ""))?
.items;
if items.is_empty() {
Ok(HashMap::new())
} else {
if let Some(b_map) = items.remove(0).data {
Ok(b_map.into_iter().collect())
} else {
Ok(HashMap::new())
}
}
}

#[cfg(feature = "k8s")]
pub async fn add<'a, T>(config: T) -> TardisResult<()>
where
T: GetConfigMapName + Deserialize<'a>,
{
config
}
}

#[cfg(feature = "k8s")]
pub async fn get_config_map_api() -> TardisResult<Api<ConfigMap>> {
Ok(Api::namespaced(get_k8s_client().await?, "spacegate"))
}
6 changes: 3 additions & 3 deletions admin/src/service/gateway_service.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::dto::query_dto::GatewayQueryDto;
#[cfg(feature = "k8s")]
use crate::dto::ToFields;
#[cfg(feature = "k8s")]
use crate::helper::get_k8s_client;
use crate::model::query_dto::GatewayQueryDto;
#[cfg(feature = "k8s")]
use crate::model::ToFields;

use crate::service::plugin_service::PluginService;
#[cfg(feature = "k8s")]
Expand Down
22 changes: 16 additions & 6 deletions admin/src/service/plugin_service.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use crate::dto::query_dto::PluginQueryDto;
#[cfg(feature = "k8s")]
use crate::dto::ToFields;
#[cfg(feature = "k8s")]
use crate::helper::{get_k8s_client, WarpKubeResult};
use crate::model::query_dto::PluginQueryDto;
use crate::model::vo::plugin_vo::SgFilterVO;
#[cfg(feature = "k8s")]
use crate::model::ToFields;
#[cfg(feature = "k8s")]
use kernel_common::constants::DEFAULT_NAMESPACE;
#[cfg(feature = "k8s")]
Expand All @@ -13,19 +14,28 @@ use kernel_common::k8s_crd::sg_filter::SgFilter;
#[cfg(feature = "k8s")]
use kube::{api::ListParams, api::PostParams, Api, ResourceExt};
use std::collections::HashMap;
use k8s_gateway_api::Gateway;
use tardis::basic::error::TardisError;
use tardis::basic::result::TardisResult;

pub struct PluginService;

impl PluginService {
pub async fn add(add: SgFilterVO) -> TardisResult<Vec<SgRouteFilter>> {
let result = vec![];
#[cfg(feature = "k8s")]
{}
#[cfg(not(feature = "k8s"))]
{}

Ok(result)
}

pub async fn list(query: PluginQueryDto) -> TardisResult<Vec<SgRouteFilter>> {
let result = vec![];
#[cfg(feature = "k8s")]
{
let filter_api: Api<SgFilter> = Self::get_filter_api(&query.namespace).await?;

let _filter_list = filter_api.list(&ListParams::default().fields(&query.to_fields())).await.map_err(|e| TardisError::io_error(&format!("err:{e}"), ""))?;

}
#[cfg(not(feature = "k8s"))]
{}
Expand Down
Empty file.
1 change: 1 addition & 0 deletions kernel-common/src/converter/http_route_k8s_conv.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

2 changes: 0 additions & 2 deletions kernel-common/src/inner_model/gateway.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ use tardis::web::poem_openapi;
///
/// Reference: [Kubernetes Gateway](https://gateway-api.sigs.k8s.io/references/spec/#gateway.networking.k8s.io/v1beta1.Gateway)
#[derive(Default, Debug, Serialize, Deserialize, Clone)]
#[cfg_attr(feature = "admin-support", derive(poem_openapi::Object))]
pub struct SgGateway {
/// Name of the Gateway. Global Unique.
///
Expand Down Expand Up @@ -43,7 +42,6 @@ pub struct SgParameters {

/// Listener embodies the concept of a logical endpoint where a Gateway accepts network connections.
#[derive(Default, Debug, Serialize, Deserialize, Clone)]
#[cfg_attr(feature = "admin-support", derive(poem_openapi::Object))]
pub struct SgListener {
/// Name is the name of the Listener. This name MUST be unique within a Gateway.
pub name: String,
Expand Down
Loading

0 comments on commit 74de04d

Please sign in to comment.