Skip to content

Commit

Permalink
fix frontend issues
Browse files Browse the repository at this point in the history
  • Loading branch information
Dionisio committed Nov 19, 2024
1 parent fb4f866 commit 26af028
Show file tree
Hide file tree
Showing 19 changed files with 191 additions and 122 deletions.
7 changes: 7 additions & 0 deletions api-gateway/backend/src/backends/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,10 @@ pub mod handlers;
pub mod routes;

pub use routes::configure_routes;

/// Inicializar el manejador de backends
pub async fn start_backends_manager() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
println!("Starting Backends Manager...");
// Aquí iría la lógica específica de inicialización del manejador de backends
Ok(())
}
24 changes: 18 additions & 6 deletions api-gateway/backend/src/gateway/crd/gateway.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,24 +105,25 @@ impl GatewayManager {
certificate: &str,
) -> Result<(), GatewayError> {
let gateways: Api<DynamicObject> = Api::namespaced_with(self.client.clone(), namespace, &self.ar);

// Obtener el Gateway existente.
let mut existing_gateway = gateways.get(name).await?;
let mut data = existing_gateway.data;

let mut data = existing_gateway.data.clone(); // Clonar el campo data
// Actualizar el certificado y habilitar TLS.
if let Some(spec) = data.get_mut("spec") {
if let Some(spec_obj) = spec.as_object_mut() {
spec_obj.insert("tlsEnabled".to_string(), serde_json::Value::Bool(true));
spec_obj.insert("certificate".to_string(), serde_json::Value::String(certificate.to_string()));
}
}

// Actualizar el Gateway.

// Reemplazar el Gateway con los cambios actualizados.
existing_gateway.data = data; // Actualizar el campo data después de la edición
gateways.replace(name, &PostParams::default(), &existing_gateway).await?;
Ok(())
}

/// Obtener métricas simuladas de los Gateways.
pub async fn get_metrics(&self) -> Result<Vec<(String, String, u64)>, GatewayError> {
// Ejemplo de métricas simuladas.
Expand All @@ -141,3 +142,14 @@ pub enum GatewayError {
#[error("Error de serialización/deserialización: {0}")]
SerdeError(#[from] serde_json::Error),
}

/// Implementación de conversión de `models::Route` a `gateway::crd::gateway::Route`.
impl From<crate::gateway::models::Route> for Route {
fn from(route: crate::gateway::models::Route) -> Self {
Route {
path: route.path.unwrap_or_default(),
backend: route.backend,
methods: route.methods,
}
}
}
40 changes: 37 additions & 3 deletions api-gateway/backend/src/gateway/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ use actix_web::{web, HttpResponse, Responder};
use serde_json::json;
use kube::Client;

use super::crd::gateway::GatewayManager; // Manager para Gateways
use super::models::{Gateway, Route}; // Modelos compartidos
use crate::gateway::crd::gateway::{GatewaySpec, GatewayInnerSpec, GatewayManager};
use super::models::Gateway; // Modelo de Gateway compartido

/// Listar todos los Gateways disponibles en Kubernetes.
pub async fn list_gateways(client: web::Data<Client>) -> impl Responder {
Expand All @@ -22,7 +22,18 @@ pub async fn list_gateways(client: web::Data<Client>) -> impl Responder {
pub async fn add_gateway(client: web::Data<Client>, gateway: web::Json<Gateway>) -> impl Responder {
let manager = GatewayManager::new(client.get_ref().clone());

match manager.create_gateway("default", &gateway.into_inner()).await {
// Construir `GatewaySpec` basado en el modelo `Gateway`.
let gateway_spec = GatewaySpec {
spec: GatewayInnerSpec {
hostname: gateway.hostname.clone(),
tls_enabled: gateway.tls_enabled,
certificate: gateway.certificate.clone(),
routes: gateway.routes.iter().cloned().map(Into::into).collect(),
},
};


match manager.create_gateway("default", &gateway_spec).await {
Ok(_) => HttpResponse::Created().json(json!({ "message": "Gateway created successfully." })),
Err(e) => {
eprintln!("Error creating Gateway: {:?}", e);
Expand Down Expand Up @@ -73,3 +84,26 @@ pub async fn get_gateway_metrics(client: web::Data<Client>) -> impl Responder {
}
}
}

/// Inicia el servicio de Gateway API.
/// Esto configura y ejecuta todos los endpoints relacionados con Gateways.
pub async fn start_gateway_api(client: Client) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
println!("Starting Gateway API...");

// Configuración del servidor Actix-Web para manejar los endpoints.
actix_web::HttpServer::new(move || {
actix_web::App::new()
.app_data(web::Data::new(client.clone()))
.route("/gateways", web::get().to(list_gateways)) // Endpoint para listar Gateways
.route("/gateways", web::post().to(add_gateway)) // Endpoint para crear Gateway
.route("/gateways/{id}", web::delete().to(delete_gateway)) // Eliminar Gateway
.route("/gateways/tls", web::post().to(configure_tls)) // Configurar TLS
.route("/gateways/metrics", web::get().to(get_gateway_metrics)) // Obtener métricas
})
.bind(("0.0.0.0", 8082))? // Puerto para el Gateway API
.run()
.await?;

println!("Gateway API is running on port 8082.");
Ok(())
}
1 change: 1 addition & 0 deletions api-gateway/backend/src/gateway/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@ pub mod models; // Define las estructuras de datos compartidas
pub mod crd; // Interacción con los CRDs en Kubernetes

pub use handlers::*;
pub use handlers::{start_gateway_api, list_gateways, add_gateway, delete_gateway, configure_tls, get_gateway_metrics};
pub use models::*;
pub use crd::*;
51 changes: 38 additions & 13 deletions api-gateway/backend/src/gateway/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,44 +8,69 @@ use serde::{Deserialize, Serialize};
/// Este modelo mapea directamente los datos necesarios para un Gateway CRD.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Gateway {
pub id: String, // Identificador único del Gateway
pub hostname: String, // Hostname del Gateway
pub tls_enabled: bool, // Indica si TLS está habilitado
pub id: String, // Identificador único del Gateway
pub hostname: String, // Hostname del Gateway
pub tls_enabled: bool, // Indica si TLS está habilitado
pub certificate: Option<String>, // Certificado TLS, si aplica
pub routes: Vec<Route>, // Rutas asociadas a este Gateway
pub routes: Vec<Route>, // Rutas asociadas a este Gateway
pub gateway_class_name: String, // Nombre de la clase del Gateway
pub listeners: Vec<Listener>, // Listeners del Gateway
}

impl Gateway {
/// Convierte un `Gateway` en un `GatewaySpec` para su uso con los CRDs.
pub fn to_spec(&self) -> super::crd::gateway::GatewaySpec {
super::crd::gateway::GatewaySpec {
spec: super::crd::gateway::GatewayInnerSpec {
hostname: self.hostname.clone(),
tls_enabled: self.tls_enabled,
certificate: self.certificate.clone(),
routes: self.routes.iter().map(|r| r.clone().into()).collect(),
},
}
}
}


/// Representa un listener dentro de un Gateway.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Listener {
pub name: String, // Nombre del listener
pub protocol: String, // Protocolo del listener (e.g., HTTP, HTTPS)
pub port: u16, // Puerto del listener
}

/// Representa una ruta dentro de un Gateway.
/// Este modelo mapea las configuraciones necesarias para HTTPRoute, GRPCRoute, o TLSRoute.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Route {
pub id: String, // Identificador único de la ruta
pub id: String, // Identificador único de la ruta
pub path: Option<String>, // Ruta específica (e.g., "/api/*")
pub backend: String, // Nombre del backend asociado
pub backend: String, // Nombre del backend asociado
pub methods: Vec<String>, // Métodos permitidos (e.g., ["GET", "POST"])
pub protocols: Vec<String>, // Protocolos soportados (e.g., ["HTTP", "HTTPS"])
}

/// Representa métricas relacionadas con los Gateways.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GatewayMetric {
pub gateway_id: String, // ID del Gateway asociado
pub metric_name: String, // Nombre de la métrica (e.g., "latency", "requests_per_second")
pub value: f64, // Valor de la métrica
pub timestamp: String, // Marca de tiempo de la métrica
pub gateway_id: String, // ID del Gateway asociado
pub metric_name: String, // Nombre de la métrica (e.g., "latency", "requests_per_second")
pub value: f64, // Valor de la métrica
pub timestamp: String, // Marca de tiempo de la métrica
}

/// Representa la configuración de TLS para un Gateway.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TLSConfig {
pub certificate: String, // Contenido del certificado TLS
pub certificate: String, // Contenido del certificado TLS
pub private_key: Option<String>, // Clave privada asociada, si es necesaria
pub ca_bundle: Option<String>, // Certificados de autoridad, si aplica
pub ca_bundle: Option<String>, // Certificados de autoridad, si aplica
}

/// Representa errores genéricos relacionados con los Gateways o rutas.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GatewayError {
pub message: String, // Descripción del error
pub message: String, // Descripción del error
pub details: Option<String>, // Detalles adicionales sobre el error
}
14 changes: 12 additions & 2 deletions api-gateway/backend/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,12 @@
pub mod gateway;
pub mod rest;
pub mod gateway; // Módulo para Gateway
pub mod backends; // Módulo para manejar Backends
pub mod observability; // Módulo para Observability
pub mod security; // Módulo para Seguridad
pub mod plugins; // Módulo para Plugins
pub mod rest; // REST server

// Reexportar configuraciones de rutas para `main.rs`
// pub use backends::configure_routes as configure_backends_routes;
// pub use observability::configure_routes as configure_observability_routes;
// pub use security::configure_routes as configure_security_routes;
// pub use plugins::configure_routes as configure_plugins_routes;
12 changes: 6 additions & 6 deletions api-gateway/backend/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
Box::<dyn std::error::Error + Send + Sync>::from(e)
}),

// Start Backends manager
start_backends_manager(client.clone()).map_err(|e| {
// Start Backends manager (no arguments required)
start_backends_manager().map_err(|e| {
eprintln!("Error in start_backends_manager: {:?}", e);
Box::<dyn std::error::Error + Send + Sync>::from(e)
}),
Expand All @@ -55,14 +55,14 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
Box::<dyn std::error::Error + Send + Sync>::from(e)
}),

// Start Security service
start_security_service(client.clone()).map_err(|e| {
// Start Security service (no arguments required)
start_security_service().map_err(|e| {
eprintln!("Error in start_security_service: {:?}", e);
Box::<dyn std::error::Error + Send + Sync>::from(e)
}),

// Start Plugins manager
start_plugins_manager(client.clone()).map_err(|e| {
// Start Plugins manager (no arguments required)
start_plugins_manager().map_err(|e| {
eprintln!("Error in start_plugins_manager: {:?}", e);
Box::<dyn std::error::Error + Send + Sync>::from(e)
})
Expand Down
7 changes: 7 additions & 0 deletions api-gateway/backend/src/observability/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,10 @@ pub mod handlers;
pub mod routes;

pub use routes::configure_routes;

/// Inicializar el servicio de observabilidad
pub async fn start_observability_service(port: u16) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
println!("Starting Observability Service on port {}...", port);
// Aquí iría la lógica específica de inicialización de observabilidad
Ok(())
}
10 changes: 10 additions & 0 deletions api-gateway/backend/src/plugins/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
pub mod routes;

pub use routes::configure_routes;

/// Inicializar el manejador de plugins
pub async fn start_plugins_manager() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
println!("Starting Plugins Manager...");
// Aquí iría la lógica específica de inicialización de plugins
Ok(())
}
8 changes: 8 additions & 0 deletions api-gateway/backend/src/plugins/routes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
use actix_web::web;

pub fn configure_routes(cfg: &mut web::ServiceConfig) {
cfg.service(
web::scope("/api/plugins")
.route("/status", web::get().to(|| async { "Plugin status endpoint" })), // Ejemplo
);
}
13 changes: 8 additions & 5 deletions api-gateway/backend/src/security/handlers.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
//! Handlers para la gestión de seguridad en el API Gateway.
use actix_web::{web, HttpResponse, Responder};
use serde::{Deserialize, Serialize};
use std::sync::Mutex;
Expand Down Expand Up @@ -69,8 +67,9 @@ pub async fn add_policy(data: web::Data<AppState>, policy: web::Json<SecurityPol
/// Eliminar una política de seguridad
pub async fn delete_policy(data: web::Data<AppState>, id: web::Path<u32>) -> impl Responder {
let mut policies = data.policies.lock().unwrap();
let id_value = *id; // Clona o copia el valor de `id`.
let initial_len = policies.len();
policies.retain(|policy| policy.id != id.into_inner());
policies.retain(|policy| policy.id != id_value); // Usa la copia aquí.
if policies.len() < initial_len {
HttpResponse::Ok().finish()
} else {
Expand All @@ -80,8 +79,7 @@ pub async fn delete_policy(data: web::Data<AppState>, id: web::Path<u32>) -> imp

/// Validar un token JWT
pub async fn validate_jwt(token: web::Path<String>) -> impl Responder {
// Simulación de validación de JWT
let valid = token == "valid_token";
let valid = token.as_str() == "valid_token"; // Usa `.as_str()` para obtener un `&str`.
if valid {
HttpResponse::Ok().json(JwtValidationResponse {
valid: true,
Expand Down Expand Up @@ -116,3 +114,8 @@ pub async fn update_tls_config(tls_data: web::Json<(String, String)>) -> impl Re
"key": key,
}))
}

/// Endpoint protegido
pub async fn protected_endpoint() -> impl Responder {
HttpResponse::Ok().body("This is a protected endpoint!")
}
7 changes: 7 additions & 0 deletions api-gateway/backend/src/security/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,10 @@ pub mod handlers;
pub mod routes;

pub use routes::configure_routes;

/// Inicializar el servicio de seguridad
pub async fn start_security_service() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
println!("Starting Security Service...");
// Aquí iría la lógica específica de inicialización de seguridad
Ok(())
}
2 changes: 1 addition & 1 deletion api-gateway/backend/src/security/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use super::handlers;
pub fn configure_routes(cfg: &mut web::ServiceConfig) {
cfg.service(
web::scope("/api/security")
.route("/policies", web::get().to(handlers::get_policies))
.route("/policies", web::get().to(handlers::list_policies))
.route("/policies", web::post().to(handlers::add_policy))
.route("/policies/{name}", web::delete().to(handlers::delete_policy))
.route("/protected", web::get().to(handlers::protected_endpoint)),
Expand Down
Loading

0 comments on commit 26af028

Please sign in to comment.