Commit 126e1439 authored by nanamicat's avatar nanamicat

clean

parent b7883357
Pipeline #41996 failed with stages
in 29 seconds
[
{
"id": 3,
"routers": [
1,
3
]
}
]
import express from 'express';
import { Router } from './Router';
import routers from '../import/data/Router.json';
import _ from 'lodash';
import connections from '../import/connections.json';
export const api = express.Router();
api.get('/state', function (req, res, next) {
const result = Router.all.map((from) => ({
id: from.id,
peers: from.peers,
via: Object.fromEntries([...from.via.entries()].map(([to, via]) => [to.id, via.id])),
}));
res.json(result);
});
api.get('/routers', function (req, res, next) {
res.json(routers.map((r) => _.pick(r, ['id', 'name', 'location', 'host', 'sshPort', 'user'])));
});
api.get('/connections', function (req, res, next) {
res.json(connections);
});
use axum::{extract::State, routing::get, Json}; use axum::{routing::get, Json};
use serde::Serialize;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::sync::Arc; use std::sync::Arc;
use tokio::sync::RwLock; use tokio::sync::RwLock;
use crate::data::ConnectionData; use crate::data::{ConnectionData, RouterData};
use crate::router::Router; use crate::router::Router;
#[derive(Clone)] #[derive(Serialize, Clone)]
pub struct AppState { pub struct Info {
pub routers: Arc<RwLock<BTreeMap<u8, Router>>>, pub routers: Arc<Vec<RouterData>>,
pub connections: Arc<BTreeMap<u8, BTreeMap<u8, ConnectionData>>>, pub connections: Arc<BTreeMap<u8, BTreeMap<u8, ConnectionData>>>,
} }
pub fn create_app(routers: Arc<RwLock<BTreeMap<u8, Router>>>, connections: Arc<BTreeMap<u8, BTreeMap<u8, ConnectionData>>>) -> axum::Router { pub fn create_app(routers: Arc<Vec<RouterData>>, connections: Arc<BTreeMap<u8, BTreeMap<u8, ConnectionData>>>, routers2: Arc<RwLock<BTreeMap<u8, Router>>>) -> axum::Router {
axum::Router::new() axum::Router::new()
.route("/connections", get(get_connections)) .route("/info", get(|| async move { Json(Info { routers, connections }) }))
.route("/routers", get(get_routers)) .route("/metrics", get(|| async move { Json(routers2.read().await.clone()) }))
.with_state(AppState { routers, connections })
}
async fn get_connections(State(state): State<AppState>) -> Json<BTreeMap<u8, BTreeMap<u8, ConnectionData>>> {
Json(state.connections.as_ref().clone())
}
async fn get_routers(State(state): State<AppState>) -> Json<BTreeMap<u8, Router>> {
Json(state.routers.read().await.clone())
} }
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Deserialize)] #[derive(Serialize, Deserialize, Clone)]
pub struct RouterData { pub struct RouterData {
pub id: u8, pub id: u8,
pub name: String, pub name: String,
......
use crate::api::create_app; use crate::api::create_app;
use crate::data::{ConnectionData, RouterData}; use crate::data::RouterData;
use crate::protocol::{Change, Report}; use crate::protocol::{Change, Report};
use crate::router::Router; use crate::router::Router;
use crate::settings::{Settings, TIMEOUT}; use crate::settings::{Settings, INTERVAL, TIMEOUT};
use ::config::Config;
use anyhow::Result; use anyhow::Result;
use ::config::Config;
use config::{Environment, File}; use config::{Environment, File};
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::sync::Arc; use std::sync::Arc;
use tokio::net::UdpSocket; use tokio::net::UdpSocket;
use tokio::select; use tokio::select;
use tokio::sync::RwLock; use tokio::sync::RwLock;
use tokio::time::{Duration, interval}; use tokio::time::interval;
mod api; mod api;
mod data; mod data;
...@@ -35,10 +35,13 @@ async fn main() -> Result<()> { ...@@ -35,10 +35,13 @@ async fn main() -> Result<()> {
.build()? .build()?
.try_deserialize()?; .try_deserialize()?;
let routers_data: Vec<RouterData> = serde_json::from_str(&std::fs::read_to_string("../import/data/Router.json")?)?; let routers_data: Arc<Vec<RouterData>> = Arc::new(serde_json::from_str(&std::fs::read_to_string("../import/data/Router.json")?)?);
let connections: BTreeMap<u8, BTreeMap<u8, ConnectionData>> = serde_json::from_str(&std::fs::read_to_string("../import/connections.json")?)?; let connections = Arc::new(serde_json::from_str(&std::fs::read_to_string("../import/connections.json")?)?);
let connections = Arc::new(connections);
let routers: BTreeMap<u8, Router> = routers_data.into_iter().map(|c| (c.id, Router::new(c, &connections))).collect(); // let routers_map: BTreeMap<u8, RouterData> = routers_data.iter().map(|r| (r.id, r.clone())).collect();
// let routers_map = Arc::new(routers_map);
let routers: BTreeMap<u8, Router> = routers_data.iter().map(|c| (c.id, Router::new(c, &connections))).collect();
let routers = Arc::new(RwLock::new(routers)); let routers = Arc::new(RwLock::new(routers));
// let gateway_groups_data: Vec<GatewayGroup> = serde_json::from_str(&std::fs::read_to_string( // let gateway_groups_data: Vec<GatewayGroup> = serde_json::from_str(&std::fs::read_to_string(
// "../import/data/GatewayGroup.json", // "../import/data/GatewayGroup.json",
...@@ -55,7 +58,7 @@ async fn main() -> Result<()> { ...@@ -55,7 +58,7 @@ async fn main() -> Result<()> {
let mut updating: UpdatingState = UpdatingState::default(); let mut updating: UpdatingState = UpdatingState::default();
let listener = tokio::net::TcpListener::bind(config.http_bind).await?; let listener = tokio::net::TcpListener::bind(config.http_bind).await?;
let app = create_app(routers.clone(), connections.clone()); let app = create_app(routers_data, connections.clone(), routers.clone());
tokio::spawn(async move { tokio::spawn(async move {
axum::serve(listener, app).await.unwrap(); axum::serve(listener, app).await.unwrap();
...@@ -65,7 +68,7 @@ async fn main() -> Result<()> { ...@@ -65,7 +68,7 @@ async fn main() -> Result<()> {
println!("UDP listening on {}", config.udp_bind); println!("UDP listening on {}", config.udp_bind);
let mut buf = [0u8; u16::MAX as usize]; // Max UDP size let mut buf = [0u8; u16::MAX as usize]; // Max UDP size
let mut interval = interval(Duration::from_secs(1)); let mut interval = interval(INTERVAL);
loop { loop {
select! { select! {
......
...@@ -11,6 +11,7 @@ use tokio::time::Instant; ...@@ -11,6 +11,7 @@ use tokio::time::Instant;
#[derive(Serialize, Clone)] #[derive(Serialize, Clone)]
pub struct Router { pub struct Router {
pub id: u8, pub id: u8,
#[serde(skip)]
pub seq: u8, pub seq: u8,
// quality from peer to self. HashMap 的 key 是 from. // quality from peer to self. HashMap 的 key 是 from.
pub peers: BTreeMap<u8, PeerQuality>, pub peers: BTreeMap<u8, PeerQuality>,
...@@ -18,6 +19,7 @@ pub struct Router { ...@@ -18,6 +19,7 @@ pub struct Router {
pub plan: BTreeMap<u8, BTreeMap<u8, u8>>, // group id -> region id -> gateway_id pub plan: BTreeMap<u8, BTreeMap<u8, u8>>, // group id -> region id -> gateway_id
#[serde(skip)] #[serde(skip)]
pub time: Instant, // ms pub time: Instant, // ms
#[serde(skip)]
pub addr: Option<SocketAddr>, pub addr: Option<SocketAddr>,
// Static config // Static config
// pub config: RouterData, // pub config: RouterData,
...@@ -32,7 +34,7 @@ impl PartialEq<Self> for Router { ...@@ -32,7 +34,7 @@ impl PartialEq<Self> for Router {
impl Eq for Router {} impl Eq for Router {}
impl Router { impl Router {
pub fn new(data: RouterData, connections: &BTreeMap<u8, BTreeMap<u8, ConnectionData>>) -> Self { pub fn new(data: &RouterData, connections: &BTreeMap<u8, BTreeMap<u8, ConnectionData>>) -> Self {
Self { Self {
id: data.id, id: data.id,
seq: 0, seq: 0,
......
...@@ -6,11 +6,8 @@ use std::time::Duration; ...@@ -6,11 +6,8 @@ use std::time::Duration;
pub struct Settings { pub struct Settings {
pub udp_bind: SocketAddr, pub udp_bind: SocketAddr,
pub http_bind: SocketAddr, pub http_bind: SocketAddr,
// pub interval: u64,
// pub timeout: u64,
// pub timeout2: u64,
// pub throttle: f64,
} }
pub const INTERVAL: Duration = Duration::from_secs(1);
pub const TIMEOUT: Duration = Duration::from_secs(10); pub const TIMEOUT: Duration = Duration::from_secs(10);
pub const THROTTLE: i32 = 10; pub const THROTTLE: i32 = 10;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment