diff --git a/src/rust/Cargo.lock b/src/rust/Cargo.lock index d5af0ccd..99aa51f3 100644 --- a/src/rust/Cargo.lock +++ b/src/rust/Cargo.lock @@ -538,16 +538,6 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" -[[package]] -name = "colored" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c" -dependencies = [ - "lazy_static", - "windows-sys 0.59.0", -] - [[package]] name = "compact_str" version = "0.7.1" @@ -2042,22 +2032,6 @@ dependencies = [ "tracing-subscriber", ] -[[package]] -name = "lqos_support_tool" -version = "0.1.0" -dependencies = [ - "anyhow", - "clap", - "colored", - "libc", - "lqos_config", - "miniz_oxide", - "nix", - "serde", - "serde_cbor", - "serde_json", -] - [[package]] name = "lqos_sys" version = "0.1.0" @@ -2123,7 +2097,6 @@ dependencies = [ "lqos_heimdall", "lqos_queue_tracker", "lqos_stormguard", - "lqos_support_tool", "lqos_sys", "lqos_utils", "mimalloc", diff --git a/src/rust/Cargo.toml b/src/rust/Cargo.toml index 6317e709..6e9b8d51 100644 --- a/src/rust/Cargo.toml +++ b/src/rust/Cargo.toml @@ -30,7 +30,6 @@ members = [ "lqos_map_perf", # A CLI tool for testing eBPF map performance "uisp", # REST support for the UISP API "uisp_integration", # UISP Integration in Rust - "lqos_support_tool", # A Helper tool to make it easier to request/receive support "lqos_stormguard", # An implementation of CAKE AutoRotate using dynamic bus information. EXPERIMENTAL. "lqos_bakery", # The bakery makes CAKEs - controls queue creation. ] @@ -79,4 +78,4 @@ mimalloc = "0.1.43" # For memory debugging allocative = { version = "0.3.3", features = [ "dashmap" ] } -allocative_derive = "0.3.3" \ No newline at end of file +allocative_derive = "0.3.3" diff --git a/src/rust/lqos_bakery/src/diff/sites.rs b/src/rust/lqos_bakery/src/diff/sites.rs index 8971f75c..e8ca179c 100644 --- a/src/rust/lqos_bakery/src/diff/sites.rs +++ b/src/rust/lqos_bakery/src/diff/sites.rs @@ -1,7 +1,7 @@ use crate::BakeryCommands; use std::collections::HashMap; use std::sync::Arc; -use tracing::{debug, info, warn}; +use tracing::{debug, warn}; pub(crate) enum SiteDiffResult { RebuildRequired, @@ -51,7 +51,7 @@ pub(crate) fn diff_sites( ); // Log a concise before/after for diagnostics at warn! level so operators // can see why the site is considered structurally different. - let (ocpu, opar, oup, omin) = match old_cmd.as_ref() { + let (_ocpu, opar, oup, omin) = match old_cmd.as_ref() { crate::BakeryCommands::AddSite { parent_class_id, up_parent_class_id, @@ -65,7 +65,7 @@ pub(crate) fn diff_sites( ), _ => (0, String::new(), String::new(), 0), }; - let (ncpu, npar, nup, nmin) = match new_cmd.as_ref() { + let (_ncpu, npar, nup, nmin) = match new_cmd.as_ref() { crate::BakeryCommands::AddSite { parent_class_id, up_parent_class_id, diff --git a/src/rust/lqos_bus/src/bus/mod.rs b/src/rust/lqos_bus/src/bus/mod.rs index 412cca8f..bc812426 100644 --- a/src/rust/lqos_bus/src/bus/mod.rs +++ b/src/rust/lqos_bus/src/bus/mod.rs @@ -12,13 +12,13 @@ pub use client::{LibreqosBusClient, bus_request}; pub use queue_data::*; pub use reply::BusReply; pub use request::{BlackboardSystem, BusRequest, TopFlowType, UrgentSeverity, UrgentSource}; +#[allow(unused_imports)] pub use response::{ AsnHeatmapData, BakeryStatsSnapshot, BusResponse, CircuitHeatmapData, SiteHeatmapData, StormguardDebugDirection, StormguardDebugEntry, UrgentIssue, }; pub use session::BusSession; use thiserror::Error; -use tracing::error; pub use unix_socket_server::UnixSocketServer; /// The local socket path to which `lqosd` will bind itself, diff --git a/src/rust/lqos_config/src/network_json.rs b/src/rust/lqos_config/src/network_json.rs index 9eb245d9..d58c3b9e 100644 --- a/src/rust/lqos_config/src/network_json.rs +++ b/src/rust/lqos_config/src/network_json.rs @@ -12,7 +12,7 @@ use std::{ path::{Path, PathBuf}, }; use thiserror::Error; -use tracing::{debug, error, warn}; +use tracing::{debug, warn}; /// Holder for the network.json representation. /// This is condensed into a single level vector with index-based referencing diff --git a/src/rust/lqos_queue_tracker/src/queue_structure/mod.rs b/src/rust/lqos_queue_tracker/src/queue_structure/mod.rs index ab490009..ee30f461 100644 --- a/src/rust/lqos_queue_tracker/src/queue_structure/mod.rs +++ b/src/rust/lqos_queue_tracker/src/queue_structure/mod.rs @@ -6,7 +6,6 @@ pub use queing_structure_json_monitor::{QUEUE_STRUCTURE, QUEUE_STRUCTURE_CHANGED use queue_network::QueueNetwork; pub(crate) use queue_node::QueueNode; use thiserror::Error; -use tracing::error; pub(crate) fn read_queueing_structure() -> Result, QueueStructureError> { // Note: the ? is allowed because the sub-types return a QueueStructureError and handle logging. diff --git a/src/rust/lqos_support_tool/src/lib.rs b/src/rust/lqos_support_tool/src/lib.rs index defd7662..aa092aef 100644 --- a/src/rust/lqos_support_tool/src/lib.rs +++ b/src/rust/lqos_support_tool/src/lib.rs @@ -14,8 +14,21 @@ pub use support_info::gather_all_support_info; const REMOTE_SYSTEM: &str = "stats.libreqos.io:9200"; pub fn submit_to_network(dump: SupportDump) { + match submit_to_network_result(dump) { + Ok(()) => { + success("Submitted to LibreQoS for Analysis. Thank you."); + } + Err(err) => { + error(&err); + } + } +} + +pub fn submit_to_network_result(dump: SupportDump) -> Result<(), String> { // Build the payload - let serialized = dump.serialize_and_compress().unwrap(); + let serialized = dump + .serialize_and_compress() + .map_err(|e| format!("Failed to serialize support data: {e}"))?; let length = serialized.len() as u64; let mut bytes = Vec::new(); bytes.extend(1212u32.to_be_bytes()); @@ -24,13 +37,10 @@ pub fn submit_to_network(dump: SupportDump) { bytes.extend(1212u32.to_be_bytes()); // Do the actual connection - let stream = TcpStream::connect(REMOTE_SYSTEM); - if stream.is_err() { - error(&format!("Unable to connect to {REMOTE_SYSTEM}")); - println!("{stream:?}"); - return; - } - let mut stream = stream.unwrap(); - stream.write_all(&bytes).unwrap(); - success("Submitted to LibreQoS for Analysis. Thank you."); + let mut stream = TcpStream::connect(REMOTE_SYSTEM) + .map_err(|e| format!("Unable to connect to {REMOTE_SYSTEM}: {e}"))?; + stream + .write_all(&bytes) + .map_err(|e| format!("Failed to submit support data: {e}"))?; + Ok(()) } diff --git a/src/rust/lqosd/Cargo.toml b/src/rust/lqosd/Cargo.toml index d5792828..aab4f4d6 100644 --- a/src/rust/lqosd/Cargo.toml +++ b/src/rust/lqosd/Cargo.toml @@ -16,7 +16,6 @@ lqos_sys = { path = "../lqos_sys" } lqos_queue_tracker = { path = "../lqos_queue_tracker" } lqos_utils = { path = "../lqos_utils" } lqos_heimdall = { path = "../lqos_heimdall" } -lqos_support_tool = { path = "../lqos_support_tool" } lqos_stormguard = { path = "../lqos_stormguard" } tokio = { version = "1", features = [ "full" ] } once_cell = { workspace = true} diff --git a/src/rust/lqosd/src/lts2_sys/lts2_client/mod.rs b/src/rust/lqosd/src/lts2_sys/lts2_client/mod.rs index a4b9323f..eea54eaf 100644 --- a/src/rust/lqosd/src/lts2_sys/lts2_client/mod.rs +++ b/src/rust/lqosd/src/lts2_sys/lts2_client/mod.rs @@ -408,6 +408,7 @@ pub fn submit_site_rtt_batch(batch: &[shared_types::SiteRtt]) -> anyhow::Result< Ok(()) // SUCCESS } +#[allow(dead_code)] pub fn get_lts_license_status() -> anyhow::Result { if let Ok(tx) = client_commands::get_command_channel() { let (otx, orx) = oneshot::channel(); @@ -429,6 +430,7 @@ pub fn get_lts_license_status() -> anyhow::Result { Err(anyhow::anyhow!("Failed to get command channel")) } +#[allow(dead_code)] pub fn get_lts_license_trial_remaining() -> anyhow::Result { if let Ok(tx) = client_commands::get_command_channel() { let (otx, orx) = oneshot::channel(); diff --git a/src/rust/lqosd/src/node_manager/auth.rs b/src/rust/lqosd/src/node_manager/auth.rs index fbbf2cf2..3ad8b06c 100644 --- a/src/rust/lqosd/src/node_manager/auth.rs +++ b/src/rust/lqosd/src/node_manager/auth.rs @@ -141,6 +141,48 @@ pub async fn auth_layer( Err(Html(BOUNCE)) } +pub async fn login_from_token(token: &str) -> LoginResult { + let mut lock = WEB_USERS.lock().await; + if lock.is_none() { + match WebUsers::does_users_file_exist() { + Ok(true) => { + match WebUsers::load_or_create() { + Ok(users) => { + *lock = Some(users); + } + Err(e) => { + warn!("Unable to load users file for websocket auth: {e}"); + return LoginResult::Denied; + } + } + } + Ok(false) => { + return LoginResult::Denied; + } + Err(e) => { + warn!("Unable to check users file for websocket auth: {e}"); + return LoginResult::Denied; + } + } + } + + let Some(users) = &*lock else { + return LoginResult::Denied; + }; + + let login_result = match users.get_role_from_token(token) { + Ok(UserRole::ReadOnly) => LoginResult::ReadOnly, + Ok(UserRole::Admin) => LoginResult::Admin, + Err(_) => LoginResult::Denied, + }; + + if login_result != LoginResult::Denied { + record_first_login_timestamp_if_needed(); + } + + login_result +} + #[derive(Serialize, Deserialize)] pub struct LoginAttempt { pub username: String, diff --git a/src/rust/lqosd/src/node_manager/js_build/src/all_tree_sankey.js b/src/rust/lqosd/src/node_manager/js_build/src/all_tree_sankey.js index ff31c9ea..ecf4ac1c 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/all_tree_sankey.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/all_tree_sankey.js @@ -28,6 +28,16 @@ function lerpViridis(t) { import {isRedacted} from "./helpers/redact"; import {GenericRingBuffer} from "./helpers/ringbuffer"; import {trimStringWithElipsis} from "./helpers/strings_help"; +import {get_ws_client} from "./pubsub/ws"; + +const wsClient = get_ws_client(); +const listenOnce = (eventName, handler) => { + const wrapped = (msg) => { + wsClient.off(eventName, wrapped); + handler(msg); + }; + wsClient.on(eventName, wrapped); +}; class AllTreeSankeyGraph extends GenericRingBuffer { constructor() { @@ -36,7 +46,8 @@ class AllTreeSankeyGraph extends GenericRingBuffer { onTick(graph) { let self = this; - $.get("/local-api/networkTree", (data) => { + listenOnce("NetworkTree", (msg) => { + const data = msg && msg.data ? msg.data : []; // Maintain a 10-second ringbuffer of recent data this.push(data); @@ -154,6 +165,7 @@ class AllTreeSankeyGraph extends GenericRingBuffer { // Update the graph graph.update(nodes, links); }); + wsClient.send({ NetworkTree: {} }); } } @@ -250,4 +262,4 @@ $("#btnPause").click(() => { } }); -start(); \ No newline at end of file +start(); diff --git a/src/rust/lqosd/src/node_manager/js_build/src/asn_explorer.js b/src/rust/lqosd/src/node_manager/js_build/src/asn_explorer.js index dc2d12cf..e57a1fea 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/asn_explorer.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/asn_explorer.js @@ -1,10 +1,15 @@ import {clearDiv} from "./helpers/builders"; import {scaleNanos, scaleNumber} from "./lq_js_common/helpers/scaling"; +import {get_ws_client} from "./pubsub/ws"; -//const API_URL = "local-api/"; -const API_URL = "local-api/"; -const LIST_URL = API_URL + "asnList"; -const FLOW_URL = API_URL + "flowTimeline/"; +const wsClient = get_ws_client(); +const listenOnce = (eventName, handler) => { + const wrapped = (msg) => { + wsClient.off(eventName, wrapped); + handler(msg); + }; + wsClient.on(eventName, wrapped); +}; let asnList = []; let countryList = []; @@ -29,7 +34,8 @@ function unixTimeToDate(unixTime) { } function asnDropdown() { - $.get(LIST_URL, (data) => { + listenOnce("AsnList", (msg) => { + const data = msg && msg.data ? msg.data : []; asnList = data; // Sort data by row.count, descending @@ -71,10 +77,12 @@ function asnDropdown() { clearDiv(target); target.appendChild(parentDiv); }); + wsClient.send({ AsnList: {} }); } function countryDropdown() { - $.get(API_URL + "countryList", (data) => { + listenOnce("CountryList", (msg) => { + const data = msg && msg.data ? msg.data : []; countryList = data; // Sort data by row.count, descending @@ -113,10 +121,12 @@ function countryDropdown() { clearDiv(target); target.appendChild(parentDiv); }); + wsClient.send({ CountryList: {} }); } function protocolDropdown() { - $.get(API_URL + "protocolList", (data) => { + listenOnce("ProtocolList", (msg) => { + const data = msg && msg.data ? msg.data : []; protocolList = data; // Sort data by row.count, descending @@ -155,29 +165,34 @@ function protocolDropdown() { clearDiv(target); target.appendChild(parentDiv); }); + wsClient.send({ ProtocolList: {} }); } function selectAsn(asn) { - $.get(FLOW_URL + encodeURI(asn), (data) => { + listenOnce("AsnFlowTimeline", (msg) => { + const data = msg && msg.data ? msg.data : []; page = 0; renderAsn(asn, data); }); + wsClient.send({ AsnFlowTimeline: { asn: asn } }); } function selectCountry(country) { - let url = API_URL + "countryTimeline/" + encodeURI(country); - $.get(url, (data) => { + listenOnce("CountryFlowTimeline", (msg) => { + const data = msg && msg.data ? msg.data : []; page = 0; renderAsn(country, data); }); + wsClient.send({ CountryFlowTimeline: { iso_code: country } }); } function selectProtocol(protocol) { - let url = API_URL + "protocolTimeline/" + encodeURI(protocol.replace('/', '_')); - $.get(url, (data) => { + listenOnce("ProtocolFlowTimeline", (msg) => { + const data = msg && msg.data ? msg.data : []; page = 0; renderAsn(protocol, data); }); + wsClient.send({ ProtocolFlowTimeline: { protocol: protocol } }); } function renderAsn(asn, data) { @@ -507,4 +522,4 @@ function drawTimeline() { asnDropdown(); countryDropdown(); -protocolDropdown(); \ No newline at end of file +protocolDropdown(); diff --git a/src/rust/lqosd/src/node_manager/js_build/src/chatbot.js b/src/rust/lqosd/src/node_manager/js_build/src/chatbot.js index 1f32c9ad..b613949b 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/chatbot.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/chatbot.js @@ -1,9 +1,5 @@ -// Node Manager Chatbot UI using private_ws and persistent gateway proxy - -function private_ws_url() { - const proto = window.location.protocol === 'https:' ? 'wss://' : 'ws://'; - return proto + window.location.host + '/websocket/private_ws'; -} +// Node Manager Chatbot UI using unified websocket client +import { get_ws_client } from "./pubsub/ws"; const log = document.getElementById('chatLog'); const input = document.getElementById('chatInput'); @@ -220,21 +216,18 @@ function handleStreamText(text) { } } -let ws = null; +let client = null; if (insightEnabled) { - ws = new WebSocket(private_ws_url()); - ws.onopen = () => { - appendSys('Connected to Libby'); - const startMsg = { Chatbot: { browser_ts_ms: Date.now() } }; - ws.send(JSON.stringify(startMsg)); - }; - ws.onmessage = (ev) => { - const text = typeof ev.data === 'string' ? ev.data : String(ev.data || ''); - handleStreamText(text); - }; - ws.onclose = () => appendSys('Disconnected'); + client = get_ws_client(); + client.on("ChatbotChunk", (msg) => { + if (msg && typeof msg.text === "string") { + handleStreamText(msg.text); + } + }); + appendSys("Connected to Libby"); + client.send({ Private: { Chatbot: { browser_ts_ms: Date.now() } } }); } else { - appendSys('Libby requires an active Insight subscription. Start a free trial to enable chat.'); + appendSys("Libby requires an active Insight subscription. Start a free trial to enable chat."); } function sendText() { @@ -242,9 +235,8 @@ function sendText() { if (!insightEnabled) return; if (!text) return; bubbleUser(text); - const msg = { ChatbotUserInput: { text } }; - if (ws) { - ws.send(JSON.stringify(msg)); + if (client) { + client.send({ Private: { ChatbotUserInput: { text } } }); } input.value = ''; } diff --git a/src/rust/lqosd/src/node_manager/js_build/src/circuit.js b/src/rust/lqosd/src/node_manager/js_build/src/circuit.js index bcbd5f5c..a6e4f822 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/circuit.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/circuit.js @@ -8,7 +8,7 @@ import {CircuitRetransmitGraph} from "./graphs/circuit_retransmit_graph"; import {scaleNanos, scaleNumber} from "./lq_js_common/helpers/scaling"; import {DevicePingHistogram} from "./graphs/device_ping_graph"; import {FlowsSankey} from "./graphs/flow_sankey"; -import {subscribeWS} from "./pubsub/ws"; +import {get_ws_client, subscribeWS} from "./pubsub/ws"; import {CakeBacklog} from "./graphs/cake_backlog"; import {CakeDelays} from "./graphs/cake_delays"; import {CakeQueueLength} from "./graphs/cake_queue_length"; @@ -33,6 +33,55 @@ let devicePings = []; let flowSankey = null; let funnelGraphs = {}; let funnelParents = []; +const wsClient = get_ws_client(); +const listenOnce = (eventName, handler) => { + const wrapped = (msg) => { + wsClient.off(eventName, wrapped); + handler(msg); + }; + wsClient.on(eventName, wrapped); +}; + +function formatIpBytes(bytes) { + const list = Array.from(bytes); + if (list.length === 4) { + return list.join("."); + } + if (list.length === 16) { + const parts = []; + for (let i = 0; i < list.length; i += 2) { + const part = (list[i] << 8) | list[i + 1]; + parts.push(part.toString(16).padStart(4, "0")); + } + return parts.join(":"); + } + return list.join("."); +} + +function ipToString(ip) { + if (typeof ip === "string") { + return ip; + } + if (ip instanceof Uint8Array || Array.isArray(ip)) { + return formatIpBytes(ip); + } + return String(ip); +} + +function requestCircuitById(onSuccess, onError) { + listenOnce("CircuitByIdResult", (msg) => { + if (!msg || !msg.ok) { + if (onError) onError(); + return; + } + if (msg.id && msg.id !== circuit_id) { + if (onError) onError(); + return; + } + onSuccess(msg.devices || []); + }); + wsClient.send({ CircuitById: { id: circuit_id } }); +} function connectPrivateChannel() { channelLink = new DirectChannel({ @@ -52,10 +101,10 @@ function fullIpList(circuits) { let ipList = []; circuits.forEach((circuit) => { circuit.ipv4.forEach((ip) => { - ipList.push([ip[0], circuit.device_id]); + ipList.push([ipToString(ip[0]), circuit.device_id]); }); circuit.ipv6.forEach((ip) => { - ipList.push([ip[0], circuit.device_id]); + ipList.push([ipToString(ip[0]), circuit.device_id]); }); }); return ipList; @@ -624,7 +673,8 @@ function initialDevices(circuits) { function initialFunnel(parentNode) { let target = document.getElementById("theFunnel"); - $.get("/local-api/networkTree", (data) => { + listenOnce("NetworkTree", (msg) => { + const data = msg && msg.data ? msg.data : []; let immediateParent = null; data.forEach((node) => { if (node[1].name === parentNode) { @@ -693,6 +743,7 @@ function initialFunnel(parentNode) { subscribeWS(["NetworkTree"], onTreeEvent); }, 0)}); }); + wsClient.send({ NetworkTree: {} }); } function onTreeEvent(msg) { @@ -859,14 +910,15 @@ function wireupAnalysis(circuits) { let address = ip[0]; // For closure capture item.onclick = () => { //console.log("Clicky " + address); - $.get("/local-api/requestAnalysis/" + encodeURI(address), (data) => { - //console.log(data); - if (data === "Fail") { + listenOnce("RequestAnalysisResult", (msg) => { + const data = msg ? msg.data : null; + const okData = data && data.Ok ? data.Ok : null; + if (!okData) { alert("Packet capture is already active for another IP. Please try again when it is finished.") return; } - let counter = parseInt(data.Ok.countdown)+1; - let sessionId = data.Ok.session_id; + let counter = parseInt(okData.countdown) + 1; + let sessionId = okData.session_id; let btn = document.getElementById("CaptureTopBtn"); btn.disabled = true; btn.innerHTML = " Capturing Packets (" + counter + ")"; @@ -884,14 +936,8 @@ function wireupAnalysis(circuits) { //console.log(url); // Restore the buttons - $.ajax({ - type: "POST", - url: "/local-api/circuitById", - data: JSON.stringify({id: circuit_id}), - contentType: 'application/json', - success: (circuits) => { - wireupAnalysis(circuits); - } + requestCircuitById((circuits) => { + wireupAnalysis(circuits); }); } return; @@ -899,6 +945,7 @@ function wireupAnalysis(circuits) { btn.innerHTML = " Capturing Packets (" + counter + ")"; }, 1000); }); + wsClient.send({ RequestAnalysis: { ip: address } }); } entry.appendChild(item); listUl.appendChild(entry); @@ -917,39 +964,31 @@ function download(dataurl, filename) { } function loadInitial() { - $.ajax({ - type: "POST", - url: "/local-api/circuitById", - data: JSON.stringify({ id: circuit_id }), - contentType: 'application/json', - success: (circuits) => { - //console.log(circuits); - let circuit = circuits[0]; - $("#circuitName").text(circuit.circuit_name); - $("#parentNode").text(circuit.parent_node); - $("#bwMax").text(formatMbps(circuit.download_max_mbps) + " / " + formatMbps(circuit.upload_max_mbps)); - $("#bwMin").text(formatMbps(circuit.download_min_mbps) + " / " + formatMbps(circuit.upload_min_mbps)); - plan = { - down: circuit.download_max_mbps, - up: circuit.upload_max_mbps, - }; - initialDevices(circuits); - speedometer = new BitsPerSecondGauge("bitsGauge", "Plan"); - totalThroughput = new CircuitTotalGraph("throughputGraph", "Total Circuit Throughput"); - totalRetransmits = new CircuitRetransmitGraph("rxmitGraph", "Total Circuit Retransmits"); - flowSankey = new FlowsSankey("flowSankey"); - - connectPrivateChannel(); - connectPingers(circuits); - connectFlowChannel(); - initialFunnel(circuit.parent_node); - subscribeToCake(); - wireupAnalysis(circuits); - }, - error: () => { - alert("Circuit with id " + circuit_id + " not found"); - } - }) + requestCircuitById((circuits) => { + let circuit = circuits[0]; + $("#circuitName").text(circuit.circuit_name); + $("#parentNode").text(circuit.parent_node); + $("#bwMax").text(formatMbps(circuit.download_max_mbps) + " / " + formatMbps(circuit.upload_max_mbps)); + $("#bwMin").text(formatMbps(circuit.download_min_mbps) + " / " + formatMbps(circuit.upload_min_mbps)); + plan = { + down: circuit.download_max_mbps, + up: circuit.upload_max_mbps, + }; + initialDevices(circuits); + speedometer = new BitsPerSecondGauge("bitsGauge", "Plan"); + totalThroughput = new CircuitTotalGraph("throughputGraph", "Total Circuit Throughput"); + totalRetransmits = new CircuitRetransmitGraph("rxmitGraph", "Total Circuit Retransmits"); + flowSankey = new FlowsSankey("flowSankey"); + + connectPrivateChannel(); + connectPingers(circuits); + connectFlowChannel(); + initialFunnel(circuit.parent_node); + subscribeToCake(); + wireupAnalysis(circuits); + }, () => { + alert("Circuit with id " + circuit_id + " not found"); + }); } loadInitial(); diff --git a/src/rust/lqosd/src/node_manager/js_build/src/config/config_helper.js b/src/rust/lqosd/src/node_manager/js_build/src/config/config_helper.js index dadf51f2..5f5b341b 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/config/config_helper.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/config/config_helper.js @@ -1,26 +1,60 @@ -export function loadConfig(onComplete) { - $.get("/local-api/getConfig", (data) => { - window.config = data; - onComplete(); - }); +import { get_ws_client } from "../pubsub/ws"; + +const wsClient = get_ws_client(); + +function sendWsRequest(responseEvent, request, onComplete, onError) { + let done = false; + const responseHandler = (msg) => { + if (done) return; + done = true; + wsClient.off(responseEvent, responseHandler); + wsClient.off("Error", errorHandler); + onComplete(msg); + }; + const errorHandler = (msg) => { + if (done) return; + done = true; + wsClient.off(responseEvent, responseHandler); + wsClient.off("Error", errorHandler); + if (onError) { + onError(msg); + } + }; + wsClient.on(responseEvent, responseHandler); + wsClient.on("Error", errorHandler); + wsClient.send(request); } -export function saveConfig(onComplete) { - $.ajax({ - type: "POST", - url: "/local-api/updateConfig", - data: JSON.stringify(window.config), - contentType: 'application/json', - success: () => { - onComplete(); +export function loadConfig(onComplete, onError) { + sendWsRequest( + "GetConfig", + { GetConfig: {} }, + (msg) => { + window.config = msg.data; + if (onComplete) onComplete(msg); }, - error: () => { - alert("That didn't work"); - } - }); + onError, + ); } -export function saveNetworkAndDevices(network_json, shaped_devices, onComplete) { +export function saveConfig(onComplete, onError) { + sendWsRequest( + "UpdateConfigResult", + { UpdateConfig: { config: window.config } }, + (msg) => { + if (onComplete) onComplete(msg); + }, + (msg) => { + if (onError) { + onError(msg); + } else { + alert("That didn't work"); + } + }, + ); +} + +export function saveNetworkAndDevices(network_json, shaped_devices, onComplete, onError) { // Validate network_json structure if (!network_json || typeof network_json !== 'object') { alert("Invalid network configuration"); @@ -83,26 +117,110 @@ export function saveNetworkAndDevices(network_json, shaped_devices, onComplete) }; console.log(submission); - // Send to server and handle plain-text "Ok" response - $.ajax({ - type: "POST", - url: "/local-api/updateNetworkAndDevices", - contentType: 'application/json', - data: JSON.stringify(submission), - success: (data) => { - if (onComplete) onComplete(data === "Ok", data); + sendWsRequest( + "UpdateNetworkAndDevicesResult", + { UpdateNetworkAndDevices: submission }, + (msg) => { + if (onComplete) onComplete(!!msg.ok, msg.message); }, - error: (xhr) => { - const errorMsg = xhr.responseText || xhr.statusText || "Request failed"; - console.error("AJAX Error:", { - status: xhr.status, - statusText: xhr.statusText, - response: xhr.responseText - }); + (msg) => { + const errorMsg = (msg && msg.message) ? msg.message : "Request failed"; if (onComplete) onComplete(false, errorMsg); - alert("Error saving configuration: " + errorMsg); - } - }); + if (onError) { + onError(msg); + } else { + alert("Error saving configuration: " + errorMsg); + } + }, + ); +} + +export function adminCheck(onComplete, onError) { + sendWsRequest( + "AdminCheck", + { AdminCheck: {} }, + (msg) => { + if (onComplete) onComplete(!!msg.ok); + }, + onError, + ); +} + +export function listNics(onComplete, onError) { + sendWsRequest( + "ListNics", + { ListNics: {} }, + (msg) => { + if (onComplete) onComplete(msg.data || []); + }, + onError, + ); +} + +export function loadNetworkJson(onComplete, onError) { + sendWsRequest( + "NetworkJson", + { NetworkJson: {} }, + (msg) => { + if (onComplete) onComplete(msg.data); + }, + onError, + ); +} + +export function loadAllShapedDevices(onComplete, onError) { + sendWsRequest( + "AllShapedDevices", + { AllShapedDevices: {} }, + (msg) => { + if (onComplete) onComplete(msg.data || []); + }, + onError, + ); +} + +export function getUsers(onComplete, onError) { + sendWsRequest( + "GetUsers", + { GetUsers: {} }, + (msg) => { + if (onComplete) onComplete(msg.data || []); + }, + onError, + ); +} + +export function addUser(payload, onComplete, onError) { + sendWsRequest( + "AddUserResult", + { AddUser: payload }, + (msg) => { + if (onComplete) onComplete(msg); + }, + onError, + ); +} + +export function updateUser(payload, onComplete, onError) { + sendWsRequest( + "UpdateUserResult", + { UpdateUser: payload }, + (msg) => { + if (onComplete) onComplete(msg); + }, + onError, + ); +} + +export function deleteUser(payload, onComplete, onError) { + sendWsRequest( + "DeleteUserResult", + { DeleteUser: payload }, + (msg) => { + if (onComplete) onComplete(msg); + }, + onError, + ); } export function validNodeList(network_json) { diff --git a/src/rust/lqosd/src/node_manager/js_build/src/config_devices.js b/src/rust/lqosd/src/node_manager/js_build/src/config_devices.js index 37d0ef03..c5c91825 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/config_devices.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/config_devices.js @@ -1,4 +1,10 @@ -import { renderConfigMenu, saveNetworkAndDevices, validNodeList } from "./config/config_helper"; +import { + loadAllShapedDevices, + loadNetworkJson, + renderConfigMenu, + saveNetworkAndDevices, + validNodeList, +} from "./config/config_helper"; let shaped_devices = null; let network_json = null; @@ -157,12 +163,16 @@ function start() { // Render the configuration menu renderConfigMenu('devices'); // Load shaped devices data - $.get("/local-api/networkJson", (njs) => { + loadNetworkJson((njs) => { network_json = njs; - $.get("/local-api/allShapedDevices", (data) => { + loadAllShapedDevices((data) => { shaped_devices = data; shapedDevices(); + }, () => { + alert("Failed to load shaped devices"); }); + }, () => { + alert("Failed to load network configuration"); }); // Setup button handlers diff --git a/src/rust/lqosd/src/node_manager/js_build/src/config_network.js b/src/rust/lqosd/src/node_manager/js_build/src/config_network.js index 099f706c..d67a4cdf 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/config_network.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/config_network.js @@ -1,4 +1,9 @@ -import {saveNetworkAndDevices, renderConfigMenu} from "./config/config_helper"; +import { + loadAllShapedDevices, + loadNetworkJson, + renderConfigMenu, + saveNetworkAndDevices, +} from "./config/config_helper"; let network_json = null; let shaped_devices = null; @@ -264,12 +269,16 @@ function start() { }); // Load network data - $.get("/local-api/allShapedDevices", (data) => { + loadAllShapedDevices((data) => { shaped_devices = data; - $.get("/local-api/networkJson", (njs) => { + loadNetworkJson((njs) => { network_json = njs; renderNetwork(); + }, () => { + alert("Failed to load network configuration"); }); + }, () => { + alert("Failed to load shaped devices"); }); } diff --git a/src/rust/lqosd/src/node_manager/js_build/src/config_stormguard.js b/src/rust/lqosd/src/node_manager/js_build/src/config_stormguard.js index 782cbb83..f9674a3a 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/config_stormguard.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/config_stormguard.js @@ -1,37 +1,36 @@ -import {saveConfig, loadConfig, renderConfigMenu} from "./config/config_helper"; +import { + loadConfig, + loadNetworkJson, + renderConfigMenu, + saveConfig, +} from "./config/config_helper"; let networkData = null; let selectedTargets = []; // Load network.json for site dropdown function loadNetworkData() { - return fetch('/local-api/networkJson', { - method: 'GET', - headers: { - 'Accept': 'application/json', - }, - credentials: 'same-origin' - }) - .then(response => { - if (!response.ok) { - throw new Error('Network response was not ok'); - } - return response.json(); - }) - .then(data => { - // Check if we got the "Not done yet" response - if (typeof data === 'string' && data === 'Not done yet') { - console.error('Network.json file not found on server'); - alert('Network configuration not found. Please ensure network.json exists.'); - return; - } - networkData = data; - console.log('Network data loaded:', networkData); - populateSiteSelector(); - }) - .catch(error => { - console.error('Error loading network data:', error); - alert('Failed to load network sites. Please refresh the page.'); + return new Promise((resolve, reject) => { + loadNetworkJson( + (data) => { + // Check if we got the "Not done yet" response + if (typeof data === 'string' && data === 'Not done yet') { + console.error('Network.json file not found on server'); + alert('Network configuration not found. Please ensure network.json exists.'); + resolve(); + return; + } + networkData = data; + console.log('Network data loaded:', networkData); + populateSiteSelector(); + resolve(); + }, + (err) => { + console.error('Error loading network data:', err); + alert('Failed to load network sites. Please refresh the page.'); + reject(err); + }, + ); }); } @@ -225,4 +224,4 @@ Promise.all([ }); } }); -}); \ No newline at end of file +}); diff --git a/src/rust/lqosd/src/node_manager/js_build/src/config_users.js b/src/rust/lqosd/src/node_manager/js_build/src/config_users.js index cd5ea1bb..faad3ab1 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/config_users.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/config_users.js @@ -1,4 +1,10 @@ -import {renderConfigMenu} from "./config/config_helper"; +import { + addUser, + deleteUser, + getUsers, + renderConfigMenu, + updateUser, +} from "./config/config_helper"; $(document).ready(() => { // Render the configuration menu @@ -18,25 +24,26 @@ $(document).ready(() => { return; } - $.ajax({ - type: "POST", - url: "/local-api/addUser", - data: JSON.stringify({ + addUser( + { username: username, password: password, - role: role - }), - contentType: 'application/json', - success: () => { - $('#username').val(''); - $('#password').val(''); - loadUsers(); + role: role, }, - error: (e) => { + (msg) => { + if (msg && msg.ok) { + $('#add-username').val(''); + $('#password').val(''); + loadUsers(); + } else { + alert(msg && msg.message ? msg.message : 'Failed to add user'); + } + }, + (e) => { alert('Failed to add user'); console.log(e); - } - }); + }, + ); }); // Handle edit user form submission @@ -56,25 +63,26 @@ $(document).ready(() => { payload.password = password; } - $.ajax({ - type: "POST", - url: "/local-api/updateUser", - data: JSON.stringify(payload), - contentType: 'application/json', - success: () => { - $('#edit-password').val(''); - $('#editUserModal').modal('hide'); - loadUsers(); + updateUser( + payload, + (msg) => { + if (msg && msg.ok) { + $('#edit-password').val(''); + $('#editUserModal').modal('hide'); + loadUsers(); + } else { + alert(msg && msg.message ? msg.message : 'Failed to update user'); + } }, - error: () => { + () => { alert('Failed to update user'); - } - }); + }, + ); }); }); function loadUsers() { - $.get('/local-api/getUsers', (users) => { + getUsers((users) => { const userList = $('#users-list'); userList.empty(); @@ -120,22 +128,23 @@ function loadUsers() { $('.delete-user').on('click', function() { if (confirm('Are you sure you want to delete this user?')) { const username = $(this).data('username'); - $.ajax({ - type: "POST", - url: "/local-api/deleteUser", - data: JSON.stringify({ username: username }), - contentType: 'application/json', - success: () => { - loadUsers(); + deleteUser( + { username: username }, + (msg) => { + if (msg && msg.ok) { + loadUsers(); + } else { + alert(msg && msg.message ? msg.message : 'Failed to delete user'); + } }, - error: (e) => { + (e) => { console.error(e); alert('Failed to delete user'); - } - }); + }, + ); } }); - }).fail(() => { + }, () => { $('#users-list').html('
Failed to load users
'); }); } diff --git a/src/rust/lqosd/src/node_manager/js_build/src/configuration.js b/src/rust/lqosd/src/node_manager/js_build/src/configuration.js index aab50514..a72a8b95 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/configuration.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/configuration.js @@ -1,10 +1,36 @@ // Mostly ported from the original node manager +import { get_ws_client } from "./pubsub/ws"; let nics = null; let lqosd_config = null; let shaped_devices = null; let network_json = null; +const wsClient = get_ws_client(); + +function sendWsRequest(responseEvent, request, onComplete, onError) { + let done = false; + const responseHandler = (msg) => { + if (done) return; + done = true; + wsClient.off(responseEvent, responseHandler); + wsClient.off("Error", errorHandler); + onComplete(msg); + }; + const errorHandler = (msg) => { + if (done) return; + done = true; + wsClient.off(responseEvent, responseHandler); + wsClient.off("Error", errorHandler); + if (onError) { + onError(msg); + } + }; + wsClient.on(responseEvent, responseHandler); + wsClient.on("Error", errorHandler); + wsClient.send(request); +} + const bindings = [ // General { field: "bindVersion", path: ".version", data: "string", editable: false }, @@ -123,6 +149,26 @@ const bindings = [ ]; +function getConfigPath(path) { + if (!path || lqosd_config == null) { + return { found: false, value: undefined }; + } + let trimmed = path.startsWith(".") ? path.slice(1) : path; + if (trimmed.length === 0) { + return { found: true, value: lqosd_config }; + } + let current = lqosd_config; + let parts = trimmed.split("."); + for (let i = 0; i < parts.length; i++) { + let part = parts[i]; + if (current == null || !Object.prototype.hasOwnProperty.call(current, part)) { + return { found: false, value: undefined }; + } + current = current[part]; + } + return { found: true, value: current }; +} + function doBindings() { let active = true; @@ -132,8 +178,8 @@ function doBindings() { if (entry.conditional != null) { console.log("Conditional encountered"); if (entry.condition === "if_exists") { - let val = "lqosd_config" + entry.path; - if (eval(val) != null) { + let result = getConfigPath(entry.path); + if (result.found && result.value != null) { console.log("Conditional fired"); active = true; if (entry.showDiv != null) { @@ -155,8 +201,7 @@ function doBindings() { console.log("Skipping " + entry.path); continue; } - let value_location = "lqosd_config" + entry.path; - let value = eval(value_location); + let value = getConfigPath(entry.path).value; let controlId = "#" + entry.field; if (entry.data === "bool") { $(controlId).prop('checked', value); @@ -164,19 +209,17 @@ function doBindings() { $(controlId + " select").val(value); } else if (entry.data === "array_of_strings") { let expanded = ""; - let length = eval("lqosd_config" + entry.path + ".length"); - for (let j = 0; j < length; j++) { - let v = eval("lqosd_config" + entry.path + "[" + j + "]"); - expanded += v + " "; + let values = Array.isArray(value) ? value : []; + for (let j = 0; j < values.length; j++) { + expanded += values[j] + " "; } expanded = expanded.trimEnd(); $(controlId).val(expanded); } else if (entry.data === "ip_array") { let expanded = ""; - let length = eval("lqosd_config" + entry.path + ".length"); - for (let j = 0; j < length; j++) { - let v = eval("lqosd_config" + entry.path + "[" + j + "]"); - expanded += v + "\n"; + let values = Array.isArray(value) ? value : []; + for (let j = 0; j < values.length; j++) { + expanded += values[j] + "\n"; } expanded = expanded.trimEnd(); $(controlId).val(expanded); @@ -226,7 +269,6 @@ function detectChanges() { let controlId = entry.field; if (entry.path === ".bridge" || entry.path === ".single_interface") continue; if (entry.path != null) { - let path = "lqosd_config" + entry.path; let currentValue = $("#" + controlId).val(); // TODO: Bridge/Stick special case if (entry.data === "bool") { @@ -236,20 +278,20 @@ function detectChanges() { } else if (entry.data === "ip_array") { currentValue = currentValue.split('\n'); } - try { - let storedValue = eval(path); - if (entry.data === "string" || entry.data === "integer") { - if (storedValue === null && currentValue === "") - currentValue = null; - } - //console.log(path, currentValue, storedValue); - if (String(currentValue) !== String(storedValue)) { - console.log("Change detected!"); - console.log(entry.path, " has changed. ", storedValue, '=>', currentValue); - changes.push(i); - } - } catch { - //console.log(path + 'ignored'); + let result = getConfigPath(entry.path); + if (!result.found) { + continue; + } + let storedValue = result.value; + if (entry.data === "string" || entry.data === "integer") { + if (storedValue === null && currentValue === "") + currentValue = null; + } + //console.log(entry.path, currentValue, storedValue); + if (String(currentValue) !== String(storedValue)) { + console.log("Change detected!"); + console.log(entry.path, " has changed. ", storedValue, '=>', currentValue); + changes.push(i); } } } @@ -391,19 +433,21 @@ function saveConfig() { if (!validationResult.valid) return; updateSavedConfig(validationResult.changes); - $.ajax({ - type: "POST", - url: "/local-api/updateConfig", - contentType:"application/json", - data: JSON.stringify(lqosd_config), - success: (data) => { - if (data === "Ok") { + sendWsRequest( + "UpdateConfigResult", + { UpdateConfig: { config: lqosd_config } }, + (msg) => { + if (msg && msg.ok) { alert("Configuration saved"); } else { - alert("Configuration not saved: " + data); + const message = msg && msg.message ? msg.message : "Error"; + alert("Configuration not saved: " + message); } - } - }) + }, + () => { + alert("Configuration not saved: Error"); + }, + ); } function iterateNetJson(level, depth) { @@ -786,82 +830,6 @@ function checkIpv6Duplicate(ip, index) { return -1; } -function validNodeList() { - let nodes = []; - - function iterate(data, level) { - for (const [key, value] of Object.entries(data)) { - nodes.push(key); - if (value.children != null) - iterate(value.children, level+1); - } - } - - iterate(network_json, 0); - - return nodes; -} - -function checkIpv4(ip) { - const ipv4Pattern = - /^(\d{1,3}\.){3}\d{1,3}$/; - - if (ip.indexOf('/') === -1) { - return ipv4Pattern.test(ip); - } else { - let parts = ip.split('/'); - return ipv4Pattern.test(parts[0]); - } -} - -function checkIpv6(ip) { - // Check if the input is a valid IPv6 address with prefix - const regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))(\/([0-9]{1,3}))?$/; - return regex.test(ip); -} - -function checkIpv4Duplicate(ip, index) { - ip = ip.trim(); - for (let i=0; i < shaped_devices.length; i++) { - if (i !== index) { - let sd = shaped_devices[i]; - for (let j=0; j 0) { - formatted = sd.ipv4[j][0] + "/" + sd.ipv4[j][1]; - } else { - formatted = sd.ipv4[j][0]; - } - if (formatted === ip) { - return index; - } - } - } - } - return -1; -} - -function checkIpv6Duplicate(ip, index) { - ip = ip.trim(); - for (let i=0; i < shaped_devices.length; i++) { - if (i !== index) { - let sd = shaped_devices[i]; - for (let j=0; j 0) { - formatted = sd.ipv6[j][0] + "/" + sd.ipv6[j][1]; - } else { - formatted = sd.ipv6[j][0]; - } - if (formatted === ip) { - return index; - } - } - } - } - return -1; -} - function validateSd() { let valid = true; let errors = []; @@ -1136,19 +1104,21 @@ function saveNetAndDevices() { shaped_devices: shaped_devices, network_json: network_json, } - $.ajax({ - type: "POST", - url: "/local-api/updateNetworkAndDevices", - contentType:"application/json", - data: JSON.stringify(submission), - success: (data) => { - if (data === "Ok") { + sendWsRequest( + "UpdateNetworkAndDevicesResult", + { UpdateNetworkAndDevices: submission }, + (msg) => { + if (msg && msg.ok) { alert("Configuration saved"); } else { - alert("Configuration not saved: " + data); + const message = msg && msg.message ? msg.message : "Error"; + alert("Configuration not saved: " + message); } - } - }) + }, + () => { + alert("Configuration not saved: Error"); + }, + ); } function shapedDevices() { @@ -1252,49 +1222,80 @@ function start() { // Old display(); - $.get("/local-api/adminCheck", (is_admin) => { - if (!is_admin) { - $("#controls").html("
Failed to load summary: ${e}
`; +function fetchSummary() { + const target = document.getElementById("cpuSummary"); + if (target) { + target.innerHTML = ' Loading summary...'; } + const configPromise = requestConfig().then((cfg) => { + state.plannerEnabled = !!(cfg && cfg.queues && cfg.queues.use_binpacking); + }); + + return new Promise((resolve) => { + const timeout = setTimeout(() => { + if (target) { + target.innerHTML = '
Failed to load summary: timeout
'; + } + resolve(); + }, 10000); + + listenOnce("CpuAffinitySummary", async (msg) => { + clearTimeout(timeout); + await configPromise; + const data = msg && msg.data ? msg.data : []; + renderSummary(data); + resolve(); + }); + wsClient.send({ CpuAffinitySummary: {} }); + }); } -async function fetchCircuits() { +function fetchCircuits() { const target = document.getElementById("circuitsTable"); target.innerHTML = ' Loading circuits...'; const dir = state.direction; @@ -254,19 +289,26 @@ async function fetchCircuits() { target.innerHTML = ' Select a CPU from the table above.'; return; } - const params = new URLSearchParams(); - params.set("direction", dir); - params.set("page", String(state.page)); - params.set("page_size", String(state.pageSize)); - // no search param - try { - const r = await fetch(`/local-api/cpuAffinity/circuits/${cpu}?` + params.toString()); - if (!r.ok) throw new Error(`${r.status}`); - const data = await r.json(); - renderCircuits(data); - } catch (e) { - target.innerHTML = `
Failed to load circuits: ${e}
`; - } + const timeout = setTimeout(() => { + target.innerHTML = '
Failed to load circuits: timeout
'; + }, 10000); + listenOnce("CpuAffinityCircuits", (msg) => { + clearTimeout(timeout); + if (!msg || !msg.data) { + target.innerHTML = '
Failed to load circuits.
'; + return; + } + renderCircuits(msg.data); + }); + wsClient.send({ + CpuAffinityCircuits: { + cpu: cpu, + direction: dir, + page: state.page, + page_size: state.pageSize, + search: null, + } + }); } // Wire up controls diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/base_combined_dashlet.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/base_combined_dashlet.js index ec13c8a1..f6e1dd0f 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/base_combined_dashlet.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/base_combined_dashlet.js @@ -16,7 +16,18 @@ export class BaseCombinedDashlet extends BaseDashlet { } subscribeTo() { - return this.subsciptions; + const channels = []; + for (let i = 0; i < this.subsciptions.length; i++) { + const entry = this.subsciptions[i]; + if (Array.isArray(entry)) { + for (let j = 0; j < entry.length; j++) { + channels.push(entry[j]); + } + } else if (entry) { + channels.push(entry); + } + } + return channels; } #base() { @@ -115,4 +126,4 @@ export class BaseCombinedDashlet extends BaseDashlet { d.onMessage(msg); }) } -} \ No newline at end of file +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/ltsLast24Hours.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/ltsLast24Hours.js index 22307002..48a093b7 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/ltsLast24Hours.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/ltsLast24Hours.js @@ -1,5 +1,16 @@ import {BaseDashlet} from "../lq_js_common/dashboard/base_dashlet"; import {LtsLast24Hours_graph} from "../graphs/ltsLast24Hours_graph"; +import {get_ws_client} from "../pubsub/ws"; + +const wsClient = get_ws_client(); +const listenOnceForSeconds = (eventName, seconds, handler) => { + const wrapped = (msg) => { + if (!msg || msg.seconds !== seconds) return; + wsClient.off(eventName, wrapped); + handler(msg); + }; + wsClient.on(eventName, wrapped); +}; export class LtsLast24Hours extends BaseDashlet { constructor(slot) { @@ -37,13 +48,15 @@ export class LtsLast24Hours extends BaseDashlet { onMessage(msg) { if (msg.event === "Cadence") { if (this.count === 0) { - // Test - $.get("/local-api/lts24", (data) => { + const seconds = 24 * 60 * 60; + listenOnceForSeconds("LtsThroughput", seconds, (msg) => { + const data = msg && msg.data ? msg.data : []; this.graph.update(data); }); + wsClient.send({ LtsThroughput: { seconds } }); } this.count++; this.count %= 120; } } -} \ No newline at end of file +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/ltsShaperStatus.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/ltsShaperStatus.js index 22198f82..0f5f8b05 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/ltsShaperStatus.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/ltsShaperStatus.js @@ -1,5 +1,15 @@ import {BaseDashlet} from "../lq_js_common/dashboard/base_dashlet"; import {clearDiv, simpleRow, simpleRowHtml, theading} from "../helpers/builders"; +import {get_ws_client} from "../pubsub/ws"; + +const wsClient = get_ws_client(); +const listenOnce = (eventName, handler) => { + const wrapped = (msg) => { + wsClient.off(eventName, wrapped); + handler(msg); + }; + wsClient.on(eventName, wrapped); +}; export class LtsShaperStatus extends BaseDashlet { constructor(slot) { @@ -42,7 +52,8 @@ export class LtsShaperStatus extends BaseDashlet { onMessage(msg) { if (msg.event === "Cadence") { if (this.count === 0) { - $.get("/local-api/ltsShaperStatus", (data) => { + listenOnce("LtsShaperStatus", (msg) => { + const data = msg && msg.data ? msg.data : []; let target = document.getElementById(this.contentId); let table = document.createElement("table"); @@ -74,9 +85,10 @@ export class LtsShaperStatus extends BaseDashlet { //console.log(data); }); + wsClient.send({ LtsShaperStatus: {} }); } this.count++; this.count %= 10; } } -} \ No newline at end of file +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/queue_stats_total.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/queue_stats_total.js index 9865cffd..1b1d56d5 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/queue_stats_total.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/queue_stats_total.js @@ -2,6 +2,27 @@ import {QueueStatsTotalGraph} from "../graphs/queue_stats_total_graph"; import {LtsCakeGraph} from "../graphs/lts_cake_stats_graph"; import {DashletBaseInsight} from "./insight_dashlet_base"; import {periodNameToSeconds} from "../helpers/time_periods"; +import {get_ws_client} from "../pubsub/ws"; + +const wsClient = get_ws_client(); + +const listenOnceForSeconds = (eventName, seconds, onSuccess, onError) => { + const wrapped = (msg) => { + if (!msg || msg.seconds !== seconds) return; + wsClient.off(eventName, wrapped); + wsClient.off("Error", errorHandler); + onSuccess(msg); + }; + const errorHandler = (msg) => { + wsClient.off(eventName, wrapped); + wsClient.off("Error", errorHandler); + if (onError) { + onError(msg); + } + }; + wsClient.on(eventName, wrapped); + wsClient.on("Error", errorHandler); +}; export class QueueStatsTotalDash extends DashletBaseInsight { constructor(slot) { @@ -90,27 +111,34 @@ export class QueueStatsTotalDash extends DashletBaseInsight { this.historyGraph.chart.showLoading(); } - $.get("/local-api/ltsCake/" + seconds, (data) => { - if (this.historyPeriod !== periodName) { - return; - } - if (this.historyGraph === null) { - this.historyGraph = new LtsCakeGraph(this.historyGraphDivId(), seconds); - } - this.historyGraph.update(data); - if (data.length === 0) { - this.historyGraph.chart.showLoading("No historical data available."); - } else { - this.historyGraph.chart.hideLoading(); - } - }).fail(() => { - if (this.historyPeriod === periodName) { - if (this.historyGraph !== null && this.historyGraph.chart) { - this.historyGraph.chart.showLoading("Failed to load cake stats."); + listenOnceForSeconds( + "LtsCake", + seconds, + (msg) => { + if (this.historyPeriod !== periodName) { + return; + } + const data = msg && msg.data ? msg.data : []; + if (this.historyGraph === null) { + this.historyGraph = new LtsCakeGraph(this.historyGraphDivId(), seconds); + } + this.historyGraph.update(data); + if (data.length === 0) { + this.historyGraph.chart.showLoading("No historical data available."); } else { - historyGraph.innerHTML = "

Failed to load cake stats.

"; + this.historyGraph.chart.hideLoading(); + } + }, + () => { + if (this.historyPeriod === periodName) { + if (this.historyGraph !== null && this.historyGraph.chart) { + this.historyGraph.chart.showLoading("Failed to load cake stats."); + } else { + historyGraph.innerHTML = "

Failed to load cake stats.

"; + } } - } - }); + }, + ); + wsClient.send({ LtsCake: { seconds } }); } } diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/ram_dash.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/ram_dash.js index 57f65fd1..9279d196 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/ram_dash.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/ram_dash.js @@ -1,4 +1,5 @@ import {BaseDashlet} from "../lq_js_common/dashboard/base_dashlet"; +import {toNumber} from "../lq_js_common/helpers/scaling"; import {RamPie} from "../graphs/ram_pie"; export class RamDash extends BaseDashlet{ @@ -35,10 +36,10 @@ export class RamDash extends BaseDashlet{ onMessage(msg) { if (msg.event === "Ram") { - let total = msg.data.total; - let used = msg.data.used; - let free = total - used; + let total = toNumber(msg.data.total, 0); + let used = toNumber(msg.data.used, 0); + let free = Math.max(0, total - used); this.graph.update(free, used); } } -} \ No newline at end of file +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/throughput_bps_dash.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/throughput_bps_dash.js index 73626ba0..3f4953e7 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/throughput_bps_dash.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/throughput_bps_dash.js @@ -1,5 +1,15 @@ import {scaleNumber} from "../lq_js_common/helpers/scaling"; import {DashletBaseInsight} from "./insight_dashlet_base"; +import {get_ws_client} from "../pubsub/ws"; + +const wsClient = get_ws_client(); +const listenOnce = (eventName, handler) => { + const wrapped = (msg) => { + wsClient.off(eventName, wrapped); + handler(msg); + }; + wsClient.on(eventName, wrapped); +}; export class ThroughputBpsDash extends DashletBaseInsight{ title() { @@ -228,7 +238,8 @@ export class ThroughputBpsDash extends DashletBaseInsight{ if (window.hasLts && this.busy === false && (this.medians === null || this.tickCount > 300)) { this.tickCount = 0; this.busy = true; - $.get("/local-api/ltsRecentMedian", (m) => { + listenOnce("LtsRecentMedian", (msg) => { + const m = msg && msg.data ? msg.data : []; if (m === null || m.length === 0) { this.busy = false; return; @@ -239,6 +250,7 @@ export class ThroughputBpsDash extends DashletBaseInsight{ this.medians.last_week[0] = this.medians.last_week[0] * 8; this.medians.last_week[1] = this.medians.last_week[1] * 8; }); + wsClient.send({ LtsRecentMedian: {} }); } this.upRing.push(msg.data.bps.up); @@ -328,4 +340,4 @@ export class ThroughputBpsDash extends DashletBaseInsight{ let percent = (diff / previous) * 100; return [color, icon, percent]; } -} \ No newline at end of file +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/top10_downloaders.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/top10_downloaders.js index 2f37e83f..7f451251 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/top10_downloaders.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/top10_downloaders.js @@ -4,6 +4,17 @@ import {periodNameToSeconds} from "../helpers/time_periods"; import {formatRetransmit, formatRtt} from "../helpers/scaling"; import {scaleNumber} from "../lq_js_common/helpers/scaling"; import {DashletBaseInsight} from "./insight_dashlet_base"; +import {get_ws_client} from "../pubsub/ws"; + +const wsClient = get_ws_client(); +const listenOnceForSeconds = (eventName, seconds, handler) => { + const wrapped = (msg) => { + if (!msg || msg.seconds !== seconds) return; + wsClient.off(eventName, wrapped); + handler(msg); + }; + wsClient.on(eventName, wrapped); +}; export class Top10Downloaders extends DashletBaseInsight { constructor(slot) { @@ -66,7 +77,8 @@ export class Top10Downloaders extends DashletBaseInsight { let target = document.getElementById(this.id); clearDashDiv(this.id, target); target.appendChild(spinnerDiv); - $.get("/local-api/ltsTop10Downloaders/" + seconds, (data) => { + listenOnceForSeconds("LtsTop10Downloaders", seconds, (msg) => { + const data = msg && msg.data ? msg.data : []; let target = document.getElementById(this.id); let table = document.createElement("table"); @@ -101,5 +113,6 @@ export class Top10Downloaders extends DashletBaseInsight { clearDashDiv(this.id, target); target.appendChild(table); }); + wsClient.send({ LtsTop10Downloaders: { seconds } }); } -} \ No newline at end of file +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/top10flows_bytes.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/top10flows_bytes.js index 81c43cf3..dd315fe5 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/top10flows_bytes.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/top10flows_bytes.js @@ -5,6 +5,17 @@ import {formatRetransmit, formatRtt, rttNanosAsSpan} from "../helpers/scaling"; import {TrimToFit} from "../lq_js_common/helpers/text_utils"; import {periodNameToSeconds} from "../helpers/time_periods"; import {DashletBaseInsight} from "./insight_dashlet_base"; +import {get_ws_client} from "../pubsub/ws"; + +const wsClient = get_ws_client(); +const listenOnceForSeconds = (eventName, seconds, handler) => { + const wrapped = (msg) => { + if (!msg || msg.seconds !== seconds) return; + wsClient.off(eventName, wrapped); + handler(msg); + }; + wsClient.on(eventName, wrapped); +}; export class Top10FlowsBytes extends DashletBaseInsight { constructor(slot) { @@ -147,7 +158,8 @@ export class Top10FlowsBytes extends DashletBaseInsight { let target = document.getElementById(this.id); clearDashDiv(this.id, target); target.appendChild(spinnerDiv); - $.get("/local-api/ltsTopFlows/" + seconds, (data) => { + listenOnceForSeconds("LtsTopFlows", seconds, (msg) => { + const data = msg && msg.data ? msg.data : []; let target = document.getElementById(this.id); let table = document.createElement("table"); @@ -203,5 +215,6 @@ export class Top10FlowsBytes extends DashletBaseInsight { clearDashDiv(this.id, target); target.appendChild(table); }); + wsClient.send({ LtsTopFlows: { seconds } }); } -} \ No newline at end of file +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/total_retransmits.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/total_retransmits.js index f6dac524..7b2cf96c 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/total_retransmits.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/total_retransmits.js @@ -72,15 +72,10 @@ export class TcpRetransmitsDash extends DashletBaseInsight{ if (msg.event === "Retransmits") { this.graph.update(msg.data.down, msg.data.up, msg.data.tcp_down, msg.data.tcp_up); if (!this.ltsLoaded && window.hasLts) { - //console.log("Loading LTS data"); this.graphs.forEach((g) => { - //console.log("Loading " + g.period); - let url = "/local-api/ltsRetransmits/" + g.period; - //console.log(url); - $.get(url, (data) => { - //console.log(data); - g.update(data); - }); + if (g && g.chart) { + g.chart.showLoading("Insight retransmit history not available."); + } }); this.ltsLoaded = true; } @@ -96,4 +91,4 @@ export class TcpRetransmitsDash extends DashletBaseInsight{ supportsZoom() { return true; } -} \ No newline at end of file +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/worst10_downloaders.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/worst10_downloaders.js index 45597d40..416478aa 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/worst10_downloaders.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/worst10_downloaders.js @@ -4,6 +4,17 @@ import {periodNameToSeconds} from "../helpers/time_periods"; import {formatRetransmit, formatRtt} from "../helpers/scaling"; import {scaleNumber} from "../lq_js_common/helpers/scaling"; import {DashletBaseInsight} from "./insight_dashlet_base"; +import {get_ws_client} from "../pubsub/ws"; + +const wsClient = get_ws_client(); +const listenOnceForSeconds = (eventName, seconds, handler) => { + const wrapped = (msg) => { + if (!msg || msg.seconds !== seconds) return; + wsClient.off(eventName, wrapped); + handler(msg); + }; + wsClient.on(eventName, wrapped); +}; export class Worst10Downloaders extends DashletBaseInsight { constructor(slot) { @@ -66,7 +77,8 @@ export class Worst10Downloaders extends DashletBaseInsight { let target = document.getElementById(this.id); clearDashDiv(this.id, target); target.appendChild(spinnerDiv); - $.get("/local-api/ltsWorst10Rtt/" + seconds, (data) => { + listenOnceForSeconds("LtsWorst10Rtt", seconds, (msg) => { + const data = msg && msg.data ? msg.data : []; let target = document.getElementById(this.id); let table = document.createElement("table"); @@ -101,5 +113,6 @@ export class Worst10Downloaders extends DashletBaseInsight { clearDashDiv(this.id, target); target.appendChild(table); }); + wsClient.send({ LtsWorst10Rtt: { seconds } }); } -} \ No newline at end of file +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/worst10_retransmits.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/worst10_retransmits.js index 909336e0..1c11ec2c 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/worst10_retransmits.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/worst10_retransmits.js @@ -4,6 +4,17 @@ import {periodNameToSeconds} from "../helpers/time_periods"; import {formatRetransmit, formatRtt} from "../helpers/scaling"; import {scaleNumber} from "../lq_js_common/helpers/scaling"; import {DashletBaseInsight} from "./insight_dashlet_base"; +import {get_ws_client} from "../pubsub/ws"; + +const wsClient = get_ws_client(); +const listenOnceForSeconds = (eventName, seconds, handler) => { + const wrapped = (msg) => { + if (!msg || msg.seconds !== seconds) return; + wsClient.off(eventName, wrapped); + handler(msg); + }; + wsClient.on(eventName, wrapped); +}; export class Worst10Retransmits extends DashletBaseInsight { constructor(slot) { @@ -66,7 +77,8 @@ export class Worst10Retransmits extends DashletBaseInsight { let target = document.getElementById(this.id); clearDashDiv(this.id, target); target.appendChild(spinnerDiv); - $.get("/local-api/ltsWorst10Rxmit/" + seconds, (data) => { + listenOnceForSeconds("LtsWorst10Rxmit", seconds, (msg) => { + const data = msg && msg.data ? msg.data : []; let target = document.getElementById(this.id); let table = document.createElement("table"); @@ -101,5 +113,6 @@ export class Worst10Retransmits extends DashletBaseInsight { clearDashDiv(this.id, target); target.appendChild(table); }); + wsClient.send({ LtsWorst10Rxmit: { seconds } }); } -} \ No newline at end of file +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/executive_utils.js b/src/rust/lqosd/src/node_manager/js_build/src/executive_utils.js index 34a0d1f7..15572647 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/executive_utils.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/executive_utils.js @@ -1,4 +1,13 @@ -import {subscribeWS} from "./pubsub/ws"; +import {get_ws_client, subscribeWS} from "./pubsub/ws"; + +const wsClient = get_ws_client(); +const listenOnce = (eventName, handler) => { + const wrapped = (msg) => { + wsClient.off(eventName, wrapped); + handler(msg); + }; + wsClient.on(eventName, wrapped); +}; export function listenExecutiveHeatmaps(onData) { subscribeWS(["ExecutiveHeatmaps"], (msg) => { @@ -15,7 +24,15 @@ export function getSiteIdMap() { if (siteIdMap) return Promise.resolve(siteIdMap); if (siteIdMapPromise) return siteIdMapPromise; siteIdMapPromise = new Promise((resolve) => { - $.get("/local-api/networkTree", (data) => { + let resolved = false; + const resolveOnce = (map) => { + if (resolved) return; + resolved = true; + siteIdMap = map; + resolve(map); + }; + listenOnce("NetworkTree", (msg) => { + const data = msg && msg.data ? msg.data : []; const map = new Map(); (data || []).forEach((entry) => { if (!Array.isArray(entry) || entry.length < 2) return; @@ -25,12 +42,11 @@ export function getSiteIdMap() { map.set(node.name, id); } }); - siteIdMap = map; - resolve(map); - }).fail(() => { - siteIdMap = new Map(); - resolve(siteIdMap); }); + wsClient.send({ NetworkTree: {} }); + setTimeout(() => { + resolveOnce(new Map()); + }, 5000); }); return siteIdMapPromise; } diff --git a/src/rust/lqosd/src/node_manager/js_build/src/flow_map.js b/src/rust/lqosd/src/node_manager/js_build/src/flow_map.js index 50cff467..c68ec4f0 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/flow_map.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/flow_map.js @@ -1,5 +1,15 @@ import { DashboardGraph } from "./graphs/dashboard_graph"; import {lerpGreenToRedViaOrange} from "./helpers/scaling"; +import {get_ws_client} from "./pubsub/ws"; + +const wsClient = get_ws_client(); +const listenOnce = (eventName, handler) => { + const wrapped = (msg) => { + wsClient.off(eventName, wrapped); + handler(msg); + }; + wsClient.on(eventName, wrapped); +}; class FlowMap extends DashboardGraph { constructor(id) { @@ -66,7 +76,8 @@ class FlowMap extends DashboardGraph { } function updateMap() { - $.get("/local-api/flowMap", (data) => { + listenOnce("FlowMap", (msg) => { + const data = msg && msg.data ? msg.data : []; let output = []; data.forEach((d) => { let rtt = Math.min(200, d[4]); @@ -83,7 +94,8 @@ function updateMap() { // Note that I'm NOT using a channel ticker here because of the amount of data setTimeout(updateMap, 1000); // Keep on ticking! }); + wsClient.send({ FlowMap: {} }); } let map = new FlowMap("flowMap"); -updateMap() \ No newline at end of file +updateMap() diff --git a/src/rust/lqosd/src/node_manager/js_build/src/graphs/flows_graph_timeseries.js b/src/rust/lqosd/src/node_manager/js_build/src/graphs/flows_graph_timeseries.js index d633c953..d0f81286 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/graphs/flows_graph_timeseries.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/graphs/flows_graph_timeseries.js @@ -1,6 +1,18 @@ import {DashboardGraph} from "./dashboard_graph"; import {GraphOptionsBuilder} from "../lq_js_common/e_charts/chart_builder"; import {periodNameToSeconds} from "../helpers/time_periods"; +import {get_ws_client} from "../pubsub/ws"; + +const wsClient = get_ws_client(); + +const listenOnceForSeconds = (eventName, seconds, handler) => { + const wrapped = (msg) => { + if (!msg || msg.seconds !== seconds) return; + wsClient.off(eventName, wrapped); + handler(msg); + }; + wsClient.on(eventName, wrapped); +}; export class FlowCountGraphTimescale extends DashboardGraph { constructor(id, period) { @@ -23,7 +35,8 @@ export class FlowCountGraphTimescale extends DashboardGraph { this.option && this.chart.setOption(this.option); let seconds = periodNameToSeconds(period); - $.get("/local-api/ltsFlows/" + seconds, (data) => { + listenOnceForSeconds("LtsFlows", seconds, (msg) => { + const data = msg && msg.data ? msg.data : []; data.forEach((d) => { this.option.xAxis.data.push(d.time); this.option.series[0].data.push(d.flow_count); @@ -31,5 +44,6 @@ export class FlowCountGraphTimescale extends DashboardGraph { this.chart.setOption(this.option); this.chart.hideLoading(); }); + wsClient.send({ LtsFlows: { seconds } }); } -} \ No newline at end of file +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/graphs/packets_bar_insight.js b/src/rust/lqosd/src/node_manager/js_build/src/graphs/packets_bar_insight.js index 5674f820..3778c0ff 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/graphs/packets_bar_insight.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/graphs/packets_bar_insight.js @@ -1,6 +1,18 @@ import {DashboardGraph} from "./dashboard_graph"; import {scaleNumber} from "../lq_js_common/helpers/scaling"; import {periodNameToSeconds} from "../helpers/time_periods"; +import {get_ws_client} from "../pubsub/ws"; + +const wsClient = get_ws_client(); + +const listenOnceForSeconds = (eventName, seconds, handler) => { + const wrapped = (msg) => { + if (!msg || msg.seconds !== seconds) return; + wsClient.off(eventName, wrapped); + handler(msg); + }; + wsClient.on(eventName, wrapped); +}; export class PacketsPerSecondTimescale extends DashboardGraph { constructor(id, period) { @@ -36,8 +48,8 @@ export class PacketsPerSecondTimescale extends DashboardGraph { let seconds = periodNameToSeconds(period); console.log("Requesting Insight History Data"); - $.get("/local-api/ltsPackets/" + seconds, (data) => { - //console.log(data); + listenOnceForSeconds("LtsPackets", seconds, (msg) => { + const data = msg && msg.data ? msg.data : []; let n = 1; let seriesTcpDown = { @@ -139,7 +151,8 @@ export class PacketsPerSecondTimescale extends DashboardGraph { this.chart.setOption(this.option); this.chart.hideLoading(); - }) + }); + wsClient.send({ LtsPackets: { seconds } }); } update(down, up, tcp, udp, icmp) { @@ -158,4 +171,4 @@ export class PacketsPerSecondTimescale extends DashboardGraph { ]; this.chart.setOption(this.option); } -} \ No newline at end of file +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/graphs/rtt_histo_timeseries.js b/src/rust/lqosd/src/node_manager/js_build/src/graphs/rtt_histo_timeseries.js index 2f147662..5b7bdbbe 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/graphs/rtt_histo_timeseries.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/graphs/rtt_histo_timeseries.js @@ -1,8 +1,19 @@ import {DashboardGraph} from "./dashboard_graph"; import {lerpGreenToRedViaOrange} from "../helpers/scaling"; import {periodNameToSeconds} from "../helpers/time_periods"; +import {get_ws_client} from "../pubsub/ws"; export const N_ITEMS = 50; +const wsClient = get_ws_client(); + +const listenOnceForSeconds = (eventName, seconds, handler) => { + const wrapped = (msg) => { + if (!msg || msg.seconds !== seconds) return; + wsClient.off(eventName, wrapped); + handler(msg); + }; + wsClient.on(eventName, wrapped); +}; export class RttHistogramTimeseries extends DashboardGraph { constructor(id, period) { @@ -41,7 +52,8 @@ export class RttHistogramTimeseries extends DashboardGraph { let seconds = periodNameToSeconds(period); console.log("Requesting Insight History Data (RTT Histo)"); - $.get("/local-api/ltsRttHisto/" + seconds, (rtt) => { + listenOnceForSeconds("LtsRttHisto", seconds, (msg) => { + const rtt = msg && msg.data ? msg.data : []; console.log(rtt); this.option.series.data = []; for (let i=0; i { + const wrapped = (msg) => { + if (!msg || msg.seconds !== seconds) return; + wsClient.off(eventName, wrapped); + handler(msg); + }; + wsClient.on(eventName, wrapped); +}; export class ShapedUnshapedTimescale extends DashboardGraph { constructor(id, period) { @@ -23,7 +35,8 @@ export class ShapedUnshapedTimescale extends DashboardGraph { // Request let seconds = periodNameToSeconds(period); - $.get("/local-api/ltsPercentShaped/" + seconds, (data) => { + listenOnceForSeconds("LtsPercentShaped", seconds, (msg) => { + const data = msg && msg.data ? msg.data : []; console.log(data); // Add data to graph @@ -36,5 +49,6 @@ export class ShapedUnshapedTimescale extends DashboardGraph { this.chart.setOption(this.option); this.chart.hideLoading(); }); + wsClient.send({ LtsPercentShaped: { seconds } }); } } diff --git a/src/rust/lqosd/src/node_manager/js_build/src/graphs/throughput_ring_graph_timescale.js b/src/rust/lqosd/src/node_manager/js_build/src/graphs/throughput_ring_graph_timescale.js index 67bd40a2..d7754a74 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/graphs/throughput_ring_graph_timescale.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/graphs/throughput_ring_graph_timescale.js @@ -2,8 +2,19 @@ import {DashboardGraph} from "./dashboard_graph"; import {GraphOptionsBuilder} from "../lq_js_common/e_charts/chart_builder"; import {periodNameToSeconds} from "../helpers/time_periods"; import {MinMaxSeries} from "../lq_js_common/e_charts/min_max_median_series"; +import {get_ws_client} from "../pubsub/ws"; const RING_SIZE = 60 * 5; // 5 Minutes +const wsClient = get_ws_client(); + +const listenOnceForSeconds = (eventName, seconds, handler) => { + const wrapped = (msg) => { + if (!msg || msg.seconds !== seconds) return; + wsClient.off(eventName, wrapped); + handler(msg); + }; + wsClient.on(eventName, wrapped); +}; export class ThroughputRingBufferGraphTimescale extends DashboardGraph { constructor(id, period) { @@ -20,7 +31,8 @@ export class ThroughputRingBufferGraphTimescale extends DashboardGraph { let seconds = periodNameToSeconds(period); console.log("Requesting Insight History Data"); - $.get("local-api/ltsThroughput/" + seconds, (data) => { + listenOnceForSeconds("LtsThroughput", seconds, (msg) => { + const data = msg && msg.data ? msg.data : []; console.log("Received Insight History Data", data); let shaperDown = new MinMaxSeries("Down", 1); let shaperUp = new MinMaxSeries(" Up", 1); @@ -42,6 +54,7 @@ export class ThroughputRingBufferGraphTimescale extends DashboardGraph { this.chart.setOption(this.option); this.chart.hideLoading(); }); + wsClient.send({ LtsThroughput: { seconds } }); } onThemeChange() { diff --git a/src/rust/lqosd/src/node_manager/js_build/src/help.js b/src/rust/lqosd/src/node_manager/js_build/src/help.js index 786acfd3..c9f4174b 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/help.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/help.js @@ -1,95 +1,4 @@ import {displayDaveMemorial} from "./dave"; -function gather() { - let details = { - name: $("#gatherName").val() + ", " + $("#gatherEmail").val(), - comment: $("#gatherComments").val() - }; - console.log(details); - - if (details.name === ", " || details.name.indexOf("@")<1) { - alert("Please enter a name and email address. If you share this, it'll be handy to know who sent it!"); - return; - } - - $.ajax({ - type: "POST", - url: "/local-api/gatherSupport", - data: JSON.stringify(details), - contentType : 'application/json', - xhrFields: { - responseType: 'blob' // to avoid binary data being mangled on charset conversion - }, - success: function(blob, result, xhr) { - var filename = "libreqos.support"; - - // use HTML5 a[download] attribute to specify filename - var downloadUrl = URL.createObjectURL(blob); - var a = document.createElement("a"); - // safari doesn't support this yet - if (typeof a.download === 'undefined') { - window.location.href = downloadUrl; - } else { - a.href = downloadUrl; - a.download = filename; - document.body.appendChild(a); - a.click(); - } - } - }) -} - -function submit() { - let details = { - name: $("#submitName").val() + ", " + $("#submitEmail").val(), - comment: $("#submitComments").val() - }; - console.log(details); - - if (details.name === ", " || details.name.indexOf("@")<1) { - alert("Please enter a name and email address. If you share this, it'll be handy to know who sent it!"); - return; - } - - $.ajax({ - type: "POST", - url: "/local-api/submitSupport", - data: JSON.stringify(details), - contentType : 'application/json', - success: function(result) { - console.log(result); - alert(result); - } - }) -} - -function sanity() { - $.get("/local-api/sanity", (data) => { - console.log(data); - let html = ""; - for (let i=0; i"; - if (row.success) { - html += ""; - html += ""; - } - html += ""; - $("#configCheck").html(html); - - // Show the modal - const myModal = new bootstrap.Modal(document.getElementById('sanityModal'), { focus: true }); - myModal.show(); - }) -} - // Perform wireups -$("#btnSanity").click(sanity); -$("#btnGather").click(gather); -$("#btnClickSub").click(submit); -$("#btnDave").click(displayDaveMemorial); \ No newline at end of file +$("#btnDave").click(displayDaveMemorial); diff --git a/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/dashboard.js b/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/dashboard.js index f690b567..800f1f2a 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/dashboard.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/dashboard.js @@ -1,6 +1,7 @@ // Provides a generic dashboard system for use in LibreQoS and Insight import {DashboardLayout} from "./layout"; import {resetWS, subscribeWS} from "./ws"; +import {get_ws_client} from "../../pubsub/ws"; import {heading5Icon} from "../helpers/content_builders"; import {openDashboardEditor} from "./dashboard_editor"; @@ -408,6 +409,15 @@ export class Dashboard { c3.classList.add("col-3"); c3.appendChild(heading5Icon("save", "Save Layout")); + const wsClient = get_ws_client(); + const listenOnce = (eventName, handler) => { + const wrapped = (msg) => { + wsClient.off(eventName, wrapped); + handler(msg); + }; + wsClient.on(eventName, wrapped); + }; + let saveGroup = document.createElement("div"); saveGroup.classList.add("input-group"); let saveAppend = document.createElement("div"); @@ -427,20 +437,20 @@ export class Dashboard { saveBtn.onclick = () => { let name = $("#saveDashName").val(); if (name.length < 1) return; - let request = { - name: name, - entries: this.dashletIdentities - } - $.ajax({ - type: "POST", - url: "/local-api/dashletSave", - data: JSON.stringify(request), - contentType : 'application/json', - success: () => { - localStorage.setItem("forceEditMode", "true"); - window.location.reload(); + listenOnce("DashletSaveResult", (msg) => { + if (!msg || !msg.ok) { + alert(msg && msg.error ? msg.error : "Failed to save dashboard layout"); + return; } - }) + localStorage.setItem("forceEditMode", "true"); + window.location.reload(); + }); + wsClient.send({ + DashletSave: { + name: name, + entries: this.dashletIdentities + } + }); } saveGroup.appendChild(saveDashName); saveAppend.appendChild(saveBtn); @@ -450,7 +460,7 @@ export class Dashboard { let c4 = document.createElement("div"); c4.classList.add("col-3"); c4.appendChild(heading5Icon("save", "Saved Layouts")); - $.get(this.savedDashUrl, (data) => { + listenOnce("DashletThemes", (data) => { let list = document.createElement("ul"); list.classList.add("list-group", "list-group-numbered"); data.entries.forEach((d) => { @@ -462,19 +472,17 @@ export class Dashboard { ln.onclick = () => { let resp = confirm("Load [" + d.name + "] from [" + d.path + "]?"); if (resp) { - $.ajax({ - type: "POST", - url: "/local-api/dashletGet", - data: JSON.stringify({name: d.name}), - contentType : 'application/json', - success: (x) => { - console.log(x); - this.dashletIdentities = x.entries; - this.layout.save(this.dashletIdentities); - localStorage.setItem("forceEditMode", "true"); - window.location.reload(); + listenOnce("DashletTheme", (x) => { + if (!x || !x.entries) { + alert("Failed to load dashboard layout"); + return; } + this.dashletIdentities = x.entries; + this.layout.save(this.dashletIdentities); + localStorage.setItem("forceEditMode", "true"); + window.location.reload(); }); + wsClient.send({ DashletGet: { name: d.name } }); } }; let dl = document.createElement("a"); @@ -485,16 +493,15 @@ export class Dashboard { dl.onclick = () => { let resp = confirm("Delete [" + d.name + "] from [" + d.path + "]?"); if (resp) { - $.ajax({ - type: "POST", - url: "/local-api/dashletDelete", - data: JSON.stringify({name: d.name}), - contentType : 'application/json', - success: () => { - localStorage.setItem("forceEditMode", "true"); - window.location.reload(); + listenOnce("DashletDeleteResult", (msg) => { + if (!msg || !msg.ok) { + alert(msg && msg.error ? msg.error : "Failed to delete dashboard layout"); + return; } + localStorage.setItem("forceEditMode", "true"); + window.location.reload(); }); + wsClient.send({ DashletDelete: { name: d.name } }); } } i.appendChild(ln); @@ -503,6 +510,7 @@ export class Dashboard { }); c4.appendChild(list); }); + wsClient.send({ DashletThemes: {} }); row.appendChild(c1); row.appendChild(c2); diff --git a/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/ws.js b/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/ws.js index 02ef9010..b493a677 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/ws.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/ws.js @@ -1,33 +1,17 @@ -// Setup any WS feeds for this page -import { ws_proto } from '../../pubsub/ws.js'; -let ws = null; +import { get_ws_client, resetWS as reset_shared } from "../../pubsub/ws"; export function subscribeWS(channels, handler) { - if (channels.length === 0) { + if (!channels || channels.length === 0) { return; } - if (ws) { - ws.close(); + const client = get_ws_client(); + client.on("join", handler); + for (let i = 0; i < channels.length; i++) { + client.on(channels[i], handler); } - - ws = new WebSocket(ws_proto() + window.location.host + '/websocket/ws'); - ws.onopen = () => { - for (let i=0; i { - ws = null; - } - ws.onerror = (error) => { - ws = null - } - ws.onmessage = function (event) { - let msg = JSON.parse(event.data); - handler(msg); - }; + client.subscribe(channels); } export function resetWS() { - ws = null; + reset_shared(); } diff --git a/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/helpers/scaling.js b/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/helpers/scaling.js index b7a0a9fd..5ff448f9 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/helpers/scaling.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/helpers/scaling.js @@ -12,6 +12,21 @@ export function trimTrailingZeros(str) { } } +export function toNumber(value, fallback = 0) { + if (value === null || value === undefined) { + return fallback; + } + if (typeof value === "bigint") { + const num = Number(value); + return Number.isFinite(num) ? num : fallback; + } + if (typeof value === "number") { + return Number.isFinite(value) ? value : fallback; + } + const num = Number(value); + return Number.isFinite(num) ? num : fallback; +} + // Scale a number to T/G/M/K, with a fixed number of decimal places. export function scaleNumber(n, fixed=2) { @@ -41,4 +56,4 @@ export function scaleNanos(n, precision=2) { return trimTrailingZeros((n / 1000).toFixed(precision)) + "µs"; } return n + "ns"; -} \ No newline at end of file +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/lts_trial.js b/src/rust/lqosd/src/node_manager/js_build/src/lts_trial.js index e47bc6df..51abdb4c 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/lts_trial.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/lts_trial.js @@ -1,4 +1,37 @@ import {PLACEHOLDER_TEASERS} from "./lts_teasers_shared"; +import {get_ws_client} from "./pubsub/ws"; + +const wsClient = get_ws_client(); +const listenOnce = (eventName, handler) => { + const wrapped = (msg) => { + wsClient.off(eventName, wrapped); + handler(msg); + }; + wsClient.on(eventName, wrapped); +}; + +function sendWsRequest(responseEvent, request) { + return new Promise((resolve, reject) => { + let done = false; + const onResponse = (msg) => { + if (done) return; + done = true; + wsClient.off(responseEvent, onResponse); + wsClient.off("Error", onError); + resolve(msg); + }; + const onError = (msg) => { + if (done) return; + done = true; + wsClient.off(responseEvent, onResponse); + wsClient.off("Error", onError); + reject(msg); + }; + wsClient.on(responseEvent, onResponse); + wsClient.on("Error", onError); + wsClient.send(request); + }); +} // Paddle-compatible countries (excluding embargoed nations) const ALLOWED_COUNTRIES = [ @@ -433,12 +466,13 @@ function getLtsUrl(endpoint) { // Fetch node ID and LTS URL from configuration async function fetchNodeId() { try { - const response = await $.get('/local-api/getConfig'); - nodeId = response.node_id || null; + const response = await sendWsRequest("LtsTrialConfigResult", { LtsTrialConfig: {} }); + const data = response && response.data ? response.data : {}; + nodeId = data.node_id || null; // Extract LTS URL from config, defaulting to the standard URL - if (response.long_term_stats && response.long_term_stats.lts_url) { - ltsBaseUrl = response.long_term_stats.lts_url; + if (data.lts_url) { + ltsBaseUrl = data.lts_url; // Ensure the URL ends with a slash if (!ltsBaseUrl.endsWith('/')) { ltsBaseUrl += '/'; @@ -453,9 +487,10 @@ async function fetchNodeId() { // Fetch circuit count async function fetchCircuitCount() { try { - const response = await $.get('/local-api/circuits/count'); - const count = response.count || 0; - const configuredCount = response.configured_count || 0; + const response = await sendWsRequest("CircuitCountResult", { CircuitCount: {} }); + const data = response && response.data ? response.data : {}; + const count = data.count || 0; + const configuredCount = data.configured_count || 0; // Always show circuit count if we have any circuits (active or configured) if (count > 0 || configuredCount > 0) { @@ -584,14 +619,7 @@ function attachEventHandlers() { `); $('#configStatus').text('Saving configuration...'); - $.ajax({ - type: "POST", - url: "/local-api/ltsSignUp", - data: JSON.stringify({ - license_key: licenseKey, - }), - contentType: 'application/json', - }); + wsClient.send({ LtsSignUp: { license_key: licenseKey } }); // Show success message now, then swap spinner to a check and enable dashboard after 5s $('#configStatus').html(`License validated! Your configuration has been updated - data will start going to Insight shortly.`); setTimeout(() => { @@ -697,14 +725,7 @@ function attachEventHandlers() { `); $('#configStatus').text('Saving configuration...'); - $.ajax({ - type: "POST", - url: "/local-api/ltsSignUp", - data: JSON.stringify({ - license_key: response.licenseKey, - }), - contentType: 'application/json', - }); + wsClient.send({ LtsSignUp: { license_key: response.licenseKey } }); // Show success message now, then swap spinner to a check and enable dashboard after 5s $('#configStatus').html(`Account created! Your configuration has been updated - data will start going to Insight shortly.`); setTimeout(() => { diff --git a/src/rust/lqosd/src/node_manager/js_build/src/pubsub/direct_channels.js b/src/rust/lqosd/src/node_manager/js_build/src/pubsub/direct_channels.js index 707f38ae..ee1705d8 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/pubsub/direct_channels.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/pubsub/direct_channels.js @@ -1,22 +1,21 @@ -import {ws_proto} from './ws.js'; +import { get_ws_client } from "./ws"; export class DirectChannel { constructor(subObject, handler) { - this.ws = null; + this.client = get_ws_client(); this.handler = handler; - this.ws = new WebSocket(ws_proto() + window.location.host + '/websocket/private_ws'); - this.ws.onopen = () => { - this.ws.send(JSON.stringify(subObject)); - } - this.ws.onclose = () => { - this.ws = null; - } - this.ws.onerror = (error) => { - this.ws = null - } - this.ws.onmessage = function (event) { - let msg = JSON.parse(event.data); + this.event_name = Object.keys(subObject)[0]; + this.bound_handler = (msg) => { handler(msg); }; + this.client.on(this.event_name, this.bound_handler); + this.client.send({ Private: subObject }); + } + + close() { + if (!this.client || !this.bound_handler) { + return; + } + this.client.off(this.event_name, this.bound_handler); } -} \ No newline at end of file +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/pubsub/ws.js b/src/rust/lqosd/src/node_manager/js_build/src/pubsub/ws.js index 0b101d1e..c2a2b486 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/pubsub/ws.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/pubsub/ws.js @@ -1,37 +1,211 @@ -// Setup any WS feeds for this page -let ws = null; +import { Encoder, decode } from "../lq_js_common/helpers/cbor-x"; + +const ACK_TEXT = "I accept that this is an unstable, internal API and is unsupported"; +const EXPECTED_UI_VERSION = (window.LQOS_UI_VERSION || "").trim() || null; +const USER_TOKEN_COOKIE = "User-Token"; +const encoder = new Encoder({ useRecords: false, variableMapSize: true }); + +let shared_client = null; + +function get_cookie_value(name) { + const cookies = document.cookie ? document.cookie.split(";") : []; + const prefix = `${name}=`; + for (let i = 0; i < cookies.length; i++) { + const entry = cookies[i].trim(); + if (entry.startsWith(prefix)) { + return decodeURIComponent(entry.slice(prefix.length)); + } + } + return ""; +} + +function get_user_token() { + return get_cookie_value(USER_TOKEN_COOKIE); +} export function ws_proto() { - if (window.location.protocol.startsWith('https')) { + if (window.location.protocol.startsWith("https")) { return "wss://"; - } else { - return "ws://"; } + return "ws://"; } -export function subscribeWS(channels, handler) { - if (ws) { - ws.close(); +export class WsClient { + constructor() { + this.ws = null; + this.handlers = new Map(); + this.pending = []; + this.handshake_done = false; + } + + connect() { + if (this.ws) { + return; + } + this.ws = new WebSocket(ws_proto() + window.location.host + "/websocket/ws"); + this.ws.binaryType = "arraybuffer"; + + this.ws.onmessage = async (event) => { + let msg = null; + try { + if (event.data instanceof ArrayBuffer) { + msg = decode(new Uint8Array(event.data)); + } else if (event.data && typeof event.data.arrayBuffer === "function") { + const buf = await event.data.arrayBuffer(); + msg = decode(new Uint8Array(buf)); + } + } catch (err) { + console.error("Failed to decode websocket message", err); + return; + } + + if (msg && msg.event === "Hello") { + this._acknowledge_handshake(msg); + return; + } + this._dispatch(msg); + }; + + this.ws.onclose = () => { + this.ws = null; + this.handshake_done = false; + this.pending = []; + }; + + this.ws.onerror = () => { + this.ws = null; + this.handshake_done = false; + }; } - ws = new WebSocket(ws_proto() + window.location.host + '/websocket/ws'); - ws.onopen = () => { - for (let i=0; i { - ws = null; + + subscribe(channels) { + for (let i = 0; i < channels.length; i++) { + this.send({ Subscribe: { channel: channels[i] } }); + } } - ws.onerror = (error) => { - ws = null + + send(request_obj) { + const normalized = normalizeRequest(request_obj); + if (!this.ws) { + this.connect(); + } + if (!this.handshake_done) { + this.pending.push(normalized); + return; + } + this.ws.send(encoder.encode(normalized)); + } + + on(event_name, handler) { + const list = this.handlers.get(event_name) || []; + list.push(handler); + this.handlers.set(event_name, list); + } + + off(event_name, handler) { + const list = this.handlers.get(event_name); + if (!list) { + return; + } + this.handlers.set( + event_name, + list.filter((h) => h !== handler), + ); + } + + _acknowledge_handshake(hello) { + if (this.handshake_done) { + return; + } + if (!EXPECTED_UI_VERSION || hello.version !== EXPECTED_UI_VERSION) { + console.error( + "Websocket version mismatch:", + hello ? hello.version : "missing", + ); + this.close(); + return; + } + this.handshake_done = true; + this.ws.send( + encoder.encode({ + HelloReply: { + ack: ACK_TEXT, + token: get_user_token(), + }, + }), + ); + for (let i = 0; i < this.pending.length; i++) { + this.ws.send(encoder.encode(this.pending[i])); + } + this.pending = []; + } + + _dispatch(msg) { + if (!msg || !msg.event) { + return; + } + const list = this.handlers.get(msg.event); + if (!list) { + return; + } + for (let i = 0; i < list.length; i++) { + list[i](msg); + } } - ws.onmessage = function (event) { - let msg = JSON.parse(event.data); - handler(msg); - }; +} + +function normalizeRequest(request_obj) { + if (!request_obj || typeof request_obj !== "object") { + return request_obj; + } + const keys = Object.keys(request_obj); + if (keys.length !== 1) { + return request_obj; + } + const key = keys[0]; + const value = request_obj[key]; + if ( + value && + typeof value === "object" && + !Array.isArray(value) && + Object.keys(value).length === 0 + ) { + return { [key]: null }; + } + return request_obj; +} + +export function get_ws_client() { + if (!shared_client) { + shared_client = new WsClient(); + } + return shared_client; +} + +export function subscribeWS(channels, handler) { + if (!channels || channels.length === 0) { + return; + } + const client = get_ws_client(); + client.on("join", handler); + for (let i = 0; i < channels.length; i++) { + client.on(channels[i], handler); + } + client.subscribe(channels); } export function resetWS() { - ws = null; -} \ No newline at end of file + if (shared_client) { + shared_client.close(); + } + shared_client = null; +} diff --git a/src/rust/lqosd/src/node_manager/js_build/src/shaped-devices.js b/src/rust/lqosd/src/node_manager/js_build/src/shaped-devices.js index 3aad312e..cc9412b8 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/shaped-devices.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/shaped-devices.js @@ -1,5 +1,5 @@ import {clearDiv, clientTableHeader, formatLastSeen, simpleRow} from "./helpers/builders"; -import {subscribeWS} from "./pubsub/ws"; +import {get_ws_client, subscribeWS} from "./pubsub/ws"; import {formatRetransmit, formatRtt, formatThroughput} from "./helpers/scaling"; let shapedDevices = null; @@ -7,6 +7,14 @@ let displayDevices = null; let devicesPerPage = 10; let page = 0; let searchTerm = ""; +const wsClient = get_ws_client(); +const listenOnce = (eventName, handler) => { + const wrapped = (msg) => { + wsClient.off(eventName, wrapped); + handler(msg); + }; + wsClient.on(eventName, wrapped); +}; function tableRow(device) { let tr = document.createElement("tr"); @@ -253,14 +261,15 @@ function countCircuits() { } function loadDevices() { - $.get("/local-api/devicesAll", (data) => { - //console.log(data); + listenOnce("DevicesAll", (msg) => { + const data = msg && msg.data ? msg.data : []; shapedDevices = data; displayDevices = data; renderTable(); $("#count").text(shapedDevices.length + " devices"); $("#countCircuit").text(countCircuits() + " circuits"); - }) + }); + wsClient.send({ DevicesAll: {} }); } loadDevices(); diff --git a/src/rust/lqosd/src/node_manager/js_build/src/template.js b/src/rust/lqosd/src/node_manager/js_build/src/template.js index 71997d0b..cdf2904d 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/template.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/template.js @@ -2,6 +2,16 @@ import {clearDiv} from "./helpers/builders"; import {initRedact} from "./helpers/redact"; import {initDayNightMode} from "./helpers/dark_mode"; import {initColorBlind} from "./helpers/colorblind"; +import {get_ws_client} from "./pubsub/ws"; + +const wsClient = get_ws_client(); +const listenOnce = (eventName, handler) => { + const wrapped = (msg) => { + wsClient.off(eventName, wrapped); + handler(msg); + }; + wsClient.on(eventName, wrapped); +}; function escapeAttr(text) { if (text === undefined || text === null) return ""; @@ -16,7 +26,9 @@ function escapeAttr(text) { function loadSchedulerStatus() { const container = document.getElementById('schedulerStatus'); if (!container) return; - $.get('/local-api/scheduler/status', (data) => { + listenOnce("SchedulerStatus", (msg) => { + if (!msg || !msg.data) return; + const data = msg.data; const color = data.available ? 'text-success' : 'text-danger'; const icon = data.available ? 'fa-check-circle' : 'fa-times-circle'; container.innerHTML = ` @@ -30,6 +42,7 @@ function loadSchedulerStatus() { openSchedulerModal(); }); }); + wsClient.send({ SchedulerStatus: {} }); } function openSchedulerModal() { @@ -38,20 +51,23 @@ function openSchedulerModal() { const myModal = new bootstrap.Modal(modalEl, { focus: true }); myModal.show(); $("#schedulerDetailsBody").html(" Loading scheduler status..."); - $.ajax({ - url: '/local-api/scheduler/details', - method: 'GET', - success: (text) => { $("#schedulerDetailsBody").text(text); }, - error: () => { $("#schedulerDetailsBody").text('Failed to load scheduler details'); } + listenOnce("SchedulerDetails", (msg) => { + if (!msg || !msg.data) { + $("#schedulerDetailsBody").text('Failed to load scheduler details'); + return; + } + $("#schedulerDetailsBody").text(msg.data.details); }); + wsClient.send({ SchedulerDetails: {} }); } function getDeviceCounts() { - $.get("/local-api/deviceCount", (data) => { - //console.log(data); - $("#shapedDeviceCount").text(data.shaped_devices); - $("#unknownIpCount").text(data.unknown_ips); - }) + listenOnce("DeviceCount", (msg) => { + if (!msg || !msg.data) return; + $("#shapedDeviceCount").text(msg.data.shaped_devices); + $("#unknownIpCount").text(msg.data.unknown_ips); + }); + wsClient.send({ DeviceCount: {} }); } function initLogout() { @@ -69,57 +85,66 @@ function initLogout() { }); } +let lastSearchTerm = ""; +let searchHandlerReady = false; + +function renderSearchResults(data) { + let searchResults = document.getElementById("searchResults"); + // Position panel near the search input for consistent placement + const inp = document.getElementById("txtSearch"); + if (inp && searchResults) { + const rect = inp.getBoundingClientRect(); + // Use fixed positioning relative to viewport + searchResults.style.position = 'fixed'; + searchResults.style.top = (rect.bottom + 8) + 'px'; + searchResults.style.left = rect.left + 'px'; + const widthPx = Math.max(320, rect.width + 200); + searchResults.style.minWidth = widthPx + 'px'; + searchResults.style.width = widthPx + 'px'; + // Ensure it's not shifted or hidden by existing CSS + searchResults.style.transform = 'none'; + searchResults.style.zIndex = '2000'; + searchResults.style.padding = '6px'; + } + searchResults.style.visibility = "visible"; + let list = document.createElement("table"); + list.classList.add("table", "table-striped"); + let tbody = document.createElement("tbody"); + data.forEach((item) => { + let r = document.createElement("tr"); + let c = document.createElement("td"); + + if (item.Circuit !== undefined) { + c.innerHTML = " " + item.Circuit.name + ""; + } else if (item.Device !== undefined) { + c.innerHTML = " " + item.Device.name + ""; + } else if (item.Site !== undefined) { + c.innerHTML = " " + item.Site.name + ""; + } else { + console.log(item); + c.innerText = item; + } + r.appendChild(c); + tbody.appendChild(r); + }); + clearDiv(searchResults); + list.appendChild(tbody); + searchResults.appendChild(list); +} + function doSearch(search) { if (search.length > 2) { - $.ajax({ - type: "POST", - url: "/local-api/search", - data: JSON.stringify({term: search}), - contentType: 'application/json', - success: (data) => { - let searchResults = document.getElementById("searchResults"); - // Position panel near the search input for consistent placement - const inp = document.getElementById("txtSearch"); - if (inp && searchResults) { - const rect = inp.getBoundingClientRect(); - // Use fixed positioning relative to viewport - searchResults.style.position = 'fixed'; - searchResults.style.top = (rect.bottom + 8) + 'px'; - searchResults.style.left = rect.left + 'px'; - const widthPx = Math.max(320, rect.width + 200); - searchResults.style.minWidth = widthPx + 'px'; - searchResults.style.width = widthPx + 'px'; - // Ensure it's not shifted or hidden by existing CSS - searchResults.style.transform = 'none'; - searchResults.style.zIndex = '2000'; - searchResults.style.padding = '6px'; + lastSearchTerm = search; + if (!searchHandlerReady) { + wsClient.on("SearchResults", (msg) => { + if (!msg || msg.term !== lastSearchTerm) { + return; } - searchResults.style.visibility = "visible"; - let list = document.createElement("table"); - list.classList.add("table", "table-striped"); - let tbody = document.createElement("tbody"); - data.forEach((item) => { - let r = document.createElement("tr"); - let c = document.createElement("td"); - - if (item.Circuit !== undefined) { - c.innerHTML = " " + item.Circuit.name + ""; - } else if (item.Device !== undefined) { - c.innerHTML = " " + item.Device.name + ""; - } else if (item.Site !== undefined) { - c.innerHTML = " " + item.Site.name + ""; - } else { - console.log(item); - c.innerText = item; - } - r.appendChild(c); - tbody.appendChild(r); - }); - clearDiv(searchResults); - list.appendChild(tbody); - searchResults.appendChild(list); - }, - }) + renderSearchResults(msg.results || []); + }); + searchHandlerReady = true; + } + wsClient.send({ Search: { term: search } }); } else { // Close the search panel let searchResults = document.getElementById("searchResults"); @@ -214,9 +239,14 @@ function setupReload() { const myModal = new bootstrap.Modal(document.getElementById('reloadModal'), { focus: true }); myModal.show(); $("#reloadLibreResult").html(" Reloading LibreQoS..."); - $.get("/local-api/reloadLqos", (result) => { - $("#reloadLibreResult").text(result); + listenOnce("ReloadResult", (msg) => { + if (!msg) { + $("#reloadLibreResult").text("Failed to reload LibreQoS"); + return; + } + $("#reloadLibreResult").text(msg.message || ""); }); + wsClient.send({ ReloadLibreQoS: {} }); } } @@ -263,6 +293,113 @@ function setupDynamicUrls() { } } +function initUrgentIssues() { + const containerId = 'urgentStatus'; + const linkId = 'urgentStatusLink'; + const badgeId = 'urgentBadge'; + + function ensurePlaceholder() { + return document.getElementById(containerId) !== null; + } + + function renderStatus(count) { + const cont = document.getElementById(containerId); + if (!cont) return; + const cls = count > 0 ? 'text-danger' : 'text-secondary'; + const icon = count > 0 ? 'fa-bell' : 'fa-bell-slash'; + cont.innerHTML = ` + + Urgent Issues + ${count} + `; + $("#" + containerId).off("click").on("click", `#${linkId}`, (e) => { + e.preventDefault(); + showModal(); + }); + } + + function poll() { + if (!ensurePlaceholder()) return; + listenOnce("UrgentStatus", (msg) => { + const count = msg && msg.data ? msg.data.count : 0; + renderStatus(count || 0); + }); + wsClient.send({ UrgentStatus: {} }); + } + + function showModal() { + const modalEl = document.getElementById('urgentModal'); + if (!modalEl) return; + new bootstrap.Modal(modalEl, { focus: true }).show(); + const holder = document.getElementById('urgentListContainer'); + if (!holder) return; + holder.innerHTML = `
Loading...
`; + listenOnce("UrgentList", (msg) => { + const items = msg && msg.data ? msg.data.items || [] : []; + if (items.length === 0) { + holder.innerHTML = '
No urgent issues.
'; + return; + } + const table = document.createElement('table'); + table.className = 'table table-sm table-striped'; + const tbody = document.createElement('tbody'); + items.forEach((it) => { + const tr = document.createElement('tr'); + const td = document.createElement('td'); + const when = new Date(it.ts * 1000).toLocaleString(); + const sev = it.severity === 'Error' ? 'danger' : 'warning'; + td.innerHTML = ` +
+ ${it.severity} + ${it.code} + (${it.source}) + ${when} + +
+
${it.message}
+ ${it.context ? `
${it.context}
` : ''} + `; + tr.appendChild(td); + tbody.appendChild(tr); + }); + table.appendChild(tbody); + holder.innerHTML = ''; + holder.appendChild(table); + $(holder).off('click').on('click', 'a.urgent-clear', function (e) { + e.preventDefault(); + const id = $(this).data('id'); + listenOnce("UrgentClearResult", () => { + showModal(); + poll(); + }); + wsClient.send({ UrgentClear: { id } }); + }); + }); + wsClient.send({ UrgentList: {} }); + } + + if (!document.getElementById(containerId)) { + const ul = document.querySelector('.sidebar .navbar-nav'); + if (ul) { + const li = document.createElement('li'); + li.className = 'nav-item'; + li.id = containerId; + ul.appendChild(li); + } + } + + $(document).off('click', '#urgentClearAll').on('click', '#urgentClearAll', () => { + listenOnce("UrgentClearAllResult", () => { + showModal(); + poll(); + }); + wsClient.send({ UrgentClearAll: {} }); + }); + + poll(); + setInterval(poll, 30000); +} + function initSchedulerTooltips() { // Initialize Bootstrap tooltips for scheduler status elements const schedulerElements = document.querySelectorAll('[data-bs-toggle="tooltip"]'); @@ -279,5 +416,6 @@ getDeviceCounts(); setupSearch(); setupReload(); setupDynamicUrls(); +window.lqosInitUrgentIssues = initUrgentIssues; initSchedulerTooltips(); loadSchedulerStatus(); diff --git a/src/rust/lqosd/src/node_manager/js_build/src/toasts/global_warnings.js b/src/rust/lqosd/src/node_manager/js_build/src/toasts/global_warnings.js index ffac8c17..145609b1 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/toasts/global_warnings.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/toasts/global_warnings.js @@ -1,11 +1,44 @@ import {createBootstrapToast} from "../lq_js_common/helpers/toasts"; import {PLACEHOLDER_TEASERS} from "../lts_teasers_shared"; +import {get_ws_client} from "../pubsub/ws"; let insightModalShown = false; let modalTeasers = []; let modalTeasersLoaded = false; let modalLtsBaseUrl = "https://insight.libreqos.com/"; +const wsClient = get_ws_client(); + +const listenOnce = (eventName, handler) => { + const wrapped = (msg) => { + wsClient.off(eventName, wrapped); + handler(msg); + }; + wsClient.on(eventName, wrapped); +}; + +function sendWsRequest(responseEvent, request) { + return new Promise((resolve, reject) => { + let done = false; + const onResponse = (msg) => { + if (done) return; + done = true; + wsClient.off(responseEvent, onResponse); + wsClient.off("Error", onError); + resolve(msg); + }; + const onError = (msg) => { + if (done) return; + done = true; + wsClient.off(responseEvent, onResponse); + wsClient.off("Error", onError); + reject(msg); + }; + wsClient.on(responseEvent, onResponse); + wsClient.on("Error", onError); + wsClient.send(request); + }); +} function getModalLtsUrl(endpoint) { let baseUrl = modalLtsBaseUrl; @@ -25,14 +58,10 @@ async function loadModalTeasers() { } try { - // Try to respect configured LTS URL if available - const config = await $.get("/local-api/getConfig"); - if ( - config.long_term_stats && - config.long_term_stats.lts_url && - typeof config.long_term_stats.lts_url === "string" - ) { - modalLtsBaseUrl = config.long_term_stats.lts_url; + const response = await sendWsRequest("LtsTrialConfigResult", { LtsTrialConfig: {} }); + const data = response && response.data ? response.data : {}; + if (data.lts_url && typeof data.lts_url === "string") { + modalLtsBaseUrl = data.lts_url; } } catch (e) { // If this fails, we just fall back to the default base URL. @@ -170,7 +199,9 @@ export function globalWarningToasts() { if (window.sm) { showInsightTrialModal(); } - $.get("/local-api/globalWarnings", (warnings) => { + const handler = (msg) => { + wsClient.off("GlobalWarnings", handler); + const warnings = msg && msg.data ? msg.data : []; let parent = document.getElementById("toasts"); let i = 0; warnings.forEach(warning => { @@ -205,5 +236,7 @@ export function globalWarningToasts() { createBootstrapToast("global-warning-" + i, headerSpan, bodyDiv); i++; }); - }) + }; + wsClient.on("GlobalWarnings", handler); + wsClient.send({ GlobalWarnings: {} }); } diff --git a/src/rust/lqosd/src/node_manager/js_build/src/toasts/sponsor_us.js b/src/rust/lqosd/src/node_manager/js_build/src/toasts/sponsor_us.js index 71864505..a7a8d877 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/toasts/sponsor_us.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/toasts/sponsor_us.js @@ -1,9 +1,11 @@ +import { get_ws_client } from "../pubsub/ws"; + const sponsorBtn = " Sponsor Us on GitHub"; export function sponsorTag(parentId) { if (!window.hasLts) { - $.get("/local-api/deviceCount", (counts) => { - //console.log(data); + const client = get_ws_client(); + const handler = () => { if (!window.hasLts) { let div = document.createElement("div"); let random = Math.floor(Math.random() * 5) + 1; @@ -27,6 +29,9 @@ export function sponsorTag(parentId) { let parent = document.getElementById(parentId); parent.appendChild(div); } - }); + client.off("DeviceCount", handler); + }; + client.on("DeviceCount", handler); + client.send({ DeviceCount: {} }); } } diff --git a/src/rust/lqosd/src/node_manager/js_build/src/tree.js b/src/rust/lqosd/src/node_manager/js_build/src/tree.js index 5ed4ae2d..123ba8e6 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/tree.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/tree.js @@ -6,7 +6,7 @@ import { formatThroughput, } from "./helpers/scaling"; import {scaleNumber} from "./lq_js_common/helpers/scaling"; -import {subscribeWS} from "./pubsub/ws"; +import {get_ws_client, subscribeWS} from "./pubsub/ws"; var tree = null; var parent = 0; @@ -14,6 +14,14 @@ var upParent = 0; var subscribed = false; var expandedNodes = new Set(); var childrenByParentId = new Map(); +const wsClient = get_ws_client(); +const listenOnce = (eventName, handler) => { + const wrapped = (msg) => { + wsClient.off(eventName, wrapped); + handler(msg); + }; + wsClient.on(eventName, wrapped); +}; function buildChildrenMap() { childrenByParentId = new Map(); @@ -94,8 +102,8 @@ function renderTree() { // This runs first and builds the initial structure on the page function getInitialTree() { - $.get("/local-api/networkTree", (data) => { - //console.log(data); + listenOnce("NetworkTree", (msg) => { + const data = msg && msg.data ? msg.data : []; tree = data; buildChildrenMap(); if (tree[parent] !== undefined) { @@ -108,6 +116,7 @@ function getInitialTree() { subscribed = true; } }); + wsClient.send({ NetworkTree: {} }); } function fillHeader(node) { diff --git a/src/rust/lqosd/src/node_manager/js_build/src/unknown-ips.js b/src/rust/lqosd/src/node_manager/js_build/src/unknown-ips.js index d6d4565e..a2a214a0 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/unknown-ips.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/unknown-ips.js @@ -1,55 +1,89 @@ import {clearDiv, formatLastSeen, simpleRow, theading} from "./helpers/builders"; import {scaleNumber} from "./lq_js_common/helpers/scaling"; +import {get_ws_client} from "./pubsub/ws"; -let button = document.getElementById("btnCsv"); -button.onclick = () => { - window.location.href = "/local-api/unknownIpsCsv"; +const wsClient = get_ws_client(); +const listenOnce = (eventName, handler) => { + const wrapped = (msg) => { + wsClient.off(eventName, wrapped); + handler(msg); + }; + wsClient.on(eventName, wrapped); }; -let clearButton = document.getElementById("btnClear"); -if (clearButton) { - clearButton.onclick = async () => { - try { - await fetch("/local-api/unknownIps/clear", { method: "POST" }); - } catch (e) { - console.error("Failed to clear unknown IPs", e); - } finally { - // Reload to refresh the list - window.location.reload(); +function downloadCsv() { + listenOnce("UnknownIpsCsv", (msg) => { + const csv = msg && msg.csv ? msg.csv : ""; + if (!csv) { + console.warn("Empty unknown IP CSV payload"); + return; } - }; + const blob = new Blob([csv], { type: "text/csv;charset=utf-8" }); + const url = URL.createObjectURL(blob); + const link = document.createElement("a"); + link.href = url; + link.download = "unknown_ips.csv"; + document.body.appendChild(link); + link.click(); + link.remove(); + URL.revokeObjectURL(url); + }); + wsClient.send({ UnknownIpsCsv: {} }); } -$.get("/local-api/unknownIps", (data) => { - let target = document.getElementById("unknown"); - clearDiv(target); - - if (!data || data.length === 0) { - const p = document.createElement('p'); - p.classList.add('text-muted'); - p.textContent = 'No unknown IPs seen in the last 5 minutes.'; - target.appendChild(p); - return; - } - - let table = document.createElement("table"); - table.classList.add("table", "table-striped"); - let thead = document.createElement("thead"); - thead.appendChild(theading("IP Address")); - thead.appendChild(theading("Last Seen")); - thead.appendChild(theading("Total Bytes", 2)); - table.appendChild(thead); - let tbody = document.createElement("tbody"); - - data.forEach((row) => { - let tr = document.createElement("tr"); - tr.appendChild(simpleRow(row.ip)); - tr.appendChild(simpleRow(formatLastSeen(row.last_seen_nanos))); - tr.appendChild(simpleRow(scaleNumber(row.total_bytes.down))); - tr.appendChild(simpleRow(scaleNumber(row.total_bytes.up))); - tbody.appendChild(tr); +function loadUnknownIps() { + listenOnce("UnknownIps", (msg) => { + const data = msg && msg.data ? msg.data : []; + let target = document.getElementById("unknown"); + clearDiv(target); + + if (!data || data.length === 0) { + const p = document.createElement('p'); + p.classList.add('text-muted'); + p.textContent = 'No unknown IPs seen in the last 5 minutes.'; + target.appendChild(p); + return; + } + + let table = document.createElement("table"); + table.classList.add("table", "table-striped"); + let thead = document.createElement("thead"); + thead.appendChild(theading("IP Address")); + thead.appendChild(theading("Last Seen")); + thead.appendChild(theading("Total Bytes", 2)); + table.appendChild(thead); + let tbody = document.createElement("tbody"); + + data.forEach((row) => { + let tr = document.createElement("tr"); + tr.appendChild(simpleRow(row.ip)); + tr.appendChild(simpleRow(formatLastSeen(row.last_seen_nanos))); + tr.appendChild(simpleRow(scaleNumber(row.total_bytes.down))); + tr.appendChild(simpleRow(scaleNumber(row.total_bytes.up))); + tbody.appendChild(tr); + }); + + table.appendChild(tbody); + target.appendChild(table); }); + wsClient.send({ UnknownIps: {} }); +} + +let button = document.getElementById("btnCsv"); +if (button) { + button.onclick = () => { + downloadCsv(); + }; +} + +let clearButton = document.getElementById("btnClear"); +if (clearButton) { + clearButton.onclick = () => { + listenOnce("UnknownIpsCleared", () => { + loadUnknownIps(); + }); + wsClient.send({ UnknownIpsClear: {} }); + }; +} - table.appendChild(tbody); - target.appendChild(table); -}); +loadUnknownIps(); diff --git a/src/rust/lqosd/src/node_manager/local_api.rs b/src/rust/lqosd/src/node_manager/local_api.rs index 52f2f87c..d5f971d2 100644 --- a/src/rust/lqosd/src/node_manager/local_api.rs +++ b/src/rust/lqosd/src/node_manager/local_api.rs @@ -1,143 +1,32 @@ -mod circuit; -mod circuit_count; -mod config; -mod container_status; -mod cpu_affinity; -mod dashboard_themes; -mod device_counts; -mod flow_explorer; -mod flow_map; +pub(crate) mod circuit; +pub(crate) mod circuit_count; +pub(crate) mod config; +pub(crate) mod cpu_affinity; +pub(crate) mod dashboard_themes; +pub(crate) mod device_counts; +pub(crate) mod flow_explorer; +pub(crate) mod flow_map; pub mod lts; -mod network_tree; -mod packet_analysis; -mod reload_libreqos; -mod scheduler; -mod search; -mod shaped_device_api; -mod support; -mod unknown_ips; -mod urgent; -mod version_check; -mod warnings; +pub(crate) mod network_tree; +pub(crate) mod packet_analysis; +pub(crate) mod reload_libreqos; +pub(crate) mod scheduler; +pub(crate) mod search; +pub(crate) mod shaped_device_api; +pub(crate) mod unknown_ips; +pub(crate) mod urgent; +pub(crate) mod warnings; use crate::node_manager::auth::auth_layer; use crate::node_manager::shaper_queries_actor::ShaperQueryCommand; -use axum::routing::{get, post}; +use axum::routing::get; use axum::{Extension, Router}; -use axum_extra::extract::CookieJar; -use serde::Serialize; use tower_http::cors::CorsLayer; pub fn local_api(shaper_query: tokio::sync::mpsc::Sender) -> Router { Router::new() - .route("/dashletThemes", get(dashboard_themes::list_themes)) - .route("/dashletSave", post(dashboard_themes::save_theme)) - .route("/dashletDelete", post(dashboard_themes::delete_theme)) - .route("/dashletGet", post(dashboard_themes::get_theme)) - .route("/versionCheck", get(version_check::version_check)) - .route("/deviceCount", get(device_counts::count_users)) - .route("/devicesAll", get(shaped_device_api::all_shaped_devices)) - .route("/networkTree", get(network_tree::get_network_tree)) - .route("/sanity", get(support::run_sanity_check)) - .route("/ltsCheck", get(lts::stats_check)) - .route("/search", post(search::search)) - .route("/unknownIps", get(unknown_ips::unknown_ips)) - .route("/unknownIpsCsv", get(unknown_ips::unknown_ips_csv)) - .route("/unknownIps/clear", post(unknown_ips::clear_unknown_ips)) - .route("/reloadLqos", get(reload_libreqos::reload_libreqos)) - .route("/adminCheck", get(config::admin_check)) - .route("/getConfig", get(config::get_config)) - .route("/listNics", get(config::list_nics)) - .route("/networkJson", get(config::network_json)) - .route("/allShapedDevices", get(config::all_shaped_devices)) - .route("/updateConfig", post(config::update_lqosd_config)) - .route( - "/updateNetworkAndDevices", - post(config::update_network_and_devices), - ) - .route("/getUsers", get(config::get_users)) - .route("/addUser", post(config::add_user)) - .route("/updateUser", post(config::update_user)) - .route("/deleteUser", post(config::delete_user)) - .route("/circuitById", post(circuit::get_circuit_by_id)) - .route("/hashCircuit", post(circuit::hash_circuit)) - .route("/circuits/count", get(circuit_count::get_circuit_count)) - .route( - "/requestAnalysis/:ip", - get(packet_analysis::request_analysis), - ) .route("/pcapDump/:id", get(packet_analysis::pcap_dump)) - .route("/flowMap", get(flow_map::flow_lat_lon)) - .route( - "/cpuAffinity/summary", - get(cpu_affinity::cpu_affinity_summary), - ) - .route( - "/cpuAffinity/circuits/:cpu", - get(cpu_affinity::cpu_affinity_circuits), - ) - .route( - "/cpuAffinity/circuitsAll", - get(cpu_affinity::cpu_affinity_circuits_all), - ) - .route( - "/cpuAffinity/previewWeights", - get(cpu_affinity::cpu_affinity_preview_weights), - ) - .route("/globalWarnings", get(warnings::get_global_warnings)) - .route("/asnList", get(flow_explorer::asn_list)) - .route("/countryList", get(flow_explorer::country_list)) - .route("/protocolList", get(flow_explorer::protocol_list)) - .route("/flowTimeline/:asn_id", get(flow_explorer::flow_timeline)) - .route( - "/countryTimeline/:iso_code", - get(flow_explorer::country_timeline), - ) - .route( - "/protocolTimeline/:protocol", - get(flow_explorer::protocol_timeline), - ) - .route("/containerStatus", get(container_status::container_status)) - .route("/ltsSignUp", post(lts::lts_trial_signup)) - .route("/ltsShaperStatus", get(lts::shaper_status_from_lts)) - //.route("/lts24", get(lts::last_24_hours)) - .route("/ltsThroughput/:seconds", get(lts::throughput_period)) - .route("/ltsPackets/:seconds", get(lts::packets_period)) - .route( - "/ltsPercentShaped/:seconds", - get(lts::percent_shaped_period), - ) - .route("/ltsFlows/:seconds", get(lts::percent_flows_period)) - //.route("/ltsRetransmits/:seconds", get(lts::retransmits_period)) - .route("/ltsCake/:seconds", get(lts::cake_period)) - .route("/ltsRttHisto/:seconds", get(lts::rtt_histo_period)) - .route( - "/ltsTop10Downloaders/:seconds", - get(lts::top10_downloaders_period), - ) - .route("/ltsWorst10Rtt/:seconds", get(lts::worst10_rtt_period)) - .route("/ltsWorst10Rxmit/:seconds", get(lts::worst10_rxmit_period)) - .route("/ltsTopFlows/:seconds", get(lts::top10_flows_period)) - .route("/ltsRecentMedian", get(lts::recent_medians)) - .route("/scheduler/status", get(scheduler::scheduler_status)) - .route("/scheduler/details", get(scheduler::scheduler_details)) - .route("/urgent/status", get(urgent::urgent_status)) - .route("/urgent/list", get(urgent::urgent_list)) - .route("/urgent/clear/:id", post(urgent::urgent_clear)) - .route("/urgent/clear_all", post(urgent::urgent_clear_all)) - .route("/chatbot_sso_token", get(chatbot_sso_token)) .layer(Extension(shaper_query)) .layer(CorsLayer::very_permissive()) .route_layer(axum::middleware::from_fn(auth_layer)) } - -#[derive(Serialize)] -struct ChatbotToken { - token: Option, -} - -async fn chatbot_sso_token(jar: CookieJar) -> axum::Json { - // Node Manager stores auth as a cookie named "User-Token" - let tok = jar.get("User-Token").map(|c| c.value().to_string()); - axum::Json(ChatbotToken { token: tok }) -} diff --git a/src/rust/lqosd/src/node_manager/local_api/circuit.rs b/src/rust/lqosd/src/node_manager/local_api/circuit.rs index 8b6447ad..8991bfe8 100644 --- a/src/rust/lqosd/src/node_manager/local_api/circuit.rs +++ b/src/rust/lqosd/src/node_manager/local_api/circuit.rs @@ -1,18 +1,8 @@ use crate::shaped_devices_tracker::SHAPED_DEVICES; -use axum::Json; -use axum::http::StatusCode; use lqos_config::ShapedDevice; -use serde::{Deserialize, Serialize}; -#[derive(Deserialize)] -pub struct CircuitId { - id: String, -} - -pub async fn get_circuit_by_id( - Json(id): Json, -) -> Result>, StatusCode> { - let safe_id = id.id.to_lowercase().trim().to_string(); +pub fn circuit_by_id_data(id: &str) -> Option> { + let safe_id = id.to_lowercase().trim().to_string(); let reader = SHAPED_DEVICES.load(); let devices: Vec = reader .devices @@ -22,19 +12,8 @@ pub async fn get_circuit_by_id( .collect(); if devices.is_empty() { - return Err(StatusCode::NOT_FOUND); + None } else { - return Ok(Json(devices)); + Some(devices) } } - -#[derive(Serialize)] -pub struct CircuitHash { - pub hash: i64, -} - -/// Compute the standard LibreQoS circuit hash (i64) from a circuit_id string. -pub async fn hash_circuit(Json(id): Json) -> Json { - let h = lqos_utils::hash_to_i64(&id.id); - Json(CircuitHash { hash: h }) -} diff --git a/src/rust/lqosd/src/node_manager/local_api/circuit_count.rs b/src/rust/lqosd/src/node_manager/local_api/circuit_count.rs index 961afe20..b9c6928b 100644 --- a/src/rust/lqosd/src/node_manager/local_api/circuit_count.rs +++ b/src/rust/lqosd/src/node_manager/local_api/circuit_count.rs @@ -1,25 +1,24 @@ use crate::shaped_devices_tracker::SHAPED_DEVICES; use crate::throughput_tracker::THROUGHPUT_TRACKER; -use axum::Json; use lqos_utils::unix_time::time_since_boot; use serde::Serialize; use std::collections::HashSet; use std::time::Duration; -#[derive(Serialize)] +#[derive(Debug, Serialize)] pub struct CircuitCount { pub count: usize, pub configured_count: usize, } -pub async fn get_circuit_count() -> Json { +pub fn circuit_count_data() -> CircuitCount { const FIVE_MINUTES_IN_NANOS: u64 = 5 * 60 * 1_000_000_000; let Ok(time_since_boot) = time_since_boot() else { - return Json(CircuitCount { + return CircuitCount { count: 0, configured_count: 0, - }); + }; }; let now = Duration::from(time_since_boot).as_nanos() as u64; @@ -51,8 +50,8 @@ pub async fn get_circuit_count() -> Json { configured_circuits.len() }; - Json(CircuitCount { + CircuitCount { count, configured_count: configured_circuits.len(), - }) + } } diff --git a/src/rust/lqosd/src/node_manager/local_api/config.rs b/src/rust/lqosd/src/node_manager/local_api/config.rs index 7a2c6fc8..445052ba 100644 --- a/src/rust/lqosd/src/node_manager/local_api/config.rs +++ b/src/rust/lqosd/src/node_manager/local_api/config.rs @@ -1,7 +1,6 @@ use crate::node_manager::auth::LoginResult; use crate::shaped_devices_tracker::SHAPED_DEVICES; use axum::http::StatusCode; -use axum::{Extension, Json}; use default_net::get_interfaces; use lqos_bus::{BusRequest, bus_request}; use lqos_config::{Config, ConfigShapedDevices, ShapedDevice, WebUser, WebUsers}; @@ -9,26 +8,20 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; use std::sync::Arc; -pub async fn admin_check(Extension(login): Extension) -> Json { - match login { - LoginResult::Admin => Json(true), - _ => Json(false), - } +pub fn admin_check_data(login: LoginResult) -> bool { + matches!(login, LoginResult::Admin) } -pub async fn get_config( - Extension(login): Extension, -) -> Result, StatusCode> { +pub fn get_config_data(login: LoginResult) -> Result { if login != LoginResult::Admin { return Err(StatusCode::FORBIDDEN); } - let config = lqos_config::load_config().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - Ok(Json((*config).clone())) + lqos_config::load_config() + .map(|config| (*config).clone()) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR) } -pub async fn list_nics( - Extension(login): Extension, -) -> Result>, StatusCode> { +pub fn list_nics_data(login: LoginResult) -> Result, StatusCode> { if login != LoginResult::Admin { return Err(StatusCode::FORBIDDEN); } @@ -43,58 +36,52 @@ pub async fn list_nics( (eth.name.clone(), format!("{:?}", eth.if_type), mac) }) .collect(); - Ok(Json(result)) + Ok(result) } -pub async fn network_json() -> Json { +pub fn network_json_data() -> Value { if let Ok(config) = lqos_config::load_config() { let path = std::path::Path::new(&config.lqos_directory).join("network.json"); if path.exists() { let raw = std::fs::read_to_string(path).expect("Unable to read network json"); let json: Value = serde_json::from_str(&raw).expect("Unable to read network json"); - return Json(json); + return json; } } - Json(Value::String("Not done yet".to_string())) + Value::String("Not done yet".to_string()) } -pub async fn all_shaped_devices() -> Json> { - Json(SHAPED_DEVICES.load().devices.clone()) +pub fn all_shaped_devices_data() -> Vec { + SHAPED_DEVICES.load().devices.clone() } -pub async fn update_lqosd_config( - Extension(login): Extension, - data: Json, -) -> String { +pub async fn update_lqosd_config_data( + login: LoginResult, + config: Config, +) -> Result<(), StatusCode> { if login != LoginResult::Admin { - return "Unauthorized".to_string(); + return Err(StatusCode::FORBIDDEN); } - let config: Config = (*data).clone(); bus_request(vec![BusRequest::UpdateLqosdConfig(Box::new(config))]) .await - .expect("Unable to update config"); - "Ok".to_string() + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(()) } -#[derive(Deserialize, Clone)] -pub struct NetworkAndDevices { - shaped_devices: Vec, +pub fn update_network_and_devices_data( + login: LoginResult, network_json: Value, -} - -pub async fn update_network_and_devices( - Extension(login): Extension, - data: Json, -) -> String { + shaped_devices: Vec, +) -> Result<(), StatusCode> { if login != LoginResult::Admin { - return "Unauthorized".to_string(); + return Err(StatusCode::FORBIDDEN); } let config = lqos_config::load_config().expect("Unable to load LibreQoS config"); // Save network.json - let serialized_string = serde_json::to_string_pretty(&data.network_json) + let serialized_string = serde_json::to_string_pretty(&network_json) .expect("Unable to serialize network.json payload"); let net_json_path = std::path::Path::new(&config.lqos_directory).join("network.json"); let net_json_backup_path = @@ -114,36 +101,24 @@ pub async fn update_network_and_devices( std::fs::copy(&sd_path, sd_backup_path).expect("Unable to create ShapedDevices.csv backup"); } let mut copied = ConfigShapedDevices::default(); - copied.replace_with_new_data(data.shaped_devices.clone()); + copied.replace_with_new_data(shaped_devices); copied .write_csv(&format!("{}/ShapedDevices.csv", config.lqos_directory)) .expect("Unable to write ShapedDevices.csv"); SHAPED_DEVICES.store(Arc::new(copied)); - "Ok".to_string() + Ok(()) } -#[derive(Serialize, Deserialize)] -pub struct UserRequest { - pub username: String, - pub password: Option, - pub role: String, -} - -pub async fn get_users( - Extension(login): Extension, -) -> Result>, StatusCode> { +pub fn get_users_data(login: LoginResult) -> Result, StatusCode> { if login != LoginResult::Admin { return Err(StatusCode::FORBIDDEN); } let users = WebUsers::load_or_create().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - Ok(Json(users.get_users())) + Ok(users.get_users()) } -pub async fn add_user( - Extension(login): Extension, - Json(data): Json, -) -> Result { +pub fn add_user_data(login: LoginResult, data: UserRequest) -> Result { if login != LoginResult::Admin { return Err(StatusCode::FORBIDDEN); } @@ -161,10 +136,7 @@ pub async fn add_user( Ok(format!("User '{}' added", data.username)) } -pub async fn update_user( - Extension(login): Extension, - Json(data): Json, -) -> Result { +pub fn update_user_data(login: LoginResult, data: UserRequest) -> Result { if login != LoginResult::Admin { return Err(StatusCode::FORBIDDEN); } @@ -176,21 +148,20 @@ pub async fn update_user( Ok("User updated".to_string()) } -#[derive(Deserialize)] -pub struct DeleteUserRequest { - pub username: String, -} - -pub async fn delete_user( - Extension(login): Extension, - Json(data): Json, -) -> Result { +pub fn delete_user_data(login: LoginResult, username: String) -> Result { if login != LoginResult::Admin { return Err(StatusCode::FORBIDDEN); } let mut users = WebUsers::load_or_create().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; users - .remove_user(&data.username) + .remove_user(&username) .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; Ok("User deleted".to_string()) } + +#[derive(Serialize, Deserialize)] +pub struct UserRequest { + pub username: String, + pub password: Option, + pub role: String, +} diff --git a/src/rust/lqosd/src/node_manager/local_api/container_status.rs b/src/rust/lqosd/src/node_manager/local_api/container_status.rs deleted file mode 100644 index 20737df3..00000000 --- a/src/rust/lqosd/src/node_manager/local_api/container_status.rs +++ /dev/null @@ -1,89 +0,0 @@ -//! Provides a diagnostic API for tracking the status of various -//! data containers. Designed to help identify/diagnose RAM -//! usage issues. - -use crate::shaped_devices_tracker::{NETWORK_JSON, SHAPED_DEVICES}; -use crate::throughput_tracker::THROUGHPUT_TRACKER; -use crate::throughput_tracker::flow_data::{ALL_FLOWS, FlowAnalysisSystem, RECENT_FLOWS}; -use axum::Json; -use serde::Serialize; - -#[derive(Debug, Serialize, Default)] -pub struct ContainerSize { - pub size: usize, - pub capacity: usize, -} - -#[derive(Debug, Serialize)] -pub struct ContainerStatus { - pub tracked_flows: ContainerSize, - pub recent_flows: ContainerSize, - pub throughput_tracker: ContainerSize, - pub shaped_devices: ContainerSize, - pub shaped_devices_trie: usize, - pub asn_trie: usize, - pub geo_trie: usize, - pub asn_lookup_table: ContainerSize, - pub net_json: ContainerSize, -} - -fn tracked_flows() -> ContainerSize { - let all_flows = ALL_FLOWS.lock(); - let size = all_flows.flow_data.len(); - let capacity = all_flows.flow_data.capacity(); - ContainerSize { size, capacity } -} - -fn recent_flows() -> ContainerSize { - let (size, capacity) = RECENT_FLOWS.len_and_capacity(); - ContainerSize { size, capacity } -} - -fn throughput_tracker() -> ContainerSize { - ContainerSize { - size: THROUGHPUT_TRACKER.raw_data.lock().len(), - capacity: THROUGHPUT_TRACKER.raw_data.lock().capacity(), - } -} - -fn shaped_devices() -> (ContainerSize, usize) { - let sd = SHAPED_DEVICES.load(); - let size = sd.devices.len(); - let capacity = sd.devices.capacity(); - let trie_size = sd.trie.len(); - (ContainerSize { size, capacity }, trie_size.0 + trie_size.1) -} - -fn asn_analysis() -> (usize, usize, ContainerSize) { - let (asn_trie, geo_trie, lookup_len, lookup_capacity) = FlowAnalysisSystem::len_and_capacity(); - ( - asn_trie, - geo_trie, - ContainerSize { - size: lookup_len, - capacity: lookup_capacity, - }, - ) -} - -fn net_json() -> ContainerSize { - let nj = NETWORK_JSON.read(); - let (size, capacity) = nj.len_and_capacity(); - ContainerSize { size, capacity } -} - -pub async fn container_status() -> Json { - let (shaped_devices, shaped_devices_trie) = shaped_devices(); - let (asn_trie, geo_trie, asn_lookup_table) = asn_analysis(); - Json(ContainerStatus { - tracked_flows: tracked_flows(), - recent_flows: recent_flows(), - throughput_tracker: throughput_tracker(), - shaped_devices, - shaped_devices_trie, - asn_trie, - geo_trie, - asn_lookup_table, - net_json: net_json(), - }) -} diff --git a/src/rust/lqosd/src/node_manager/local_api/cpu_affinity.rs b/src/rust/lqosd/src/node_manager/local_api/cpu_affinity.rs index 5dc5d58c..be7ce663 100644 --- a/src/rust/lqosd/src/node_manager/local_api/cpu_affinity.rs +++ b/src/rust/lqosd/src/node_manager/local_api/cpu_affinity.rs @@ -1,4 +1,3 @@ -use axum::{Json, extract::Path, extract::Query}; use serde::Serialize; use serde_json::Value; use std::collections::HashMap; @@ -19,9 +18,6 @@ pub struct CpuAffinitySummaryEntry { pub upload: CpuSideSummary, } -#[derive(Serialize, Clone, Debug)] -pub struct CpuAffinitySummaryResponse(pub Vec); - #[derive(Serialize, Clone, Debug)] pub struct CircuitBrief { pub circuit_id: Option, @@ -252,7 +248,7 @@ fn load_all_circuits() -> Vec { circuits } -pub async fn cpu_affinity_summary() -> Json { +pub fn cpu_affinity_summary_data() -> Vec { let circuits = load_all_circuits(); let mut down: HashMap = HashMap::new(); let mut up: HashMap = HashMap::new(); @@ -305,13 +301,10 @@ pub async fn cpu_affinity_summary() -> Json { }); } - Json(CpuAffinitySummaryResponse(entries)) + entries } -pub async fn cpu_affinity_circuits( - Path(cpu): Path, - Query(q): Query, -) -> Json { +pub fn cpu_affinity_circuits_data(cpu: u32, q: CircuitsQuery) -> CpuAffinityCircuitsPage { let direction = q .direction .as_deref() @@ -388,18 +381,18 @@ pub async fn cpu_affinity_circuits( Vec::new() }; - Json(CpuAffinityCircuitsPage { + CpuAffinityCircuitsPage { cpu, direction: direction.to_string(), total, page, page_size, items: page_items, - }) + } } // Return all circuits (direction-filtered) without pagination to support client-side previews. -pub async fn cpu_affinity_circuits_all(Query(q): Query) -> Json> { +pub fn cpu_affinity_circuits_all_data(q: CircuitsQuery) -> Vec { let direction = q .direction .as_deref() @@ -460,7 +453,7 @@ pub async fn cpu_affinity_circuits_all(Query(q): Query) -> Json, -) -> Json> { +pub fn cpu_affinity_preview_weights_data(q: CircuitsQuery) -> Vec { let direction = q .direction .as_deref() @@ -525,5 +516,5 @@ pub async fn cpu_affinity_preview_weights( } }); - Json(items) + items } diff --git a/src/rust/lqosd/src/node_manager/local_api/dashboard_themes.rs b/src/rust/lqosd/src/node_manager/local_api/dashboard_themes.rs index 7364aafb..1f27718c 100644 --- a/src/rust/lqosd/src/node_manager/local_api/dashboard_themes.rs +++ b/src/rust/lqosd/src/node_manager/local_api/dashboard_themes.rs @@ -1,95 +1,119 @@ -use axum::Json; -use axum::http::StatusCode; use serde::{Deserialize, Serialize}; use lqos_config::load_config; -pub async fn list_themes() -> Json> { - if let Ok(config) = load_config() { - let base_path = std::path::Path::new(&config.lqos_directory) - .join("bin") - .join("dashboards"); - if !base_path.exists() { - std::fs::create_dir(&base_path).expect("Unable to create dashboards directory"); - } - - let mut result = Vec::new(); - for f in std::fs::read_dir(&base_path).expect("Unable to read dashboards directory") { - if let Ok(f) = f { - let fs = f.file_name().to_string_lossy().to_string(); - if fs.ends_with("json") { - result.push(fs.to_string()); - } - } - } - return Json(result); - } - Json(Vec::new()) -} - -#[derive(Serialize, Deserialize)] +#[derive(Serialize, Deserialize, Debug, Clone)] pub struct DashletSave { - name: String, - entries: Vec, + pub name: String, + pub entries: Vec, } -#[derive(Serialize, Deserialize)] +#[derive(Serialize, Deserialize, Debug, Clone)] pub struct DashletIdentity { - name: String, - tag: String, - size: i32, + pub name: String, + pub tag: String, + pub size: i32, } -pub async fn save_theme(Json(data): Json) -> StatusCode { - if let Ok(config) = load_config() { - let base_path = std::path::Path::new(&config.lqos_directory) - .join("bin") - .join("dashboards"); - if !base_path.exists() { - std::fs::create_dir(&base_path).expect("Unable to create dashboards directory"); - } +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct ThemeEntry { + pub name: String, + pub path: String, +} - let name = data.name.replace('/', "_"); - let name = format!("{}.json", name); - let file_path = base_path.join(name); - let serialized = serde_json::to_string(&data).expect("Unable to serialize theme payload"); - std::fs::write(&file_path, serialized.as_bytes()).expect("Unable to write theme file"); +fn dashboards_dir() -> Option { + let config = load_config().ok()?; + let base_path = std::path::Path::new(&config.lqos_directory) + .join("bin") + .join("dashboards"); + if !base_path.exists() { + if std::fs::create_dir(&base_path).is_err() { + return None; + } } - - StatusCode::OK + Some(base_path) } -#[derive(Deserialize)] -pub struct ThemeSelector { - theme: String, +fn normalize_theme_filename(name: &str) -> String { + let safe = name.replace('/', "_").replace('\\', "_"); + if safe.ends_with(".json") { + safe + } else { + format!("{}.json", safe) + } } -pub async fn delete_theme(Json(f): Json) -> StatusCode { - if let Ok(config) = load_config() { - let base_path = std::path::Path::new(&config.lqos_directory) - .join("bin") - .join("dashboards") - .join(&f.theme); - if base_path.exists() { - std::fs::remove_file(base_path).expect("Unable to remove theme file"); +pub(crate) fn list_theme_entries() -> Vec { + let Some(base_path) = dashboards_dir() else { + return Vec::new(); + }; + + let mut result = Vec::new(); + let entries = match std::fs::read_dir(&base_path) { + Ok(entries) => entries, + Err(_) => return result, + }; + + for f in entries.flatten() { + let fs = f.file_name().to_string_lossy().to_string(); + if !fs.ends_with(".json") { + continue; + } + let mut display_name = fs.trim_end_matches(".json").to_string(); + if let Ok(raw) = std::fs::read_to_string(f.path()) { + if let Ok(parsed) = serde_json::from_str::(&raw) { + if !parsed.name.is_empty() { + display_name = parsed.name; + } + } } + result.push(ThemeEntry { + name: display_name, + path: fs, + }); + } + result +} + +pub(crate) fn load_theme_entries(name: &str) -> Vec { + let Some(base_path) = dashboards_dir() else { + return Vec::new(); + }; + + let filename = normalize_theme_filename(name); + let file_path = base_path.join(filename); + if !file_path.exists() { + return Vec::new(); } - StatusCode::OK + let raw = match std::fs::read_to_string(&file_path) { + Ok(raw) => raw, + Err(_) => return Vec::new(), + }; + let result: DashletSave = match serde_json::from_str(&raw) { + Ok(result) => result, + Err(_) => return Vec::new(), + }; + result.entries } -pub async fn get_theme(Json(f): Json) -> Json> { - if let Ok(config) = load_config() { - let base_path = std::path::Path::new(&config.lqos_directory) - .join("bin") - .join("dashboards") - .join(&f.theme); - if base_path.exists() { - let raw = std::fs::read_to_string(&base_path).expect("Unable to read theme file"); - let result: DashletSave = - serde_json::from_str(&raw).expect("Unable to parse theme file"); - return Json(result.entries); - } +pub(crate) fn save_theme_data(data: &DashletSave) -> Result<(), String> { + let base_path = dashboards_dir().ok_or_else(|| "Unable to load configuration".to_string())?; + let filename = normalize_theme_filename(&data.name); + let file_path = base_path.join(filename); + let serialized = + serde_json::to_string(data).map_err(|e| format!("Serialize error: {e}"))?; + std::fs::write(&file_path, serialized.as_bytes()) + .map_err(|e| format!("Write error: {e}"))?; + Ok(()) +} + +pub(crate) fn delete_theme_file(name: &str) -> Result<(), String> { + let base_path = dashboards_dir().ok_or_else(|| "Unable to load configuration".to_string())?; + let filename = normalize_theme_filename(name); + let file_path = base_path.join(filename); + if file_path.exists() { + std::fs::remove_file(file_path).map_err(|e| format!("Delete error: {e}"))?; } - Json(Vec::new()) + Ok(()) } diff --git a/src/rust/lqosd/src/node_manager/local_api/device_counts.rs b/src/rust/lqosd/src/node_manager/local_api/device_counts.rs index 3125a91f..6617aceb 100644 --- a/src/rust/lqosd/src/node_manager/local_api/device_counts.rs +++ b/src/rust/lqosd/src/node_manager/local_api/device_counts.rs @@ -1,17 +1,16 @@ use crate::node_manager::local_api::unknown_ips::get_unknown_ips; use crate::shaped_devices_tracker::SHAPED_DEVICES; -use axum::Json; use serde::Serialize; -#[derive(Serialize)] +#[derive(Serialize, Debug, Clone)] pub struct DeviceCount { pub shaped_devices: usize, pub unknown_ips: usize, } -pub async fn count_users() -> Json { - Json(DeviceCount { +pub fn device_count() -> DeviceCount { + DeviceCount { shaped_devices: SHAPED_DEVICES.load().devices.len(), unknown_ips: get_unknown_ips().len(), - }) + } } diff --git a/src/rust/lqosd/src/node_manager/local_api/flow_explorer.rs b/src/rust/lqosd/src/node_manager/local_api/flow_explorer.rs index ef7985ff..c300c341 100644 --- a/src/rust/lqosd/src/node_manager/local_api/flow_explorer.rs +++ b/src/rust/lqosd/src/node_manager/local_api/flow_explorer.rs @@ -3,27 +3,25 @@ use crate::throughput_tracker::flow_data::{ AsnCountryListEntry, AsnListEntry, AsnProtocolListEntry, FlowAnalysis, FlowbeeLocalData, RECENT_FLOWS, RttData, }; -use axum::Json; -use axum::extract::Path; use lqos_sys::flowbee_data::FlowbeeKey; use lqos_utils::units::DownUpOrder; use lqos_utils::unix_time::{time_since_boot, unix_now}; use serde::Serialize; use std::time::Duration; -pub async fn asn_list() -> Json> { - Json(RECENT_FLOWS.asn_list()) +pub fn asn_list_data() -> Vec { + RECENT_FLOWS.asn_list() } -pub async fn country_list() -> Json> { - Json(RECENT_FLOWS.country_list()) +pub fn country_list_data() -> Vec { + RECENT_FLOWS.country_list() } -pub async fn protocol_list() -> Json> { - Json(RECENT_FLOWS.protocol_list()) +pub fn protocol_list_data() -> Vec { + RECENT_FLOWS.protocol_list() } -#[derive(Serialize)] +#[derive(Debug, Serialize)] pub struct FlowTimeline { start: u64, end: u64, @@ -40,7 +38,7 @@ pub struct FlowTimeline { remote_ip: String, } -pub async fn flow_timeline(Path(asn_id): Path) -> Json> { +pub fn flow_timeline_data(asn_id: u32) -> Vec { let time_since_boot = time_since_boot().expect("failed to retrieve time since boot"); let since_boot = Duration::from(time_since_boot); let boot_time = unix_now() @@ -51,7 +49,7 @@ pub async fn flow_timeline(Path(asn_id): Path) -> Json> { let flows = all_flows_to_transport(boot_time, all_flows_for_asn); - Json(flows) + flows } fn all_flows_to_transport( @@ -110,21 +108,21 @@ fn all_flows_to_transport( .collect::>() } -pub async fn country_timeline(Path(iso_code): Path) -> Json> { +pub fn country_timeline_data(iso_code: &str) -> Vec { let time_since_boot = time_since_boot().expect("failed to retrieve time since boot"); let since_boot = Duration::from(time_since_boot); let boot_time = unix_now() .expect("failed to retrieve current unix time") .saturating_sub(since_boot.as_secs()); - let all_flows_for_asn = RECENT_FLOWS.all_flows_for_country(&iso_code); + let all_flows_for_asn = RECENT_FLOWS.all_flows_for_country(iso_code); let flows = all_flows_to_transport(boot_time, all_flows_for_asn); - Json(flows) + flows } -pub async fn protocol_timeline(Path(protocol_name): Path) -> Json> { +pub fn protocol_timeline_data(protocol_name: &str) -> Vec { let protocol_name = protocol_name.replace("_", "/"); let time_since_boot = time_since_boot().expect("failed to retrieve time since boot"); let since_boot = Duration::from(time_since_boot); @@ -136,5 +134,5 @@ pub async fn protocol_timeline(Path(protocol_name): Path) -> Json Json> { - Json(flow_data::RECENT_FLOWS.lat_lon_endpoints()) +pub fn flow_map_data() -> Vec<(f64, f64, String, u64, f32)> { + flow_data::RECENT_FLOWS.lat_lon_endpoints() } diff --git a/src/rust/lqosd/src/node_manager/local_api/lts.rs b/src/rust/lqosd/src/node_manager/local_api/lts.rs index 317ba7d1..e77e981d 100644 --- a/src/rust/lqosd/src/node_manager/local_api/lts.rs +++ b/src/rust/lqosd/src/node_manager/local_api/lts.rs @@ -1,91 +1,65 @@ mod last_24_hours; mod shaper_status; -use axum::Json; +use crate::lts2_sys::shared_types::LtsStatus; +use crate::node_manager::auth::LoginResult; use axum::http::StatusCode; pub use last_24_hours::*; use lqos_bus::{BusRequest, bus_request}; use lqos_config::load_config; use serde::{Deserialize, Serialize}; -pub use shaper_status::shaper_status_from_lts; +pub use shaper_status::ShaperStatus; +pub use shaper_status::shaper_status_data; use std::ops::Deref; use std::process::Command; use tracing::{info, warn}; -#[derive(Serialize)] -pub enum StatsCheckResponse { - DoNothing, - NotSetup, - GoodToGo, +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct LtsTrialConfig { + pub node_id: String, + pub lts_url: Option, } -#[derive(Serialize)] -pub struct StatsCheckAction { - action: StatsCheckResponse, - node_id: String, - node_name: String, -} - -pub async fn stats_check() -> Json { - let (status, trial_expiration) = crate::lts2_sys::get_lts_license_status_async().await; - println!("{:?}, {trial_expiration:?}", status); - let mut response = StatsCheckAction { - action: StatsCheckResponse::DoNothing, - node_id: String::new(), - node_name: "LQOS Node".to_string(), - }; - - if let Ok(cfg) = load_config() { - if !cfg.long_term_stats.gather_stats { - response = StatsCheckAction { - action: StatsCheckResponse::NotSetup, - node_id: cfg.node_id.to_string(), - node_name: cfg.node_name.to_string(), - }; - } else { - // Stats are enabled - response = StatsCheckAction { - action: StatsCheckResponse::GoodToGo, - node_id: cfg.node_id.to_string(), - node_name: cfg.node_name.to_string(), - }; - } +pub fn lts_trial_config_data(login: LoginResult) -> Result { + if login != LoginResult::Admin { + return Err(StatusCode::FORBIDDEN); } - - Json(response) + let cfg = load_config().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(LtsTrialConfig { + node_id: cfg.node_id.clone(), + lts_url: cfg.long_term_stats.lts_url.clone(), + }) } -#[derive(Deserialize, Serialize, Debug, Clone)] -pub struct LicenseKey { - pub license_key: String, +pub(crate) async fn insight_gate() -> Result<(), StatusCode> { + let (status, _) = crate::lts2_sys::get_lts_license_status_async().await; + match status { + LtsStatus::Invalid | LtsStatus::NotChecked => Err(StatusCode::FORBIDDEN), + _ => Ok(()), + } } -pub async fn lts_trial_signup(details: Json) -> StatusCode { - info!("Received free trial signup request: {:?}", details); - let license_key = details.license_key.clone(); - +pub async fn lts_trial_signup_data(license_key: String) -> Result<(), StatusCode> { info!("Received license key, enabling free trial: {}", license_key); if license_key == "FAIL" { warn!("Free trial request failed"); - StatusCode::INTERNAL_SERVER_ERROR - } else { - info!("Free trial request succeeded, license key: {}", license_key); - let mut cfg = load_config() - .expect("Unable to load LibreQoS config") - .deref() - .clone(); - cfg.long_term_stats.gather_stats = true; - cfg.long_term_stats.license_key = Some(license_key); - bus_request(vec![BusRequest::UpdateLqosdConfig(Box::new(cfg))]) - .await - .expect("Unable to update lqosd config"); - info!("LQOSD configuration updated with new license key."); - // Best-effort: ensure the bundled lqos_api also reloads to pick up the new license - // Ignore errors if systemctl isn't present or permission is denied. - let _ = Command::new("/bin/systemctl") - .args(["restart", "lqos_api"]) - .output(); - std::process::exit(0); - //StatusCode::OK + return Err(StatusCode::INTERNAL_SERVER_ERROR); } + info!("Free trial request succeeded, license key: {}", license_key); + let mut cfg = load_config() + .expect("Unable to load LibreQoS config") + .deref() + .clone(); + cfg.long_term_stats.gather_stats = true; + cfg.long_term_stats.license_key = Some(license_key); + bus_request(vec![BusRequest::UpdateLqosdConfig(Box::new(cfg))]) + .await + .expect("Unable to update lqosd config"); + info!("LQOSD configuration updated with new license key."); + // Best-effort: ensure the bundled lqos_api also reloads to pick up the new license + // Ignore errors if systemctl isn't present or permission is denied. + let _ = Command::new("/bin/systemctl") + .args(["restart", "lqos_api"]) + .output(); + Ok(()) } diff --git a/src/rust/lqosd/src/node_manager/local_api/lts/last_24_hours.rs b/src/rust/lqosd/src/node_manager/local_api/lts/last_24_hours.rs index cf8b08b5..151f5697 100644 --- a/src/rust/lqosd/src/node_manager/local_api/lts/last_24_hours.rs +++ b/src/rust/lqosd/src/node_manager/local_api/lts/last_24_hours.rs @@ -1,7 +1,5 @@ use crate::node_manager::shaper_queries_actor::ShaperQueryCommand; -use axum::extract::Path; use axum::http::StatusCode; -use axum::{Extension, Json}; use serde::{Deserialize, Serialize}; use tracing::warn; @@ -16,7 +14,7 @@ pub struct ThroughputData { median_up: i64, } -#[derive(Serialize, Deserialize, Clone)] +#[derive(Debug, Serialize, Deserialize, Clone)] pub struct FullPacketData { pub time: i64, // Unix timestamp pub max_down: i64, @@ -45,7 +43,7 @@ pub struct FullPacketData { pub median_icmp_up: i64, } -#[derive(Serialize, Deserialize)] +#[derive(Debug, Serialize, Deserialize)] pub struct CakeData { time: i64, // Unix timestamp max_marks_down: i64, @@ -69,19 +67,19 @@ pub struct PercentShapedWeb { pub percent_shaped: f64, } -#[derive(Serialize, Deserialize, Clone)] +#[derive(Debug, Serialize, Deserialize, Clone)] pub struct FlowCountViewWeb { time: i64, shaper_id: i64, flow_count: f64, } -#[derive(Serialize, Deserialize, Clone)] +#[derive(Debug, Serialize, Deserialize, Clone)] pub struct ShaperRttHistogramEntry { pub value: i32, } -#[derive(Serialize, Deserialize, Clone)] +#[derive(Debug, Serialize, Deserialize, Clone)] pub struct Top10Circuit { pub shaper_id: i64, pub shaper_name: String, @@ -92,7 +90,7 @@ pub struct Top10Circuit { pub rxmit: Option, } -#[derive(Serialize, Deserialize, Clone)] +#[derive(Debug, Serialize, Deserialize, Clone)] pub struct Worst10RttCircuit { pub shaper_id: i64, pub shaper_name: String, @@ -103,7 +101,7 @@ pub struct Worst10RttCircuit { pub rxmit: Option, } -#[derive(Serialize, Deserialize, Clone)] +#[derive(Debug, Serialize, Deserialize, Clone)] pub struct Worst10RxmitCircuit { pub shaper_id: i64, pub shaper_name: String, @@ -138,10 +136,11 @@ pub struct RecentMedians { pub last_week: (i64, i64), } -pub async fn throughput_period( - Extension(shaper_query): Extension>, - Path(seconds): Path, -) -> Result>, StatusCode> { +pub async fn throughput_period_data( + shaper_query: tokio::sync::mpsc::Sender, + seconds: i32, +) -> Result, StatusCode> { + super::insight_gate().await?; let (tx, rx) = tokio::sync::oneshot::channel(); shaper_query .send(ShaperQueryCommand::ShaperThroughput { seconds, reply: tx }) @@ -151,13 +150,14 @@ pub async fn throughput_period( warn!("Error getting total throughput: {:?}", e); StatusCode::INTERNAL_SERVER_ERROR })?; - Ok(Json(throughput)) + Ok(throughput) } -pub async fn packets_period( - Extension(shaper_query): Extension>, - Path(seconds): Path, -) -> Result>, StatusCode> { +pub async fn packets_period_data( + shaper_query: tokio::sync::mpsc::Sender, + seconds: i32, +) -> Result, StatusCode> { + super::insight_gate().await?; let (tx, rx) = tokio::sync::oneshot::channel(); shaper_query .send(ShaperQueryCommand::ShaperPackets { seconds, reply: tx }) @@ -170,13 +170,14 @@ pub async fn packets_period( warn!("Error getting packets period: {:?}", e); StatusCode::INTERNAL_SERVER_ERROR })?; - Ok(Json(throughput)) + Ok(throughput) } -pub async fn percent_shaped_period( - Extension(shaper_query): Extension>, - Path(seconds): Path, -) -> Result>, StatusCode> { +pub async fn percent_shaped_period_data( + shaper_query: tokio::sync::mpsc::Sender, + seconds: i32, +) -> Result, StatusCode> { + super::insight_gate().await?; let (tx, rx) = tokio::sync::oneshot::channel(); shaper_query .send(ShaperQueryCommand::ShaperPercent { seconds, reply: tx }) @@ -189,13 +190,14 @@ pub async fn percent_shaped_period( warn!("Error getting percent shaped: {:?}", e); StatusCode::INTERNAL_SERVER_ERROR })?; - Ok(Json(throughput)) + Ok(throughput) } -pub async fn percent_flows_period( - Extension(shaper_query): Extension>, - Path(seconds): Path, -) -> Result>, StatusCode> { +pub async fn percent_flows_period_data( + shaper_query: tokio::sync::mpsc::Sender, + seconds: i32, +) -> Result, StatusCode> { + super::insight_gate().await?; let (tx, rx) = tokio::sync::oneshot::channel(); shaper_query .send(ShaperQueryCommand::ShaperFlows { seconds, reply: tx }) @@ -208,13 +210,14 @@ pub async fn percent_flows_period( warn!("Error getting flows: {:?}", e); StatusCode::INTERNAL_SERVER_ERROR })?; - Ok(Json(throughput)) + Ok(throughput) } -pub async fn rtt_histo_period( - Extension(shaper_query): Extension>, - Path(seconds): Path, -) -> Result>, StatusCode> { +pub async fn rtt_histo_period_data( + shaper_query: tokio::sync::mpsc::Sender, + seconds: i32, +) -> Result, StatusCode> { + super::insight_gate().await?; tracing::error!("rtt_histo_period"); let (tx, rx) = tokio::sync::oneshot::channel(); shaper_query @@ -228,13 +231,14 @@ pub async fn rtt_histo_period( warn!("Error getting flows: {:?}", e); StatusCode::INTERNAL_SERVER_ERROR })?; - Ok(Json(throughput)) + Ok(throughput) } -pub async fn top10_downloaders_period( - Extension(shaper_query): Extension>, - Path(seconds): Path, -) -> Result>, StatusCode> { +pub async fn top10_downloaders_period_data( + shaper_query: tokio::sync::mpsc::Sender, + seconds: i32, +) -> Result, StatusCode> { + super::insight_gate().await?; tracing::error!("rtt_histo_period"); let (tx, rx) = tokio::sync::oneshot::channel(); shaper_query @@ -248,13 +252,14 @@ pub async fn top10_downloaders_period( warn!("Error getting flows: {:?}", e); StatusCode::INTERNAL_SERVER_ERROR })?; - Ok(Json(throughput)) + Ok(throughput) } -pub async fn worst10_rtt_period( - Extension(shaper_query): Extension>, - Path(seconds): Path, -) -> Result>, StatusCode> { +pub async fn worst10_rtt_period_data( + shaper_query: tokio::sync::mpsc::Sender, + seconds: i32, +) -> Result, StatusCode> { + super::insight_gate().await?; tracing::error!("rtt_histo_period"); let (tx, rx) = tokio::sync::oneshot::channel(); shaper_query @@ -268,13 +273,14 @@ pub async fn worst10_rtt_period( warn!("Error getting flows: {:?}", e); StatusCode::INTERNAL_SERVER_ERROR })?; - Ok(Json(throughput)) + Ok(throughput) } -pub async fn worst10_rxmit_period( - Extension(shaper_query): Extension>, - Path(seconds): Path, -) -> Result>, StatusCode> { +pub async fn worst10_rxmit_period_data( + shaper_query: tokio::sync::mpsc::Sender, + seconds: i32, +) -> Result, StatusCode> { + super::insight_gate().await?; tracing::error!("rtt_histo_period"); let (tx, rx) = tokio::sync::oneshot::channel(); shaper_query @@ -288,13 +294,14 @@ pub async fn worst10_rxmit_period( warn!("Error getting flows: {:?}", e); StatusCode::INTERNAL_SERVER_ERROR })?; - Ok(Json(throughput)) + Ok(throughput) } -pub async fn top10_flows_period( - Extension(shaper_query): Extension>, - Path(seconds): Path, -) -> Result>, StatusCode> { +pub async fn top10_flows_period_data( + shaper_query: tokio::sync::mpsc::Sender, + seconds: i32, +) -> Result, StatusCode> { + super::insight_gate().await?; tracing::error!("rtt_histo_period"); let (tx, rx) = tokio::sync::oneshot::channel(); shaper_query @@ -308,12 +315,13 @@ pub async fn top10_flows_period( warn!("Error getting flows: {:?}", e); StatusCode::INTERNAL_SERVER_ERROR })?; - Ok(Json(throughput)) + Ok(throughput) } -pub async fn recent_medians( - Extension(shaper_query): Extension>, -) -> Result>, StatusCode> { +pub async fn recent_medians_data( + shaper_query: tokio::sync::mpsc::Sender, +) -> Result, StatusCode> { + super::insight_gate().await?; tracing::debug!("rtt_histo_period"); let (tx, rx) = tokio::sync::oneshot::channel(); shaper_query @@ -327,13 +335,14 @@ pub async fn recent_medians( warn!("Error getting flows: {:?}", e); StatusCode::INTERNAL_SERVER_ERROR })?; - Ok(Json(throughput)) + Ok(throughput) } -pub async fn cake_period( - Extension(shaper_query): Extension>, - Path(seconds): Path, -) -> Result>, StatusCode> { +pub async fn cake_period_data( + shaper_query: tokio::sync::mpsc::Sender, + seconds: i32, +) -> Result, StatusCode> { + super::insight_gate().await?; let (tx, rx) = tokio::sync::oneshot::channel(); shaper_query .send(ShaperQueryCommand::CakeTotals { seconds, reply: tx }) @@ -346,5 +355,5 @@ pub async fn cake_period( warn!("Error getting cake stats: {:?}", e); StatusCode::INTERNAL_SERVER_ERROR })?; - Ok(Json(response)) + Ok(response) } diff --git a/src/rust/lqosd/src/node_manager/local_api/lts/shaper_status.rs b/src/rust/lqosd/src/node_manager/local_api/lts/shaper_status.rs index 88f94703..8c214292 100644 --- a/src/rust/lqosd/src/node_manager/local_api/lts/shaper_status.rs +++ b/src/rust/lqosd/src/node_manager/local_api/lts/shaper_status.rs @@ -1,16 +1,16 @@ -use axum::Json; use axum::http::StatusCode; use lqos_config::load_config; use serde::{Deserialize, Serialize}; use tracing::error; -#[derive(Serialize, Deserialize)] +#[derive(Debug, Serialize, Deserialize)] pub struct ShaperStatus { name: String, last_seen_seconds_ago: f32, } -pub async fn shaper_status_from_lts() -> Result>, StatusCode> { +pub async fn shaper_status_data() -> Result, StatusCode> { + super::insight_gate().await?; let config = load_config().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; let url = format!( "https://{}/shaper_api/status", @@ -54,5 +54,5 @@ pub async fn shaper_status_from_lts() -> Result>, StatusC StatusCode::INTERNAL_SERVER_ERROR })?; - Ok(Json(shapers)) + Ok(shapers) } diff --git a/src/rust/lqosd/src/node_manager/local_api/network_tree.rs b/src/rust/lqosd/src/node_manager/local_api/network_tree.rs index 709a8447..5213a0aa 100644 --- a/src/rust/lqosd/src/node_manager/local_api/network_tree.rs +++ b/src/rust/lqosd/src/node_manager/local_api/network_tree.rs @@ -1,15 +1,12 @@ use crate::shaped_devices_tracker::NETWORK_JSON; -use axum::Json; use lqos_config::NetworkJsonTransport; -pub async fn get_network_tree() -> Json> { +pub fn network_tree_data() -> Vec<(usize, NetworkJsonTransport)> { let net_json = NETWORK_JSON.read(); - let result: Vec<(usize, NetworkJsonTransport)> = net_json + net_json .get_nodes_when_ready() .iter() .enumerate() .map(|(i, n)| (i, n.clone_to_transit())) - .collect(); - - Json(result) + .collect() } diff --git a/src/rust/lqosd/src/node_manager/local_api/packet_analysis.rs b/src/rust/lqosd/src/node_manager/local_api/packet_analysis.rs index 4e89d8fe..73ed3beb 100644 --- a/src/rust/lqosd/src/node_manager/local_api/packet_analysis.rs +++ b/src/rust/lqosd/src/node_manager/local_api/packet_analysis.rs @@ -1,4 +1,3 @@ -use axum::Json; use axum::body::Body; use axum::extract::Path; use axum::http::{HeaderMap, Request}; @@ -8,22 +7,22 @@ use serde::Serialize; use std::net::IpAddr; use tower_http::services::ServeFile; -#[derive(Serialize, Clone)] +#[derive(Debug, Serialize, Clone)] pub enum RequestAnalysisResult { Fail, Ok { session_id: usize, countdown: usize }, } -pub async fn request_analysis(Path(ip): Path) -> Json { +pub fn request_analysis_data(ip: &str) -> RequestAnalysisResult { if let Ok(ip) = ip.parse::() { if let Some((session_id, countdown)) = lqos_heimdall::hyperfocus_on_target(ip.into()) { - return Json(RequestAnalysisResult::Ok { + return RequestAnalysisResult::Ok { session_id, countdown, - }); + }; } } - Json(RequestAnalysisResult::Fail) + RequestAnalysisResult::Fail } pub async fn pcap_dump(Path(id): Path, headers: HeaderMap) -> impl IntoResponse { diff --git a/src/rust/lqosd/src/node_manager/local_api/reload_libreqos.rs b/src/rust/lqosd/src/node_manager/local_api/reload_libreqos.rs index ba20fb43..abe1420f 100644 --- a/src/rust/lqosd/src/node_manager/local_api/reload_libreqos.rs +++ b/src/rust/lqosd/src/node_manager/local_api/reload_libreqos.rs @@ -1,9 +1,8 @@ use crate::node_manager::auth::LoginResult; -use axum::Extension; use tokio::task::spawn_blocking; use tracing::info; -pub async fn reload_libreqos(Extension(login): Extension) -> String { +pub async fn reload_libreqos_with_login(login: LoginResult) -> String { info!("Reloading LibreQoS"); if let LoginResult::Admin = login { let Ok(result) = spawn_blocking(lqos_config::load_libreqos).await else { diff --git a/src/rust/lqosd/src/node_manager/local_api/scheduler.rs b/src/rust/lqosd/src/node_manager/local_api/scheduler.rs index f04258d1..09d1cca0 100644 --- a/src/rust/lqosd/src/node_manager/local_api/scheduler.rs +++ b/src/rust/lqosd/src/node_manager/local_api/scheduler.rs @@ -1,7 +1,3 @@ -use axum::Json; -use axum::http::StatusCode; -use axum::http::header::CONTENT_TYPE; -use axum::response::IntoResponse; use serde::Serialize; use crate::tool_status::{is_scheduler_available, scheduler_error_message}; @@ -62,56 +58,55 @@ fn strip_ansi(input: &str) -> String { out } -#[derive(Serialize)] +#[derive(Serialize, Debug, Clone)] pub struct SchedulerStatus { pub available: bool, pub error: Option, } -/// Lightweight status for navbar rendering -pub async fn scheduler_status() -> (StatusCode, Json) { - let available = is_scheduler_available(); - let error = scheduler_error_message().and_then(|s| { +#[derive(Serialize, Debug, Clone)] +pub struct SchedulerDetails { + pub available: bool, + pub error: Option, + pub details: String, +} + +fn scheduler_error() -> Option { + scheduler_error_message().and_then(|s| { let t = s.trim().to_string(); if t.is_empty() { None } else { Some(strip_ansi(&t)) } - }); - (StatusCode::OK, Json(SchedulerStatus { available, error })) + }) } -/// Potentially large details payload suitable for a modal -pub async fn scheduler_details() -> impl IntoResponse { +pub fn scheduler_status_data() -> SchedulerStatus { let available = is_scheduler_available(); - let error = scheduler_error_message().and_then(|s| { - let t = s.trim().to_string(); - if t.is_empty() { - None - } else { - Some(strip_ansi(&t)) - } - }); + let error = scheduler_error(); + SchedulerStatus { available, error } +} +pub fn scheduler_details_data() -> SchedulerDetails { + let status = scheduler_status_data(); let mut body = String::new(); - body.push_str(&format!("Scheduler available: {}\n\n", available)); - match error { + body.push_str(&format!("Scheduler available: {}\n\n", status.available)); + match status.error.as_ref() { Some(err) => { body.push_str("Reported error:\n"); - body.push_str(&err); + body.push_str(err); body.push('\n'); } None => { body.push_str("No scheduler error reported.\n"); } } - // Placeholder for future expansion (e.g., log tail, diagnostics) body.push_str("\n(Additional scheduler diagnostics not available.)\n"); - ( - StatusCode::OK, - [(CONTENT_TYPE, "text/plain; charset=utf-8")], - body, - ) + SchedulerDetails { + available: status.available, + error: status.error, + details: body, + } } diff --git a/src/rust/lqosd/src/node_manager/local_api/search.rs b/src/rust/lqosd/src/node_manager/local_api/search.rs index 83f4fa72..564f4828 100644 --- a/src/rust/lqosd/src/node_manager/local_api/search.rs +++ b/src/rust/lqosd/src/node_manager/local_api/search.rs @@ -1,5 +1,4 @@ use crate::shaped_devices_tracker::{NETWORK_JSON, SHAPED_DEVICES}; -use axum::Json; use ip_network::IpNetwork; use serde::{Deserialize, Serialize}; use std::collections::HashSet; @@ -70,7 +69,7 @@ pub enum SearchResult { }, } -pub async fn search(Json(search): Json) -> Json> { +pub async fn search_results(search: SearchRequest) -> Vec { const MAX_RESULTS: usize = 50; let mut results: Vec = Vec::new(); let mut seen: HashSet = HashSet::new(); // keys like "Device::" or "Circuit:" or "Site:" @@ -253,5 +252,5 @@ pub async fn search(Json(search): Json) -> Json } } - Json(results) + results } diff --git a/src/rust/lqosd/src/node_manager/local_api/shaped_device_api.rs b/src/rust/lqosd/src/node_manager/local_api/shaped_device_api.rs index 41cdc198..411ed7ae 100644 --- a/src/rust/lqosd/src/node_manager/local_api/shaped_device_api.rs +++ b/src/rust/lqosd/src/node_manager/local_api/shaped_device_api.rs @@ -1,7 +1,6 @@ use crate::shaped_devices_tracker::SHAPED_DEVICES; -use axum::Json; use lqos_config::ShapedDevice; -pub async fn all_shaped_devices() -> Json> { - Json(SHAPED_DEVICES.load().devices.clone()) +pub fn all_shaped_devices_data() -> Vec { + SHAPED_DEVICES.load().devices.clone() } diff --git a/src/rust/lqosd/src/node_manager/local_api/support.rs b/src/rust/lqosd/src/node_manager/local_api/support.rs deleted file mode 100644 index 9a19bdc8..00000000 --- a/src/rust/lqosd/src/node_manager/local_api/support.rs +++ /dev/null @@ -1,8 +0,0 @@ -use axum::Json; -use lqos_support_tool::{SanityChecks, run_sanity_checks}; - -pub async fn run_sanity_check() -> Json { - let mut status = run_sanity_checks(false).expect("Failed to run sanity checks"); - status.results.sort_by(|a, b| a.success.cmp(&b.success)); - Json(status) -} diff --git a/src/rust/lqosd/src/node_manager/local_api/unknown_ips.rs b/src/rust/lqosd/src/node_manager/local_api/unknown_ips.rs index 8f688985..9d6c23da 100644 --- a/src/rust/lqosd/src/node_manager/local_api/unknown_ips.rs +++ b/src/rust/lqosd/src/node_manager/local_api/unknown_ips.rs @@ -9,7 +9,7 @@ use std::collections::HashSet; use std::time::Duration; use tracing::warn; -#[derive(Serialize)] +#[derive(Debug, Serialize)] pub struct UnknownIp { ip: String, last_seen_nanos: u64, @@ -76,11 +76,7 @@ pub fn get_unknown_ips() -> Vec { .collect() } -pub async fn unknown_ips() -> axum::Json> { - axum::Json(get_unknown_ips()) -} - -pub async fn unknown_ips_csv() -> String { +pub fn unknown_ips_csv_data() -> String { let list = get_unknown_ips(); let mut csv = String::new(); @@ -95,24 +91,24 @@ pub async fn unknown_ips_csv() -> String { csv } -#[derive(Serialize)] +#[derive(Debug, Serialize)] pub struct ClearUnknownIpsResponse { cleared: usize, } -pub async fn clear_unknown_ips() -> axum::Json { +pub fn clear_unknown_ips_data() -> ClearUnknownIpsResponse { // Load config and shaped devices to mirror the same filtering logic used for display let Ok(config) = load_config() else { warn!("Failed to load config"); - return axum::Json(ClearUnknownIpsResponse { cleared: 0 }); + return ClearUnknownIpsResponse { cleared: 0 }; }; let Ok(allowed_ips) = config.ip_ranges.allowed_network_table() else { warn!("Could not load allowed IP table"); - return axum::Json(ClearUnknownIpsResponse { cleared: 0 }); + return ClearUnknownIpsResponse { cleared: 0 }; }; let Ok(ignored_ips) = config.ip_ranges.ignored_network_table() else { warn!("Could not load ignored IP table"); - return axum::Json(ClearUnknownIpsResponse { cleared: 0 }); + return ClearUnknownIpsResponse { cleared: 0 }; }; let sd_reader = SHAPED_DEVICES.load(); @@ -120,7 +116,7 @@ pub async fn clear_unknown_ips() -> axum::Json { // Now time for last_seen comparison (match the 5 minute window used in get_unknown_ips) // If the system clock isn't ready yet (very early after boot), do nothing to avoid mass deletion. let Ok(ts) = time_since_boot() else { - return axum::Json(ClearUnknownIpsResponse { cleared: 0 }); + return ClearUnknownIpsResponse { cleared: 0 }; }; let now = Duration::from(ts).as_nanos() as u64; const FIVE_MINUTES_IN_NANOS: u64 = 5 * 60 * 1_000_000_000; @@ -171,5 +167,5 @@ pub async fn clear_unknown_ips() -> axum::Json { } } - axum::Json(ClearUnknownIpsResponse { cleared }) + ClearUnknownIpsResponse { cleared } } diff --git a/src/rust/lqosd/src/node_manager/local_api/urgent.rs b/src/rust/lqosd/src/node_manager/local_api/urgent.rs index 1527e84f..5b0ff3d5 100644 --- a/src/rust/lqosd/src/node_manager/local_api/urgent.rs +++ b/src/rust/lqosd/src/node_manager/local_api/urgent.rs @@ -1,6 +1,3 @@ -use axum::Json; -use axum::extract::Path; -use axum::http::StatusCode; use serde::Serialize; use crate::urgent; @@ -61,13 +58,13 @@ fn strip_ansi(input: &str) -> String { out } -#[derive(Serialize)] +#[derive(Debug, Serialize)] pub struct UrgentStatus { pub has_urgent: bool, pub count: usize, } -#[derive(Serialize)] +#[derive(Debug, Serialize)] pub struct UrgentItem { pub id: u64, pub ts: u64, @@ -78,23 +75,20 @@ pub struct UrgentItem { pub context: Option, } -#[derive(Serialize)] +#[derive(Debug, Serialize)] pub struct UrgentList { pub items: Vec, } -pub async fn urgent_status() -> (StatusCode, Json) { +pub fn urgent_status_data() -> UrgentStatus { let items = urgent::list(); - ( - StatusCode::OK, - Json(UrgentStatus { - has_urgent: !items.is_empty(), - count: items.len(), - }), - ) + UrgentStatus { + has_urgent: !items.is_empty(), + count: items.len(), + } } -pub async fn urgent_list() -> (StatusCode, Json) { +pub fn urgent_list_data() -> UrgentList { let items = urgent::list(); let items: Vec = items .into_iter() @@ -108,19 +102,13 @@ pub async fn urgent_list() -> (StatusCode, Json) { context: i.context, }) .collect(); - (StatusCode::OK, Json(UrgentList { items })) + UrgentList { items } } -pub async fn urgent_clear(Path(id): Path) -> (StatusCode, &'static str) { - let ok = urgent::clear(id); - if ok { - (StatusCode::OK, "OK") - } else { - (StatusCode::NOT_FOUND, "NOT_FOUND") - } +pub fn urgent_clear_id(id: u64) -> bool { + urgent::clear(id) } -pub async fn urgent_clear_all() -> (StatusCode, &'static str) { +pub fn urgent_clear_all_data() { urgent::clear_all(); - (StatusCode::OK, "OK") } diff --git a/src/rust/lqosd/src/node_manager/local_api/version_check.rs b/src/rust/lqosd/src/node_manager/local_api/version_check.rs deleted file mode 100644 index f865f289..00000000 --- a/src/rust/lqosd/src/node_manager/local_api/version_check.rs +++ /dev/null @@ -1,64 +0,0 @@ -use axum::Json; -use lqos_config::load_config; -use lqos_utils::unix_time::unix_now; -use serde::{Deserialize, Serialize}; -use std::sync::atomic::AtomicU64; -use tracing::error; - -static LAST_VERSION_CHECK: AtomicU64 = AtomicU64::new(0); -const ONE_HOUR_SECONDS: u64 = 60 * 60; -const VERSION_STRING: &str = include_str!("../../../../../VERSION_STRING"); - -#[derive(Serialize)] -struct VersionCheckRequest { - current_git_hash: String, - version_string: String, - node_id: String, -} - -#[derive(Deserialize, Debug)] -pub struct VersionCheckResponse { - update_available: bool, -} - -async fn send_version_check() -> anyhow::Result { - if let Ok(cfg) = load_config() { - let current_hash = env!("GIT_HASH"); - let request = VersionCheckRequest { - current_git_hash: current_hash.to_string(), - version_string: VERSION_STRING.to_string(), - node_id: cfg.node_id.to_string(), - }; - let response = reqwest::Client::new() - .post("https://insight.libreqos.com/shaper_api/version_check") - .json(&request) - .send() - .await? - .json() - .await?; - - Ok(response) - } else { - anyhow::bail!("No config"); - } -} - -pub async fn version_check() -> Json { - let last_check = LAST_VERSION_CHECK.load(std::sync::atomic::Ordering::Relaxed); - if let Ok(now) = unix_now() { - if now > last_check + ONE_HOUR_SECONDS { - let res = send_version_check().await; - if let Ok(response) = send_version_check().await { - LAST_VERSION_CHECK.store(now, std::sync::atomic::Ordering::Relaxed); - - if response.update_available { - return Json(String::from("Update available")); - } - } else { - error!("Unable to send version check"); - error!("{res:?}"); - } - } - } - Json(String::from("All Good")) -} diff --git a/src/rust/lqosd/src/node_manager/local_api/warnings.rs b/src/rust/lqosd/src/node_manager/local_api/warnings.rs index b723aea0..3519e928 100644 --- a/src/rust/lqosd/src/node_manager/local_api/warnings.rs +++ b/src/rust/lqosd/src/node_manager/local_api/warnings.rs @@ -1,20 +1,5 @@ use crate::node_manager::WarningLevel; -use axum::Json; -use tracing::{error, info}; -pub async fn get_global_warnings() -> Json> { - let mut warnings = crate::node_manager::warnings::get_global_warnings(); - - info!("Sanity checking configuration..."); - - if let Ok(support_sanity) = lqos_support_tool::run_sanity_checks(false) { - let found_warnings = support_sanity.results.iter().any(|c| !c.success); - if found_warnings { - warnings.push((WarningLevel::Error, "Support tool sanity checks failed. Please run the support tool.".to_string())); - } - } else { - error!("Failed to run support tool sanity checks"); - } - - Json(warnings) +pub async fn global_warnings_data() -> Vec<(WarningLevel, String)> { + crate::node_manager::warnings::get_global_warnings() } diff --git a/src/rust/lqosd/src/node_manager/run.rs b/src/rust/lqosd/src/node_manager/run.rs index 9a109a4b..ed4ccb93 100644 --- a/src/rust/lqosd/src/node_manager/run.rs +++ b/src/rust/lqosd/src/node_manager/run.rs @@ -57,7 +57,12 @@ pub async fn spawn_webserver( .route("/health", get(health_check)) .nest( "/websocket/", - websocket_router(bus_tx.clone(), system_usage_tx.clone(), control_tx.clone()), + websocket_router( + bus_tx.clone(), + system_usage_tx.clone(), + control_tx.clone(), + shaper_tx.clone(), + ), ) .nest("/vendor", vendor_route()?) // Serve /vendor as purely static .nest("/", static_routes()?) diff --git a/src/rust/lqosd/src/node_manager/static2/help.html b/src/rust/lqosd/src/node_manager/static2/help.html index 56ffd2f5..d02a7d0f 100644 --- a/src/rust/lqosd/src/node_manager/static2/help.html +++ b/src/rust/lqosd/src/node_manager/static2/help.html @@ -76,9 +76,8 @@
Tools

- Sanity check reads your configuration and looks for common issues. This should be - your first step when troubleshooting the system.
- + Support tool retired. The legacy support tool and sanity checks are no longer + available in the UI. Use the configuration pages and logs when troubleshooting.

@@ -87,23 +86,6 @@
- - - + diff --git a/src/rust/lqosd/src/node_manager/static2/template.html b/src/rust/lqosd/src/node_manager/static2/template.html index ce56180d..6b7552e8 100644 --- a/src/rust/lqosd/src/node_manager/static2/template.html +++ b/src/rust/lqosd/src/node_manager/static2/template.html @@ -18,6 +18,7 @@ %%%LTS_SCRIPT%%% +
@@ -258,102 +259,9 @@ document.getElementById('year').textContent = new Date().getFullYear(); - // Urgent Issues: poll status, update badge, and show modal with details - (function(){ - const containerId = 'urgentStatus'; - const linkId = 'urgentStatusLink'; - const badgeId = 'urgentBadge'; - - function ensurePlaceholder(){ - // no-op: server injects a placeholder; if not present, skip - return document.getElementById(containerId) !== null; - } - - function renderStatus(count){ - const cont = document.getElementById(containerId); - if (!cont) return; - const cls = count > 0 ? 'text-danger' : 'text-secondary'; - const icon = count > 0 ? 'fa-bell' : 'fa-bell-slash'; - cont.innerHTML = ` - - Urgent Issues - ${count} - `; - $("#"+containerId).off("click").on("click", `#${linkId}`, (e)=>{ - e.preventDefault(); - showModal(); - }); - } - - function poll(){ - if (!ensurePlaceholder()) return; - $.get('/local-api/urgent/status', (res)=>{ - renderStatus(res.count||0); - }); - } - - function showModal(){ - const modalEl = document.getElementById('urgentModal'); - if (!modalEl) return; - new bootstrap.Modal(modalEl,{focus:true}).show(); - const holder = document.getElementById('urgentListContainer'); - holder.innerHTML = `
Loading...
`; - $.get('/local-api/urgent/list', (res)=>{ - const items = res.items||[]; - if (items.length===0){ holder.innerHTML = '
No urgent issues.
'; return; } - const table = document.createElement('table'); - table.className = 'table table-sm table-striped'; - const tbody = document.createElement('tbody'); - items.forEach(it=>{ - const tr = document.createElement('tr'); - const td = document.createElement('td'); - const when = new Date(it.ts*1000).toLocaleString(); - const sev = it.severity === 'Error' ? 'danger' : 'warning'; - td.innerHTML = ` -
- ${it.severity} - ${it.code} - (${it.source}) - ${when} - -
-
${it.message}
- ${it.context?`
${it.context}
`:''} - `; - tr.appendChild(td); - tbody.appendChild(tr); - }); - table.appendChild(tbody); - // Clear existing content and insert table - holder.innerHTML = ''; - holder.appendChild(table); - // Bind clear buttons (acknowledge) - $(holder).off('click').on('click','a.urgent-clear', function(e){ - e.preventDefault(); - const id = $(this).data('id'); - $.post(`/local-api/urgent/clear/${id}`, ()=>{ showModal(); poll(); }); - }); - }).fail(()=>{ - holder.innerHTML = '
Failed to load urgent issues.
'; - }); - } - - // Initial placeholder in case server didn’t inject content (defensive) - if (!document.getElementById(containerId)){ - const ul = document.querySelector('.sidebar .navbar-nav'); - if (ul){ - const li = document.createElement('li'); li.className='nav-item'; li.id=containerId; ul.appendChild(li); - } - } - // Clear all action - $(document).off('click','#urgentClearAll').on('click','#urgentClearAll', function(){ - $.post('/local-api/urgent/clear_all', ()=>{ showModal(); poll(); }); - }); - - // Start polling - poll(); - setInterval(poll, 30000); - })(); + if (window.lqosInitUrgentIssues) { + window.lqosInitUrgentIssues(); + } diff --git a/src/rust/lqosd/src/node_manager/template.rs b/src/rust/lqosd/src/node_manager/template.rs index 8734ff59..5dd650c5 100644 --- a/src/rust/lqosd/src/node_manager/template.rs +++ b/src/rust/lqosd/src/node_manager/template.rs @@ -168,9 +168,10 @@ pub async fn apply_templates( .await .expect("Cannot read template bytes"); let byte_string = String::from_utf8_lossy(&bytes).to_string(); + let version_string = VERSION_STRING.trim(); let byte_string = template_text .replace("%%BODY%%", &byte_string) - .replace("%%VERSION%%", VERSION_STRING) + .replace("%%VERSION%%", version_string) .replace("%%TITLE%%", &title) .replace("%%LTS_LINK%%", &trial_link) .replace("%%%LTS_SCRIPT%%%", <s_script) diff --git a/src/rust/lqosd/src/node_manager/warnings.rs b/src/rust/lqosd/src/node_manager/warnings.rs index 1ed5906a..14da09ba 100644 --- a/src/rust/lqosd/src/node_manager/warnings.rs +++ b/src/rust/lqosd/src/node_manager/warnings.rs @@ -1,10 +1,10 @@ -//! A place to store warnings from sanity checks, the need to reload LibreQoS and similar. +//! A place to store warnings from system checks, the need to reload LibreQoS and similar. use parking_lot::Mutex; use serde::Serialize; #[allow(dead_code)] -#[derive(Serialize, Copy, Clone)] +#[derive(Serialize, Debug, Copy, Clone)] pub enum WarningLevel { Info, Warning, diff --git a/src/rust/lqosd/src/node_manager/ws.rs b/src/rust/lqosd/src/node_manager/ws.rs index ba3a932c..0115271b 100644 --- a/src/rust/lqosd/src/node_manager/ws.rs +++ b/src/rust/lqosd/src/node_manager/ws.rs @@ -1,21 +1,23 @@ -//! Websocket handling for the node manager. This module provides a websocket router that can be mounted in the main application. -//! There are two major types of websocket connection supported: -//! * General websocket connections that allow for subscribing to multiple channels, using the `/ws` route. -//! * Private websocket connections that allow for subscribing to a single channel, using the `/private_ws` route. -//! -//! General websocket connections are multi-user, and based on a time-based "ticker". They send out updates -//! to all subscribers at a regular interval, sharing the latest information about the system. -//! -//! Private websocket connections are single-user, and are used for more specific information. They are used -//! for things like monitoring a specific user, or for receiving updates about a specific user. +//! Websocket handling for the node manager. This module provides a websocket router that can be mounted in +//! the main application. Websocket connections are multi-user, and based on a time-based "ticker". They send +//! out updates to all subscribers at a regular interval, sharing the latest information about the system. //! +//! Private websocket commands are routed through the same `/ws` entrypoint as pubsub subscriptions. //! Both types of websocket are authenticated using the auth layer. -use std::collections::HashSet; -use std::str::FromStr; +use std::collections::{BTreeMap, HashSet}; use std::sync::Arc; -use crate::node_manager::auth::auth_layer; +use crate::node_manager::auth::{LoginResult, login_from_token}; +use crate::node_manager::local_api::{ + circuit, circuit_count, config, cpu_affinity, dashboard_themes, device_counts, flow_explorer, + flow_map, lts, network_tree, packet_analysis, reload_libreqos, scheduler, search, + shaped_device_api, unknown_ips, urgent, warnings, +}; +use crate::node_manager::shaper_queries_actor::ShaperQueryCommand; +use crate::node_manager::ws::messages::{ + WsHello, WsHelloReply, WsRequest, WsResponse, encode_ws_message, WS_HANDSHAKE_REQUIREMENT, +}; use crate::node_manager::ws::publish_subscribe::PubSub; use crate::node_manager::ws::published_channels::PublishedChannels; use crate::node_manager::ws::ticker::channel_ticker; @@ -26,29 +28,60 @@ use axum::{ WebSocketUpgrade, ws::{Message, WebSocket}, }, + http::{HeaderMap, StatusCode, header}, response::IntoResponse, routing::get, }; use lqos_bus::BusRequest; -use serde::Deserialize; use tokio::sync::mpsc::Sender; -use tracing::debug; +use serde_cbor::Value as CborValue; +use tracing::{info, warn}; mod publish_subscribe; mod published_channels; +pub(crate) mod messages; mod single_user_channels; mod ticker; -/// Provides an Axum router for the websocket system. Exposes two routes: -/// * /ws: A general websocket route that allows for subscribing to multiple channels -/// * /private_ws: A private websocket route that allows for subscribing to a single channel -/// -/// Returns a router that can be mounted in the main application. +const WS_VERSION: &str = include_str!("../../../../VERSION_STRING"); +const HANDSHAKE_TIMEOUT_SECS: u64 = 10; + +fn log_expected_cbor_payloads() { + let subscribe = WsRequest::Subscribe { + channel: PublishedChannels::Cadence, + }; + if let Ok(payload) = serde_cbor::to_vec(&subscribe) { + let hex = payload_prefix_hex(&payload, payload.len()); + info!( + "WS expected CBOR Subscribe(Cadence): len {}, hex {}", + payload.len(), + hex + ); + } + + let hello_reply = WsRequest::HelloReply(WsHelloReply { + ack: WS_HANDSHAKE_REQUIREMENT.to_string(), + token: "TOKEN".to_string(), + }); + if let Ok(payload) = serde_cbor::to_vec(&hello_reply) { + let hex = payload_prefix_hex(&payload, payload.len()); + info!( + "WS expected CBOR HelloReply: len {}, hex {}", + payload.len(), + hex + ); + } +} + +/// Provides an Axum router for the websocket system. Exposes a single /ws route that supports +/// pubsub subscriptions and private commands. pub fn websocket_router( bus_tx: Sender<(tokio::sync::oneshot::Sender, BusRequest)>, system_usage_tx: crossbeam_channel::Sender>, control_tx: tokio::sync::mpsc::Sender, + shaper_query: Sender, ) -> Router { + log_expected_cbor_payloads(); let channels = PubSub::new(); tokio::spawn(channel_ticker( channels.clone(), @@ -56,52 +89,121 @@ pub fn websocket_router( system_usage_tx.clone(), )); Router::new() - .route( - "/private_ws", - get(single_user_channels::private_channel_ws_handler), - ) .route("/ws", get(ws_handler)) - .route_layer(axum::middleware::from_fn(auth_layer)) .layer(Extension(channels)) .layer(Extension(bus_tx.clone())) .layer(Extension(control_tx.clone())) + .layer(Extension(shaper_query.clone())) } async fn ws_handler( ws: WebSocketUpgrade, Extension(channels): Extension>, + Extension(bus_tx): Extension< + Sender<(tokio::sync::oneshot::Sender, BusRequest)>, + >, + Extension(control_tx): Extension< + tokio::sync::mpsc::Sender, + >, + Extension(shaper_query): Extension>, + headers: HeaderMap, ) -> impl IntoResponse { - debug!("WS Upgrade Called"); + let has_cookie = headers.contains_key(header::COOKIE); + let user_agent = headers + .get(header::USER_AGENT) + .and_then(|h| h.to_str().ok()) + .unwrap_or("unknown"); + info!( + "WS upgrade requested (cookie present: {has_cookie}, ua: {user_agent})" + ); let channels = channels.clone(); - ws.on_upgrade(move |socket| async { - handle_socket(socket, channels).await; + let browser_language = headers + .get(header::ACCEPT_LANGUAGE) + .and_then(|h| h.to_str().ok()) + .map(|s| s.to_string()); + ws.on_upgrade(move |socket| async move { + handle_socket( + socket, + channels, + bus_tx, + control_tx, + shaper_query, + browser_language, + ) + .await; }) } -#[derive(Deserialize)] -struct Subscribe { - channel: String, -} - -async fn handle_socket(mut socket: WebSocket, channels: Arc) { - debug!("Websocket connected"); +async fn handle_socket( + mut socket: WebSocket, + channels: Arc, + bus_tx: Sender<(tokio::sync::oneshot::Sender, BusRequest)>, + control_tx: tokio::sync::mpsc::Sender, + shaper_query: Sender, + browser_language: Option, +) { + info!("Websocket connected"); - let (tx, mut rx) = tokio::sync::mpsc::channel::>(128); + let (tx, mut rx) = tokio::sync::mpsc::channel::>>(128); let mut subscribed_channels = HashSet::new(); + let mut handshake_complete = false; + let mut login = LoginResult::Denied; + let handshake_timeout = tokio::time::sleep(std::time::Duration::from_secs( + HANDSHAKE_TIMEOUT_SECS, + )); + tokio::pin!(handshake_timeout); + + let hello = WsResponse::Hello { + hello: WsHello { + version: WS_VERSION.trim().to_string(), + requirement: WS_HANDSHAKE_REQUIREMENT.to_string(), + }, + }; + if let Ok(payload) = encode_ws_message(&hello) { + if socket.send(Message::Binary((*payload).clone())).await.is_err() { + return; + } + } else { + return; + } + + let mut private_state = + single_user_channels::PrivateState::new(tx.clone(), bus_tx, control_tx, browser_language); loop { tokio::select! { + _ = &mut handshake_timeout, if !handshake_complete => { + warn!("Websocket handshake timed out"); + break; + } inbound = socket.recv() => { // Received a websocket message match inbound { - Some(Ok(msg)) => receive_channel_message(msg, channels.clone(), tx.clone(), &mut subscribed_channels).await, - Some(Err(_)) => break, // The channel has closed + Some(Ok(msg)) => { + let should_close = receive_channel_message( + msg, + channels.clone(), + tx.clone(), + &mut subscribed_channels, + &mut handshake_complete, + &mut private_state, + &mut login, + shaper_query.clone(), + ).await; + if should_close { + break; + } + } + Some(Err(err)) => { + warn!("Websocket recv error: {err}"); + break; + } None => break, // The channel has closed } } outbound = rx.recv() => { match outbound { Some(msg) => { - if let Err(_) = socket.send(Message::Text((*msg).clone())).await { + if let Err(_) = socket.send(Message::Binary((*msg).clone())).await { // The outbound websocket has closed. That's ok, it's not // an error. We're relying on *this* task terminating to in // turn close the subscription channel, which will in turn @@ -116,23 +218,1005 @@ async fn handle_socket(mut socket: WebSocket, channels: Arc) { } } } - debug!("Websocket disconnected"); + info!("Websocket disconnected"); } async fn receive_channel_message( msg: Message, channels: Arc, - tx: Sender>, + tx: Sender>>, subscribed_channels: &mut HashSet, -) { - if let Ok(text) = msg.to_text() { - if let Ok(sub) = serde_json::from_str::(text) { - if let Ok(channel) = PublishedChannels::from_str(&sub.channel) { - if !subscribed_channels.contains(&channel) { - channels.subscribe(channel, tx.clone()).await; - subscribed_channels.insert(channel); + handshake_complete: &mut bool, + private_state: &mut single_user_channels::PrivateState, + login: &mut LoginResult, + shaper_query: Sender, +) -> bool { + let payload = match msg { + Message::Binary(data) => data, + Message::Text(text) => { + warn!( + "Websocket text message received (len {}, hint {})", + text.len(), + payload_hint(text.as_bytes()) + ); + return true; + } + Message::Ping(_) | Message::Pong(_) => { + return false; + } + Message::Close(frame) => { + warn!("Websocket close frame received: {:?}", frame); + return true; + } + }; + + let request = match decode_ws_request(&payload) { + Ok(request) => request, + Err(err) => { + let prefix = payload_prefix_hex(&payload, 24); + let hint = payload_hint(&payload); + warn!( + "Websocket decode failed: {err} (len {}, prefix {prefix}, hint {hint})", + payload.len() + ); + return true; + } + }; + + if !*handshake_complete { + if let WsRequest::HelloReply(reply) = request { + if reply.ack != WS_HANDSHAKE_REQUIREMENT { + warn!("Websocket handshake ack mismatch"); + return true; + } + let token = reply.token.trim(); + let login_result = login_from_token(token).await; + if login_result == LoginResult::Denied { + warn!("Websocket handshake token rejected"); + return true; + } + *login = login_result; + *handshake_complete = true; + info!("Websocket handshake completed"); + return false; + } + warn!("Websocket message received before handshake complete"); + return true; + } + + match request { + WsRequest::Subscribe { channel } => { + if !subscribed_channels.contains(&channel) { + channels.subscribe(channel, tx.clone()).await; + subscribed_channels.insert(channel); + } + } + WsRequest::Unsubscribe { channel } => { + subscribed_channels.remove(&channel); + } + WsRequest::Private(command) => { + private_state.handle_request(command).await; + } + WsRequest::DashletThemes => { + let response = WsResponse::DashletThemes { + entries: dashboard_themes::list_theme_entries(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::DashletSave { name, entries } => { + let data = dashboard_themes::DashletSave { name, entries }; + let result = dashboard_themes::save_theme_data(&data); + let response = match result { + Ok(_) => WsResponse::DashletSaveResult { + ok: true, + error: None, + }, + Err(err) => WsResponse::DashletSaveResult { + ok: false, + error: Some(err), + }, + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::DashletGet { name } => { + let entries = dashboard_themes::load_theme_entries(&name); + let response = WsResponse::DashletTheme { name, entries }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::DashletDelete { name } => { + let result = dashboard_themes::delete_theme_file(&name); + let response = match result { + Ok(_) => WsResponse::DashletDeleteResult { + ok: true, + error: None, + }, + Err(err) => WsResponse::DashletDeleteResult { + ok: false, + error: Some(err), + }, + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::SchedulerStatus => { + let response = WsResponse::SchedulerStatus { + data: scheduler::scheduler_status_data(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::SchedulerDetails => { + let response = WsResponse::SchedulerDetails { + data: scheduler::scheduler_details_data(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::DeviceCount => { + let response = WsResponse::DeviceCount { + data: device_counts::device_count(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::DevicesAll => { + let response = WsResponse::DevicesAll { + data: shaped_device_api::all_shaped_devices_data(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::NetworkTree => { + let response = WsResponse::NetworkTree { + data: network_tree::network_tree_data(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::FlowMap => { + let response = WsResponse::FlowMap { + data: flow_map::flow_map_data(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::CircuitById { id } => { + let (ok, devices) = match circuit::circuit_by_id_data(&id) { + Some(devices) => (true, devices), + None => (false, Vec::new()), + }; + let response = WsResponse::CircuitByIdResult { id, devices, ok }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::RequestAnalysis { ip } => { + let response = WsResponse::RequestAnalysisResult { + data: packet_analysis::request_analysis_data(&ip), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::CpuAffinitySummary => { + let response = WsResponse::CpuAffinitySummary { + data: cpu_affinity::cpu_affinity_summary_data(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::CpuAffinityCircuits { + cpu, + direction, + page, + page_size, + search, + } => { + let query = cpu_affinity::CircuitsQuery { + direction, + page, + page_size, + search, + }; + let response = WsResponse::CpuAffinityCircuits { + data: cpu_affinity::cpu_affinity_circuits_data(cpu, query), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::CpuAffinityCircuitsAll { direction, search } => { + let query = cpu_affinity::CircuitsQuery { + direction, + page: None, + page_size: None, + search, + }; + let response = WsResponse::CpuAffinityCircuitsAll { + data: cpu_affinity::cpu_affinity_circuits_all_data(query), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::CpuAffinityPreviewWeights { direction, search } => { + let query = cpu_affinity::CircuitsQuery { + direction, + page: None, + page_size: None, + search, + }; + let response = WsResponse::CpuAffinityPreviewWeights { + data: cpu_affinity::cpu_affinity_preview_weights_data(query), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::AsnList => { + let response = WsResponse::AsnList { + data: flow_explorer::asn_list_data(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::CountryList => { + let response = WsResponse::CountryList { + data: flow_explorer::country_list_data(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::ProtocolList => { + let response = WsResponse::ProtocolList { + data: flow_explorer::protocol_list_data(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::AsnFlowTimeline { asn } => { + let response = WsResponse::AsnFlowTimeline { + asn, + data: flow_explorer::flow_timeline_data(asn), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::CountryFlowTimeline { iso_code } => { + let response = WsResponse::CountryFlowTimeline { + iso_code: iso_code.clone(), + data: flow_explorer::country_timeline_data(&iso_code), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::ProtocolFlowTimeline { protocol } => { + let response = WsResponse::ProtocolFlowTimeline { + protocol: protocol.clone(), + data: flow_explorer::protocol_timeline_data(&protocol), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::GlobalWarnings => { + let data = warnings::global_warnings_data().await; + let response = WsResponse::GlobalWarnings { data }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::UrgentStatus => { + let response = WsResponse::UrgentStatus { + data: urgent::urgent_status_data(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::UrgentList => { + let response = WsResponse::UrgentList { + data: urgent::urgent_list_data(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::UrgentClear { id } => { + let ok = urgent::urgent_clear_id(id); + let response = WsResponse::UrgentClearResult { ok }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::UrgentClearAll => { + urgent::urgent_clear_all_data(); + let response = WsResponse::UrgentClearAllResult { ok: true }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::UnknownIps => { + let response = WsResponse::UnknownIps { + data: unknown_ips::get_unknown_ips(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::UnknownIpsClear => { + let response = WsResponse::UnknownIpsCleared { + data: unknown_ips::clear_unknown_ips_data(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::UnknownIpsCsv => { + let response = WsResponse::UnknownIpsCsv { + csv: unknown_ips::unknown_ips_csv_data(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::Search { term } => { + let results = search::search_results(search::SearchRequest { term: term.clone() }).await; + let response = WsResponse::SearchResults { term, results }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::ReloadLibreQoS => { + let message = reload_libreqos::reload_libreqos_with_login(*login).await; + let response = WsResponse::ReloadResult { message }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::LtsTrialConfig => { + match lts::lts_trial_config_data(*login) { + Ok(data) => { + let response = WsResponse::LtsTrialConfigResult { data }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(StatusCode::FORBIDDEN) => { + let response = WsResponse::Error { + message: "Unauthorized".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(_) => { + let response = WsResponse::Error { + message: "Unable to load LTS config".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + } + } + WsRequest::CircuitCount => { + let response = WsResponse::CircuitCountResult { + data: circuit_count::circuit_count_data(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::LtsSignUp { license_key } => { + let result = lts::lts_trial_signup_data(license_key).await; + let (ok, message) = match result { + Ok(()) => (true, "Ok".to_string()), + Err(StatusCode::INTERNAL_SERVER_ERROR) => (false, "Invalid license key".to_string()), + Err(StatusCode::FORBIDDEN) => (false, "Unauthorized".to_string()), + Err(_) => (false, "Error".to_string()), + }; + let response = WsResponse::LtsSignUpResult { ok, message }; + if send_ws_response(&tx, response).await { + return true; + } + if ok { + tokio::spawn(async { + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + std::process::exit(0); + }); + } + } + WsRequest::LtsShaperStatus => { + match lts::shaper_status_data().await { + Ok(data) => { + let response = WsResponse::LtsShaperStatus { data }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(StatusCode::FORBIDDEN) => { + let response = WsResponse::Error { + message: "Insight not enabled".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(_) => { + let response = WsResponse::Error { + message: "Unable to load shaper status".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + } + } + WsRequest::LtsThroughput { seconds } => { + match lts::throughput_period_data(shaper_query.clone(), seconds).await { + Ok(data) => { + let response = WsResponse::LtsThroughput { seconds, data }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(StatusCode::FORBIDDEN) => { + let response = WsResponse::Error { + message: "Insight not enabled".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(_) => { + let response = WsResponse::Error { + message: "Unable to load throughput".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + } + } + WsRequest::LtsPackets { seconds } => { + match lts::packets_period_data(shaper_query.clone(), seconds).await { + Ok(data) => { + let response = WsResponse::LtsPackets { seconds, data }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(StatusCode::FORBIDDEN) => { + let response = WsResponse::Error { + message: "Insight not enabled".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(_) => { + let response = WsResponse::Error { + message: "Unable to load packets".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + } + } + WsRequest::LtsPercentShaped { seconds } => { + match lts::percent_shaped_period_data(shaper_query.clone(), seconds).await { + Ok(data) => { + let response = WsResponse::LtsPercentShaped { seconds, data }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(StatusCode::FORBIDDEN) => { + let response = WsResponse::Error { + message: "Insight not enabled".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(_) => { + let response = WsResponse::Error { + message: "Unable to load percent shaped".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } } } } + WsRequest::LtsFlows { seconds } => { + match lts::percent_flows_period_data(shaper_query.clone(), seconds).await { + Ok(data) => { + let response = WsResponse::LtsFlows { seconds, data }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(StatusCode::FORBIDDEN) => { + let response = WsResponse::Error { + message: "Insight not enabled".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(_) => { + let response = WsResponse::Error { + message: "Unable to load flows".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + } + } + WsRequest::LtsCake { seconds } => { + match lts::cake_period_data(shaper_query.clone(), seconds).await { + Ok(data) => { + let response = WsResponse::LtsCake { seconds, data }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(StatusCode::FORBIDDEN) => { + let response = WsResponse::Error { + message: "Insight not enabled".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(_) => { + let response = WsResponse::Error { + message: "Unable to load cake stats".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + } + } + WsRequest::LtsRttHisto { seconds } => { + match lts::rtt_histo_period_data(shaper_query.clone(), seconds).await { + Ok(data) => { + let response = WsResponse::LtsRttHisto { seconds, data }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(StatusCode::FORBIDDEN) => { + let response = WsResponse::Error { + message: "Insight not enabled".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(_) => { + let response = WsResponse::Error { + message: "Unable to load RTT histogram".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + } + } + WsRequest::LtsTop10Downloaders { seconds } => { + match lts::top10_downloaders_period_data(shaper_query.clone(), seconds).await { + Ok(data) => { + let response = WsResponse::LtsTop10Downloaders { seconds, data }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(StatusCode::FORBIDDEN) => { + let response = WsResponse::Error { + message: "Insight not enabled".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(_) => { + let response = WsResponse::Error { + message: "Unable to load top downloaders".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + } + } + WsRequest::LtsWorst10Rtt { seconds } => { + match lts::worst10_rtt_period_data(shaper_query.clone(), seconds).await { + Ok(data) => { + let response = WsResponse::LtsWorst10Rtt { seconds, data }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(StatusCode::FORBIDDEN) => { + let response = WsResponse::Error { + message: "Insight not enabled".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(_) => { + let response = WsResponse::Error { + message: "Unable to load worst RTT".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + } + } + WsRequest::LtsWorst10Rxmit { seconds } => { + match lts::worst10_rxmit_period_data(shaper_query.clone(), seconds).await { + Ok(data) => { + let response = WsResponse::LtsWorst10Rxmit { seconds, data }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(StatusCode::FORBIDDEN) => { + let response = WsResponse::Error { + message: "Insight not enabled".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(_) => { + let response = WsResponse::Error { + message: "Unable to load worst retransmits".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + } + } + WsRequest::LtsTopFlows { seconds } => { + match lts::top10_flows_period_data(shaper_query.clone(), seconds).await { + Ok(data) => { + let response = WsResponse::LtsTopFlows { seconds, data }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(StatusCode::FORBIDDEN) => { + let response = WsResponse::Error { + message: "Insight not enabled".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(_) => { + let response = WsResponse::Error { + message: "Unable to load top flows".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + } + } + WsRequest::LtsRecentMedian => { + match lts::recent_medians_data(shaper_query.clone()).await { + Ok(data) => { + let response = WsResponse::LtsRecentMedian { data }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(StatusCode::FORBIDDEN) => { + let response = WsResponse::Error { + message: "Insight not enabled".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(_) => { + let response = WsResponse::Error { + message: "Unable to load medians".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + } + } + WsRequest::AdminCheck => { + let response = WsResponse::AdminCheck { + ok: config::admin_check_data(*login), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::GetConfig => { + match config::get_config_data(*login) { + Ok(data) => { + let response = WsResponse::GetConfig { data }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(StatusCode::FORBIDDEN) => { + let response = WsResponse::Error { + message: "Unauthorized".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(_) => { + let response = WsResponse::Error { + message: "Unable to load config".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + } + } + WsRequest::UpdateConfig { config: cfg } => { + let result = config::update_lqosd_config_data(*login, cfg).await; + let (ok, message) = match result { + Ok(()) => (true, "Ok".to_string()), + Err(StatusCode::FORBIDDEN) => (false, "Unauthorized".to_string()), + Err(_) => (false, "Error".to_string()), + }; + let response = WsResponse::UpdateConfigResult { ok, message }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::UpdateNetworkAndDevices { + network_json, + shaped_devices, + } => { + let result = config::update_network_and_devices_data( + *login, + network_json, + shaped_devices, + ); + let (ok, message) = match result { + Ok(()) => (true, "Ok".to_string()), + Err(StatusCode::FORBIDDEN) => (false, "Unauthorized".to_string()), + Err(_) => (false, "Error".to_string()), + }; + let response = WsResponse::UpdateNetworkAndDevicesResult { ok, message }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::ListNics => { + match config::list_nics_data(*login) { + Ok(data) => { + let response = WsResponse::ListNics { data }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(StatusCode::FORBIDDEN) => { + let response = WsResponse::Error { + message: "Unauthorized".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(_) => { + let response = WsResponse::Error { + message: "Unable to list NICs".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + } + } + WsRequest::NetworkJson => { + let response = WsResponse::NetworkJson { + data: config::network_json_data(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::AllShapedDevices => { + let response = WsResponse::AllShapedDevices { + data: config::all_shaped_devices_data(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::GetUsers => { + match config::get_users_data(*login) { + Ok(data) => { + let response = WsResponse::GetUsers { data }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(StatusCode::FORBIDDEN) => { + let response = WsResponse::Error { + message: "Unauthorized".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + Err(_) => { + let response = WsResponse::Error { + message: "Unable to load users".to_string(), + }; + if send_ws_response(&tx, response).await { + return true; + } + } + } + } + WsRequest::AddUser { + username, + password, + role, + } => { + let result = config::add_user_data( + *login, + config::UserRequest { + username, + password, + role, + }, + ); + let (ok, message) = match result { + Ok(message) => (true, message), + Err(StatusCode::FORBIDDEN) => (false, "Unauthorized".to_string()), + Err(StatusCode::BAD_REQUEST) => (false, "Invalid user data".to_string()), + Err(_) => (false, "Error".to_string()), + }; + let response = WsResponse::AddUserResult { ok, message }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::UpdateUser { + username, + password, + role, + } => { + let result = config::update_user_data( + *login, + config::UserRequest { + username, + password, + role, + }, + ); + let (ok, message) = match result { + Ok(message) => (true, message), + Err(StatusCode::FORBIDDEN) => (false, "Unauthorized".to_string()), + Err(StatusCode::BAD_REQUEST) => (false, "Invalid user data".to_string()), + Err(_) => (false, "Error".to_string()), + }; + let response = WsResponse::UpdateUserResult { ok, message }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::DeleteUser { username } => { + let result = config::delete_user_data(*login, username); + let (ok, message) = match result { + Ok(message) => (true, message), + Err(StatusCode::FORBIDDEN) => (false, "Unauthorized".to_string()), + Err(StatusCode::BAD_REQUEST) => (false, "Invalid user data".to_string()), + Err(_) => (false, "Error".to_string()), + }; + let response = WsResponse::DeleteUserResult { ok, message }; + if send_ws_response(&tx, response).await { + return true; + } + } + WsRequest::HelloReply(_) => {} + } + false +} + +async fn send_ws_response(tx: &Sender>>, response: WsResponse) -> bool { + let payload = match encode_ws_message(&response) { + Ok(payload) => payload, + Err(_) => return true, + }; + tx.send(payload).await.is_err() +} + +fn decode_ws_request(payload: &[u8]) -> Result { + let prefix = payload_prefix_hex(payload, 24); + let hint = payload_hint(payload); + match serde_cbor::from_slice::(payload) { + Ok(request) => Ok(request), + Err(err) => { + if let Ok(CborValue::Map(map)) = serde_cbor::from_slice::(payload) { + if map.len() == 1 { + let (key, value) = map.into_iter().next().unwrap(); + if matches!(value, CborValue::Map(ref inner) if inner.is_empty()) { + let mut normalized_map = BTreeMap::new(); + normalized_map.insert(key, CborValue::Null); + let normalized = CborValue::Map(normalized_map); + if let Ok(request) = + serde_cbor::value::from_value::(normalized) + { + return Ok(request); + } + } + } + } + Err(format!( + "{err} (len {}, prefix {prefix}, hint {hint})", + payload.len() + )) + } + } +} + +fn payload_prefix_hex(payload: &[u8], max_len: usize) -> String { + let mut out = String::new(); + let len = payload.len().min(max_len); + for (idx, byte) in payload.iter().take(len).enumerate() { + if idx > 0 { + out.push(' '); + } + out.push_str(&format!("{:02x}", byte)); + } + out +} + +fn payload_hint(payload: &[u8]) -> &'static str { + let mut idx = 0; + while idx < payload.len() && payload[idx].is_ascii_whitespace() { + idx += 1; + } + if idx >= payload.len() { + return "empty"; + } + match payload[idx] { + b'{' | b'[' => "looks like JSON", + b'"' => "looks like quoted text", + _ => "binary", } } diff --git a/src/rust/lqosd/src/node_manager/ws/publish_subscribe.rs b/src/rust/lqosd/src/node_manager/ws/publish_subscribe.rs index b6f3cb7a..179ca8b7 100644 --- a/src/rust/lqosd/src/node_manager/ws/publish_subscribe.rs +++ b/src/rust/lqosd/src/node_manager/ws/publish_subscribe.rs @@ -5,6 +5,7 @@ mod publisher_channel; mod subscriber; +use crate::node_manager::ws::messages::{WsResponse, encode_ws_message}; use crate::node_manager::ws::publish_subscribe::publisher_channel::PublisherChannel; use crate::node_manager::ws::published_channels::PublishedChannels; use arc_swap::ArcSwap; @@ -45,7 +46,7 @@ impl PubSub { /// Adds a subscriber to a channel set. Once added, they are /// self-managing and will be deleted when they become inactive /// automatically. - pub(super) async fn subscribe(&self, channel: PublishedChannels, sender: Sender>) { + pub(super) async fn subscribe(&self, channel: PublishedChannels, sender: Sender>>) { let mut channels = self.channels.lock().await; if let Some(channel) = channels.iter_mut().find(|c| c.channel_type == channel) { channel.subscribe(sender).await; @@ -76,10 +77,17 @@ impl PubSub { /// Sends a message to everyone subscribed to a topic. If senders' channels /// are dead, they are removed from the list. - pub(super) async fn send(&self, channel: PublishedChannels, message: String) { + pub(super) async fn send(&self, channel: PublishedChannels, message: WsResponse) { + let payload = match encode_ws_message(&message) { + Ok(payload) => payload, + Err(err) => { + warn!("Failed to encode ws message for {:?}: {:?}", channel, err); + return; + } + }; let mut channels = self.channels.lock().await; if let Some(channel) = channels.iter_mut().find(|c| c.channel_type == channel) { - channel.send(Arc::new(message)).await; + channel.send(payload).await; } } diff --git a/src/rust/lqosd/src/node_manager/ws/publish_subscribe/publisher_channel.rs b/src/rust/lqosd/src/node_manager/ws/publish_subscribe/publisher_channel.rs index 95ea35d0..1e8f8259 100644 --- a/src/rust/lqosd/src/node_manager/ws/publish_subscribe/publisher_channel.rs +++ b/src/rust/lqosd/src/node_manager/ws/publish_subscribe/publisher_channel.rs @@ -1,7 +1,7 @@ +use crate::node_manager::ws::messages::{WsResponse, encode_ws_message}; use crate::node_manager::ws::publish_subscribe::subscriber::Subscriber; use crate::node_manager::ws::published_channels::PublishedChannels; use allocative::Allocative; -use serde_json::json; use std::sync::Arc; use tokio::sync::mpsc::Sender; @@ -23,25 +23,21 @@ impl PublisherChannel { !self.subscribers.is_empty() } - pub(super) async fn subscribe(&mut self, sender: Sender>) { + pub(super) async fn subscribe(&mut self, sender: Sender>>) { self.subscribers.push(Subscriber { is_alive: true, sender: sender.clone(), }); - let welcome = Arc::new( - json!( - { - "event" : "join", - "channel" : self.channel_type.to_string(), - } - ) - .to_string(), - ); - let _ = sender.send(welcome).await; + let welcome = WsResponse::Join { + channel: self.channel_type, + }; + if let Ok(payload) = encode_ws_message(&welcome) { + let _ = sender.send(payload).await; + } } /// Submit a message to an entire channel - pub(super) async fn send(&mut self, message: Arc) { + pub(super) async fn send(&mut self, message: Arc>) { for subscriber in self.subscribers.iter_mut() { if subscriber.sender.send(message.clone()).await.is_err() { subscriber.is_alive = false; diff --git a/src/rust/lqosd/src/node_manager/ws/publish_subscribe/subscriber.rs b/src/rust/lqosd/src/node_manager/ws/publish_subscribe/subscriber.rs index 091b8fad..61bcf037 100644 --- a/src/rust/lqosd/src/node_manager/ws/publish_subscribe/subscriber.rs +++ b/src/rust/lqosd/src/node_manager/ws/publish_subscribe/subscriber.rs @@ -6,5 +6,5 @@ use tokio::sync::mpsc::Sender; pub(super) struct Subscriber { pub(super) is_alive: bool, #[allocative(skip)] - pub(super) sender: Sender>, + pub(super) sender: Sender>>, } diff --git a/src/rust/lqosd/src/node_manager/ws/published_channels.rs b/src/rust/lqosd/src/node_manager/ws/published_channels.rs index 32e0c4af..4b984e3e 100644 --- a/src/rust/lqosd/src/node_manager/ws/published_channels.rs +++ b/src/rust/lqosd/src/node_manager/ws/published_channels.rs @@ -1,7 +1,21 @@ use allocative::Allocative; +use serde::{Deserialize, Serialize}; use strum::{Display, EnumIter, EnumString}; -#[derive(PartialEq, Clone, Copy, Debug, EnumIter, Display, EnumString, Hash, Eq, Allocative)] +#[derive( + PartialEq, + Clone, + Copy, + Debug, + EnumIter, + Display, + EnumString, + Hash, + Eq, + Allocative, + Serialize, + Deserialize, +)] pub enum PublishedChannels { /// Provides a 1-second tick notification to the client Cadence, diff --git a/src/rust/lqosd/src/node_manager/ws/single_user_channels.rs b/src/rust/lqosd/src/node_manager/ws/single_user_channels.rs index 4b027459..511b3181 100644 --- a/src/rust/lqosd/src/node_manager/ws/single_user_channels.rs +++ b/src/rust/lqosd/src/node_manager/ws/single_user_channels.rs @@ -4,152 +4,125 @@ mod circuit; mod flows_by_circuit; mod ping_monitor; +use crate::node_manager::ws::messages::{PrivateRequest, WsResponse, encode_ws_message}; use crate::node_manager::ws::single_user_channels::cake_watcher::cake_watcher; use crate::node_manager::ws::single_user_channels::circuit::circuit_watcher; use crate::node_manager::ws::single_user_channels::flows_by_circuit::flows_by_circuit; use crate::node_manager::ws::single_user_channels::ping_monitor::ping_monitor; -use axum::Extension; -use axum::extract::WebSocketUpgrade; -use axum::extract::ws::{Message, WebSocket}; -use axum::http::{HeaderMap, header}; -use axum::response::IntoResponse; -use serde::{Deserialize, Serialize}; use tokio::spawn; -use tracing::{debug, info}; +use tokio::sync::mpsc::Sender; +use tracing::info; -#[derive(Serialize, Deserialize)] -enum PrivateChannel { - CircuitWatcher { circuit: String }, - PingMonitor { ips: Vec<(String, String)> }, - FlowsByCircuit { circuit: String }, - CakeWatcher { circuit: String }, - Chatbot { browser_ts_ms: Option }, -} - -pub(super) async fn private_channel_ws_handler( - ws: WebSocketUpgrade, - Extension(bus_tx): Extension< - tokio::sync::mpsc::Sender<( - tokio::sync::oneshot::Sender, - lqos_bus::BusRequest, - )>, - >, - Extension(control_tx): Extension< - tokio::sync::mpsc::Sender, - >, - headers: HeaderMap, -) -> impl IntoResponse { - info!("WS Upgrade Called"); - let my_bus = bus_tx.clone(); - let browser_language = headers - .get(header::ACCEPT_LANGUAGE) - .and_then(|h| h.to_str().ok()) - .map(|s| s.to_string()); - ws.on_upgrade(move |socket| async { - handle_socket(socket, my_bus, control_tx, browser_language).await; - }) -} - -async fn handle_socket( - mut socket: WebSocket, - bus_tx: tokio::sync::mpsc::Sender<( +pub struct PrivateState { + tx: Sender>>, + bus_tx: Sender<( tokio::sync::oneshot::Sender, lqos_bus::BusRequest, )>, control_tx: tokio::sync::mpsc::Sender, browser_language: Option, -) { - debug!("Websocket connected"); + chatbot_request: Option, +} - let (tx, mut rx) = tokio::sync::mpsc::channel::(10); - let mut chatbot_request: Option = None; - loop { - tokio::select! { - inbound = socket.recv() => { - // Handle incoming message - select a private message source - match inbound { - Some(Ok(msg)) => { - if let Ok(text) = msg.to_text() { - if let Ok(sub) = serde_json::from_str::(text) { - match sub { - PrivateChannel::CircuitWatcher {circuit } => { - spawn(circuit_watcher(circuit, tx.clone(), bus_tx.clone())); - }, - PrivateChannel::PingMonitor { ips } => { - spawn(ping_monitor(ips, tx.clone())); - }, - PrivateChannel::FlowsByCircuit { circuit } => { - spawn(flows_by_circuit(circuit, tx.clone())); - }, - PrivateChannel::CakeWatcher { circuit } => { - spawn(cake_watcher(circuit, tx.clone())); - }, - PrivateChannel::Chatbot { browser_ts_ms } => { - // Start a chatbot session bridged via control channel - if chatbot_request.is_none() { - let request_id = rand::random::(); - chatbot_request = Some(request_id); - let (stream_tx, mut stream_rx) = tokio::sync::mpsc::channel::>(64); - let ctl = control_tx.clone(); - // Spawn forwarder: bytes -> text to client - let to_client = tx.clone(); - tracing::info!("[chatbot] starting session request_id={} browser_ts_ms={:?}", request_id, browser_ts_ms); - tokio::spawn(async move { - while let Some(b) = stream_rx.recv().await { - let s = String::from_utf8_lossy(&b).to_string(); - let _ = to_client.send(s).await; - } - tracing::info!("[chatbot] stream closed request_id={}", request_id); - }); - // Send start to control channel - let _ = ctl.send( - crate::lts2_sys::control_channel::ControlChannelCommand::StartChat { - request_id, - browser_ts_ms, - browser_language: browser_language.clone(), - stream: stream_tx, - } - ).await; - } - }, - } - } else { - // Try to parse chatbot user input when a session is active - if let Some(request_id) = chatbot_request { - #[derive(Deserialize)] - #[allow(non_snake_case)] - struct ChatMsg { ChatbotUserInput: ChatMsgBody } - #[derive(Deserialize)] - struct ChatMsgBody { text: String } - if let Ok(m) = serde_json::from_str::(text) { - let _ = control_tx.send( - crate::lts2_sys::control_channel::ControlChannelCommand::ChatSend { - request_id, - text: m.ChatbotUserInput.text, - } - ).await; - tracing::debug!("[chatbot] forwarded user input request_id={}", request_id); - } - } else { - debug!("Failed to parse private message: {:?}", text); - } - } - } - } - Some(Err(_)) => break, - None => break, - } +impl PrivateState { + pub fn new( + tx: Sender>>, + bus_tx: Sender<( + tokio::sync::oneshot::Sender, + lqos_bus::BusRequest, + )>, + control_tx: tokio::sync::mpsc::Sender< + crate::lts2_sys::control_channel::ControlChannelCommand, + >, + browser_language: Option, + ) -> Self { + Self { + tx, + bus_tx, + control_tx, + browser_language, + chatbot_request: None, + } + } + + pub async fn handle_request(&mut self, request: PrivateRequest) { + match request { + PrivateRequest::CircuitWatcher { circuit } => { + spawn(circuit_watcher( + circuit, + self.tx.clone(), + self.bus_tx.clone(), + )); } - outbound = rx.recv() => { - match outbound { - Some(msg) => { - if let Err(_) = socket.send(Message::Text(msg)).await { - break; - } + PrivateRequest::PingMonitor { ips } => { + spawn(ping_monitor(ips, self.tx.clone())); + } + PrivateRequest::FlowsByCircuit { circuit } => { + spawn(flows_by_circuit(circuit, self.tx.clone())); + } + PrivateRequest::CakeWatcher { circuit } => { + spawn(cake_watcher(circuit, self.tx.clone())); + } + PrivateRequest::Chatbot { browser_ts_ms } => { + self.start_chatbot(browser_ts_ms).await; + } + PrivateRequest::ChatbotUserInput { text } => { + self.forward_chatbot_input(text).await; + } + } + } + + async fn start_chatbot(&mut self, browser_ts_ms: Option) { + if self.chatbot_request.is_some() { + return; + } + + let request_id = rand::random::(); + self.chatbot_request = Some(request_id); + let (stream_tx, mut stream_rx) = tokio::sync::mpsc::channel::>(64); + let to_client = self.tx.clone(); + + tokio::spawn(async move { + while let Some(chunk) = stream_rx.recv().await { + let text = String::from_utf8_lossy(&chunk).to_string(); + let response = WsResponse::ChatbotChunk { text }; + if let Ok(payload) = encode_ws_message(&response) { + if to_client.send(payload).await.is_err() { + break; } - None => break, + } else { + break; } } - } + }); + + let _ = self + .control_tx + .send( + crate::lts2_sys::control_channel::ControlChannelCommand::StartChat { + request_id, + browser_ts_ms, + browser_language: self.browser_language.clone(), + stream: stream_tx, + }, + ) + .await; + info!( + "[chatbot] starting session request_id={} browser_ts_ms={:?}", + request_id, browser_ts_ms + ); + } + + async fn forward_chatbot_input(&self, text: String) { + let Some(request_id) = self.chatbot_request else { + return; + }; + let _ = self + .control_tx + .send(crate::lts2_sys::control_channel::ControlChannelCommand::ChatSend { + request_id, + text, + }) + .await; } } diff --git a/src/rust/lqosd/src/node_manager/ws/single_user_channels/cake_watcher.rs b/src/rust/lqosd/src/node_manager/ws/single_user_channels/cake_watcher.rs index d89ea73c..70ca19ea 100644 --- a/src/rust/lqosd/src/node_manager/ws/single_user_channels/cake_watcher.rs +++ b/src/rust/lqosd/src/node_manager/ws/single_user_channels/cake_watcher.rs @@ -1,7 +1,11 @@ +use crate::node_manager::ws::messages::{WsResponse, encode_ws_message}; use lqos_bus::QueueStoreTransit; use lqos_queue_tracker::{add_watched_queue, get_raw_circuit_data, still_watching}; -pub(super) async fn cake_watcher(circuit_id: String, tx: tokio::sync::mpsc::Sender) { +pub(super) async fn cake_watcher( + circuit_id: String, + tx: tokio::sync::mpsc::Sender>>, +) { const INTERVAL_MS: u64 = 1000; add_watched_queue(&circuit_id); @@ -13,8 +17,11 @@ pub(super) async fn cake_watcher(circuit_id: String, tx: tokio::sync::mpsc::Send match get_raw_circuit_data(&circuit_id) { lqos_bus::BusResponse::RawQueueData(Some(msg)) => { - if let Ok(json) = serde_json::to_string(&QueueStoreTransit::from(*msg)) { - let send_result = tx.send(json.to_string()).await; + let response = WsResponse::CakeWatcher { + data: QueueStoreTransit::from(*msg), + }; + if let Ok(payload) = encode_ws_message(&response) { + let send_result = tx.send(payload).await; if send_result.is_err() { break; } diff --git a/src/rust/lqosd/src/node_manager/ws/single_user_channels/circuit.rs b/src/rust/lqosd/src/node_manager/ws/single_user_channels/circuit.rs index 4a2f9004..c342678e 100644 --- a/src/rust/lqosd/src/node_manager/ws/single_user_channels/circuit.rs +++ b/src/rust/lqosd/src/node_manager/ws/single_user_channels/circuit.rs @@ -1,19 +1,13 @@ +use crate::node_manager::ws::messages::{WsResponse, encode_ws_message}; use crate::node_manager::ws::ticker::all_circuits; -use lqos_bus::{BusRequest, Circuit}; -use serde::Serialize; +use lqos_bus::BusRequest; use std::time::Duration; use tokio::time::MissedTickBehavior; use tracing::info; -#[derive(Serialize)] -pub struct Devices { - pub circuit_id: String, - pub devices: Vec, -} - pub(super) async fn circuit_watcher( circuit: String, - tx: tokio::sync::mpsc::Sender, + tx: tokio::sync::mpsc::Sender>>, bus_tx: tokio::sync::mpsc::Sender<( tokio::sync::oneshot::Sender, BusRequest, @@ -37,16 +31,19 @@ pub(super) async fn circuit_watcher( }) .collect(); - let result = Devices { + let result = WsResponse::CircuitWatcher { circuit_id: circuit.clone(), devices: devices_for_circuit, }; - if let Ok(message) = serde_json::to_string(&result) { - if let Err(_) = tx.send(message.to_string()).await { + if let Ok(payload) = encode_ws_message(&result) { + if let Err(_) = tx.send(payload).await { info!("Channel is gone"); break; } + } else { + info!("CircuitWatcher encode failed"); + break; } } } diff --git a/src/rust/lqosd/src/node_manager/ws/single_user_channels/flows_by_circuit.rs b/src/rust/lqosd/src/node_manager/ws/single_user_channels/flows_by_circuit.rs index 64c369d6..433bc26e 100644 --- a/src/rust/lqosd/src/node_manager/ws/single_user_channels/flows_by_circuit.rs +++ b/src/rust/lqosd/src/node_manager/ws/single_user_channels/flows_by_circuit.rs @@ -1,9 +1,9 @@ +use crate::node_manager::ws::messages::{FlowbeeKeyTransit, WsResponse, encode_ws_message}; use crate::shaped_devices_tracker::SHAPED_DEVICES; use crate::throughput_tracker::flow_data::{ ALL_FLOWS, FlowAnalysis, FlowbeeLocalData, get_asn_name_and_country, }; use lqos_utils::unix_time::time_since_boot; -use serde::Serialize; use std::net::IpAddr; use std::time::Duration; use tokio::time::MissedTickBehavior; @@ -94,37 +94,10 @@ fn recent_flows_by_circuit( Vec::new() } -#[derive(Serialize)] -pub struct FlowbeeKeyTransit { - /// Mapped `XdpIpAddress` source for the flow. - pub remote_ip: String, - /// Mapped `XdpIpAddress` destination for the flow - pub local_ip: String, - /// Source port number, or ICMP type. - pub src_port: u16, - /// Destination port number. - pub dst_port: u16, - /// IP protocol (see the Linux kernel!) - pub ip_protocol: u8, - /// Device Name - pub device_name: String, - /// ASN Name - pub asn_name: String, - /// ASN Country - pub asn_country: String, - /// Protocol Name - pub protocol_name: String, - /// Last Seen Nanos - pub last_seen_nanos: u64, -} - -#[derive(Serialize)] -struct FlowData { - circuit_id: String, - flows: Vec<(FlowbeeKeyTransit, FlowbeeLocalData, FlowAnalysis)>, -} - -pub(super) async fn flows_by_circuit(circuit: String, tx: tokio::sync::mpsc::Sender) { +pub(super) async fn flows_by_circuit( + circuit: String, + tx: tokio::sync::mpsc::Sender>>, +) { let mut ticker = tokio::time::interval(Duration::from_secs(1)); ticker.set_missed_tick_behavior(MissedTickBehavior::Skip); loop { @@ -135,15 +108,17 @@ pub(super) async fn flows_by_circuit(circuit: String, tx: tokio::sync::mpsc::Sen .collect(); if !flows.is_empty() { - let result = FlowData { + let result = WsResponse::FlowsByCircuit { circuit_id: circuit.clone(), flows, }; - if let Ok(message) = serde_json::to_string(&result) { - if let Err(_) = tx.send(message).await { + if let Ok(payload) = encode_ws_message(&result) { + if let Err(_) = tx.send(payload).await { debug!("Channel is gone"); break; } + } else { + break; } } diff --git a/src/rust/lqosd/src/node_manager/ws/single_user_channels/ping_monitor.rs b/src/rust/lqosd/src/node_manager/ws/single_user_channels/ping_monitor.rs index 0c297d82..a210bc12 100644 --- a/src/rust/lqosd/src/node_manager/ws/single_user_channels/ping_monitor.rs +++ b/src/rust/lqosd/src/node_manager/ws/single_user_channels/ping_monitor.rs @@ -1,27 +1,14 @@ +use crate::node_manager::ws::messages::{PingState, WsResponse, encode_ws_message}; use rand::random; -use serde::Serialize; use std::net::IpAddr; use std::time::Duration; use surge_ping::{Client, Config, ICMP, IcmpPacket, PingIdentifier, PingSequence}; use tokio::time::MissedTickBehavior; use tracing::{debug, error, info}; -#[derive(Serialize)] -enum PingState { - ChannelTest, - NoResponse, - Ping { time_nanos: u64, label: String }, -} - -#[derive(Serialize)] -struct PingResult { - ip: String, - result: PingState, -} - pub(super) async fn ping_monitor( ip_addresses: Vec<(String, String)>, - tx: tokio::sync::mpsc::Sender, + tx: tokio::sync::mpsc::Sender>>, ) { { let Ok(cfg) = lqos_config::load_config() else { @@ -71,52 +58,59 @@ pub(super) async fn ping_monitor( // Notify the channel that we're still here - this is really // just a test to see if the channel is still alive - let channel_test = PingResult { + let channel_test = WsResponse::PingMonitor { ip: "test".to_string(), result: PingState::ChannelTest, }; - if let Ok(message) = serde_json::to_string(&channel_test) { - if let Err(_) = tx.send(message.to_string()).await { + if let Ok(payload) = encode_ws_message(&channel_test) { + if let Err(_) = tx.send(payload).await { debug!("Channel is gone"); break; } + } else { + break; } } } -async fn send_timeout(tx: tokio::sync::mpsc::Sender, ip: String) { - let result = PingResult { +async fn send_timeout(tx: tokio::sync::mpsc::Sender>>, ip: String) { + let result = WsResponse::PingMonitor { ip, result: PingState::NoResponse, }; - if let Ok(message) = serde_json::to_string(&result) { - if let Err(_) = tx.send(message.to_string()).await { + if let Ok(payload) = encode_ws_message(&result) { + if let Err(_) = tx.send(payload).await { info!("Channel is gone"); } } } async fn send_alive( - tx: tokio::sync::mpsc::Sender, + tx: tokio::sync::mpsc::Sender>>, ip: String, ping_time: Duration, label: String, ) { - let result = PingResult { + let result = WsResponse::PingMonitor { ip, result: PingState::Ping { time_nanos: ping_time.as_nanos() as u64, label, }, }; - if let Ok(message) = serde_json::to_string(&result) { - if let Err(_) = tx.send(message.to_string()).await { + if let Ok(payload) = encode_ws_message(&result) { + if let Err(_) = tx.send(payload).await { info!("Channel is gone"); } } } -async fn ping(client: Client, addr: IpAddr, tx: tokio::sync::mpsc::Sender, label: String) { +async fn ping( + client: Client, + addr: IpAddr, + tx: tokio::sync::mpsc::Sender>>, + label: String, +) { let payload = [0; 56]; let mut pinger = client.pinger(addr, PingIdentifier(random())).await; pinger.timeout(Duration::from_secs(1)); diff --git a/src/rust/lqosd/src/node_manager/ws/ticker.rs b/src/rust/lqosd/src/node_manager/ws/ticker.rs index 12ce6677..c4403df3 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker.rs @@ -13,7 +13,7 @@ mod endpoint_latlon; mod executive_heatmaps; mod flow_counter; mod flow_endpoints; -mod ipstats_conversion; +pub(crate) mod ipstats_conversion; mod network_tree; mod queue_stats_total; mod retransmits; diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/asn_top.rs b/src/rust/lqosd/src/node_manager/ws/ticker/asn_top.rs index 018243fb..a367e76d 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/asn_top.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/asn_top.rs @@ -1,11 +1,10 @@ use std::collections::HashMap; use std::sync::Arc; +use crate::node_manager::ws::messages::{TopAsnRow, WsResponse}; use crate::node_manager::ws::publish_subscribe::PubSub; use crate::node_manager::ws::published_channels::PublishedChannels; use lqos_bus::{BusReply, BusRequest, BusResponse, FlowbeeSummaryData}; -use serde::Serialize; -use serde_json::json; use tokio::sync::mpsc::Sender; #[derive(Default)] @@ -20,14 +19,6 @@ struct Agg { flows: u64, } -#[derive(Serialize)] -struct TopAsnRow { - name: String, - value: u64, - flow_count: u64, - retransmit_percent: f64, -} - pub async fn asn_top( channels: Arc, bus_tx: Sender<(tokio::sync::oneshot::Sender, BusRequest)>, @@ -102,21 +93,13 @@ pub async fn asn_top( // Publish to channels as needed if live_down { - let message = json!({ - "event": PublishedChannels::AsnTopDownload.to_string(), - "data": down_rows, - }) - .to_string(); + let message = WsResponse::AsnTopDownload { data: down_rows }; channels .send(PublishedChannels::AsnTopDownload, message) .await; } if live_up { - let message = json!({ - "event": PublishedChannels::AsnTopUpload.to_string(), - "data": up_rows, - }) - .to_string(); + let message = WsResponse::AsnTopUpload { data: up_rows }; channels .send(PublishedChannels::AsnTopUpload, message) .await; diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/bakery.rs b/src/rust/lqosd/src/node_manager/ws/ticker/bakery.rs index 70b230f8..3c4480ef 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/bakery.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/bakery.rs @@ -1,7 +1,7 @@ +use crate::node_manager::ws::messages::{BakeryStatusData, BakeryStatusState, WsResponse}; use crate::node_manager::ws::publish_subscribe::PubSub; use crate::node_manager::ws::published_channels::PublishedChannels; use lqos_bus::{BusReply, BusRequest, BusResponse}; -use serde_json::json; use std::sync::Arc; use tokio::sync::mpsc::Sender; @@ -24,17 +24,16 @@ pub async fn bakery_ticker( for response in replies.responses { if let BusResponse::BakeryActiveCircuits(stats) = response { // Format as JSON - let msg = json!({ - "event": "BakeryStatus", - "data": { - "currentState": { - "activeCircuits": stats, + let msg = WsResponse::BakeryStatus { + data: BakeryStatusData { + current_state: BakeryStatusState { + active_circuits: stats, }, - } - }); + }, + }; pubsub - .send(PublishedChannels::BakeryStatus, msg.to_string()) + .send(PublishedChannels::BakeryStatus, msg) .await; } } diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/cadence.rs b/src/rust/lqosd/src/node_manager/ws/ticker/cadence.rs index 233fd8ee..1c283ac1 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/cadence.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/cadence.rs @@ -1,6 +1,6 @@ +use crate::node_manager::ws::messages::WsResponse; use crate::node_manager::ws::publish_subscribe::PubSub; use crate::node_manager::ws::published_channels::PublishedChannels; -use serde_json::json; use std::sync::Arc; pub async fn cadence(channels: Arc) { @@ -8,11 +8,6 @@ pub async fn cadence(channels: Arc) { return; } - let message = json!( - { - "event": PublishedChannels::Cadence.to_string(), - } - ) - .to_string(); + let message = WsResponse::Cadence; channels.send(PublishedChannels::Cadence, message).await; } diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/circuit_capacity.rs b/src/rust/lqosd/src/node_manager/ws/ticker/circuit_capacity.rs index a589cd3f..b1834423 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/circuit_capacity.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/circuit_capacity.rs @@ -1,10 +1,9 @@ +use crate::node_manager::ws::messages::{CircuitCapacityRow, WsResponse}; use crate::node_manager::ws::publish_subscribe::PubSub; use crate::node_manager::ws::published_channels::PublishedChannels; use crate::shaped_devices_tracker::SHAPED_DEVICES; use crate::throughput_tracker::THROUGHPUT_TRACKER; use lqos_utils::units::DownUpOrder; -use serde::Serialize; -use serde_json::json; use std::collections::HashMap; use std::sync::Arc; @@ -13,14 +12,6 @@ struct CircuitAccumulator { median_rtt: f32, } -#[derive(Serialize)] -struct Capacity { - circuit_id: String, - circuit_name: String, - capacity: [f64; 2], - median_rtt: f32, -} - pub async fn circuit_capacity(channels: Arc) { if !channels .is_channel_alive(PublishedChannels::CircuitCapacity) @@ -57,7 +48,7 @@ pub async fn circuit_capacity(channels: Arc) { // Map circuits to capacities let shaped_devices = SHAPED_DEVICES.load(); - let capacities: Vec = { + let capacities: Vec = { circuits .iter() .filter_map(|(circuit_id, accumulator)| { @@ -71,7 +62,7 @@ pub async fn circuit_capacity(channels: Arc) { let up_mbps = (accumulator.bytes.up as f64 * 8.0) / 1_000_000.0; let up = up_mbps / device.upload_max_mbps as f64; - Some(Capacity { + Some(CircuitCapacityRow { circuit_name: device.circuit_name.clone(), circuit_id: circuit_id.clone(), capacity: [down, up], @@ -84,13 +75,7 @@ pub async fn circuit_capacity(channels: Arc) { .collect() }; - let message = json!( - { - "event": PublishedChannels::CircuitCapacity.to_string(), - "data": capacities, - } - ) - .to_string(); + let message = WsResponse::CircuitCapacity { data: capacities }; channels .send(PublishedChannels::CircuitCapacity, message) .await; diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/endpoint_latlon.rs b/src/rust/lqosd/src/node_manager/ws/ticker/endpoint_latlon.rs index 23aa2cab..7a87af24 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/endpoint_latlon.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/endpoint_latlon.rs @@ -1,9 +1,9 @@ use std::sync::Arc; +use crate::node_manager::ws::messages::WsResponse; use crate::node_manager::ws::publish_subscribe::PubSub; use crate::node_manager::ws::published_channels::PublishedChannels; use lqos_bus::{BusReply, BusRequest, BusResponse}; -use serde_json::json; use tokio::sync::mpsc::Sender; pub async fn endpoint_latlon( @@ -36,11 +36,7 @@ pub async fn endpoint_latlon( for reply in replies.responses.into_iter() { if let BusResponse::CurrentLatLon(points) = reply { - let message = json!({ - "event": PublishedChannels::EndpointLatLon.to_string(), - "data": points, - }) - .to_string(); + let message = WsResponse::EndpointLatLon { data: points }; channels .send(PublishedChannels::EndpointLatLon, message) .await; diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/executive_heatmaps.rs b/src/rust/lqosd/src/node_manager/ws/ticker/executive_heatmaps.rs index 3353a3a1..8a23102c 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/executive_heatmaps.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/executive_heatmaps.rs @@ -1,6 +1,7 @@ use std::sync::Arc; use std::time::{Duration, Instant}; +use crate::node_manager::ws::messages::{ExecutiveHeatmapsData, OversubscribedSite, WsResponse}; use crate::node_manager::ws::publish_subscribe::PubSub; use crate::node_manager::ws::published_channels::PublishedChannels; use crate::shaped_devices_tracker::{NETWORK_JSON, SHAPED_DEVICES}; @@ -8,7 +9,6 @@ use lqos_bus::{BusReply, BusRequest, BusResponse, ExecutiveSummaryHeader}; use lqos_utils::temporal_heatmap::{HeatmapBlocks, TemporalHeatmap}; use once_cell::sync::Lazy; use parking_lot::Mutex; -use serde_json::json; use std::collections::{HashMap, HashSet}; use tokio::sync::mpsc::Sender; @@ -45,18 +45,16 @@ pub async fn executive_heatmaps( .unwrap_or_else(empty_blocks); let oversubscribed_sites = compute_oversubscribed_sites(); - let payload = json!({ - "event": PublishedChannels::ExecutiveHeatmaps.to_string(), - "data": { - "header": header, - "global": global, - "circuits": circuits, - "sites": sites, - "asns": asns, - "oversubscribed_sites": oversubscribed_sites, - } - }) - .to_string(); + let payload = WsResponse::ExecutiveHeatmaps { + data: ExecutiveHeatmapsData { + header, + global, + circuits, + sites, + asns, + oversubscribed_sites, + }, + }; channels .send(PublishedChannels::ExecutiveHeatmaps, payload) @@ -156,7 +154,7 @@ struct OversubTally { sub_up: f32, } -fn compute_oversubscribed_sites() -> Vec { +fn compute_oversubscribed_sites() -> Vec { let devices = SHAPED_DEVICES.load(); let mut circuit_map: HashMap = HashMap::new(); for device in devices.devices.iter() { @@ -256,16 +254,16 @@ fn compute_oversubscribed_sites() -> Vec { (None, Some(u)) => Some(u), (None, None) => None, }; - Some(json!({ - "site_name": site_name, - "cap_down": t.cap_down, - "cap_up": t.cap_up, - "sub_down": t.sub_down, - "sub_up": t.sub_up, - "ratio_down": ratio_down, - "ratio_up": ratio_up, - "ratio_max": ratio_max, - })) + Some(OversubscribedSite { + site_name, + cap_down: t.cap_down, + cap_up: t.cap_up, + sub_down: t.sub_down, + sub_up: t.sub_up, + ratio_down, + ratio_up, + ratio_max, + }) }) .collect() } diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/flow_counter.rs b/src/rust/lqosd/src/node_manager/ws/ticker/flow_counter.rs index 9f6a83d2..9f336cf1 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/flow_counter.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/flow_counter.rs @@ -1,7 +1,7 @@ +use crate::node_manager::ws::messages::WsResponse; use crate::node_manager::ws::publish_subscribe::PubSub; use crate::node_manager::ws::published_channels::PublishedChannels; use lqos_bus::{BusReply, BusRequest, BusResponse}; -use serde_json::json; use std::sync::Arc; use tokio::sync::mpsc::Sender; @@ -31,17 +31,11 @@ pub async fn flow_count( }; for reply in replies.responses.into_iter() { if let BusResponse::CountActiveFlows(active) = reply { - let active_flows = json!( - { - "event": PublishedChannels::FlowCount.to_string(), - "active": active, - "recent": 0, - } - ) - .to_string(); - channels - .send(PublishedChannels::FlowCount, active_flows) - .await; + let active_flows = WsResponse::FlowCount { + active, + recent: 0, + }; + channels.send(PublishedChannels::FlowCount, active_flows).await; } } } diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/flow_endpoints.rs b/src/rust/lqosd/src/node_manager/ws/ticker/flow_endpoints.rs index 01692661..935d9e57 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/flow_endpoints.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/flow_endpoints.rs @@ -1,9 +1,9 @@ use std::sync::Arc; +use crate::node_manager::ws::messages::{EtherProtocolsData, WsResponse}; use crate::node_manager::ws::publish_subscribe::PubSub; use crate::node_manager::ws::published_channels::PublishedChannels; use lqos_bus::{BusReply, BusRequest, BusResponse}; -use serde_json::json; use tokio::sync::mpsc::Sender; pub async fn endpoints_by_country( @@ -35,13 +35,7 @@ pub async fn endpoints_by_country( }; for reply in replies.responses.into_iter() { if let BusResponse::CurrentEndpointsByCountry(countries) = reply { - let message = json!( - { - "event": PublishedChannels::EndpointsByCountry.to_string(), - "data": countries, - } - ) - .to_string(); + let message = WsResponse::EndpointsByCountry { data: countries }; channels .send(PublishedChannels::EndpointsByCountry, message) .await; @@ -86,20 +80,16 @@ pub async fn ether_protocols( v6_rtt, } = reply { - let message = json!( - { - "event": PublishedChannels::EtherProtocols.to_string(), - "data": { - "v4_bytes": v4_bytes, - "v6_bytes": v6_bytes, - "v4_packets": v4_packets, - "v6_packets": v6_packets, - "v4_rtt": v4_rtt, - "v6_rtt": v6_rtt, - }, - } - ) - .to_string(); + let message = WsResponse::EtherProtocols { + data: EtherProtocolsData { + v4_bytes, + v6_bytes, + v4_packets, + v6_packets, + v4_rtt, + v6_rtt, + }, + }; channels .send(PublishedChannels::EtherProtocols, message) .await; @@ -136,13 +126,7 @@ pub async fn ip_protocols( }; for reply in replies.responses.into_iter() { if let BusResponse::IpProtocols(ip_data) = reply { - let message = json!( - { - "event": PublishedChannels::IpProtocols.to_string(), - "data": ip_data, - } - ) - .to_string(); + let message = WsResponse::IpProtocols { data: ip_data }; channels.send(PublishedChannels::IpProtocols, message).await; } } @@ -177,13 +161,7 @@ pub async fn flow_duration( }; for reply in replies.responses.into_iter() { if let BusResponse::FlowDuration(flow_data) = reply { - let message = json!( - { - "event": PublishedChannels::FlowDurations.to_string(), - "data": flow_data, - } - ) - .to_string(); + let message = WsResponse::FlowDurations { data: flow_data }; channels .send(PublishedChannels::FlowDurations, message) .await; diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/network_tree.rs b/src/rust/lqosd/src/node_manager/ws/ticker/network_tree.rs index a615db04..4c49a3b3 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/network_tree.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/network_tree.rs @@ -1,7 +1,7 @@ +use crate::node_manager::ws::messages::WsResponse; use crate::node_manager::ws::publish_subscribe::PubSub; use crate::node_manager::ws::published_channels::PublishedChannels; use lqos_bus::{BusReply, BusRequest, BusResponse, Circuit}; -use serde_json::json; use std::sync::Arc; use tokio::sync::mpsc::Sender; @@ -34,13 +34,7 @@ pub async fn network_tree( }; for reply in replies.responses.into_iter() { if let BusResponse::NetworkMap(nodes) = reply { - let message = json!( - { - "event": PublishedChannels::NetworkTree.to_string(), - "data": nodes, - } - ) - .to_string(); + let message = WsResponse::NetworkTree { data: nodes }; channels.send(PublishedChannels::NetworkTree, message).await; } } @@ -85,13 +79,7 @@ pub async fn all_subscribers( } let devices = all_circuits(bus_tx).await; - let message = json!( - { - "event": PublishedChannels::NetworkTreeClients.to_string(), - "data": devices, - } - ) - .to_string(); + let message = WsResponse::NetworkTreeClients { data: devices }; channels .send(PublishedChannels::NetworkTreeClients, message) .await; diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/queue_stats_total.rs b/src/rust/lqosd/src/node_manager/ws/ticker/queue_stats_total.rs index 27d46ebe..56691508 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/queue_stats_total.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/queue_stats_total.rs @@ -1,7 +1,8 @@ +use crate::node_manager::ws::messages::WsResponse; use crate::node_manager::ws::publish_subscribe::PubSub; use crate::node_manager::ws::published_channels::PublishedChannels; use lqos_queue_tracker::TOTAL_QUEUE_STATS; -use serde_json::json; +use lqos_utils::units::DownUpOrder; use std::sync::Arc; pub async fn queue_stats_totals(channels: Arc) { @@ -12,20 +13,16 @@ pub async fn queue_stats_totals(channels: Arc) { return; } - let message = json!( - { - "event": PublishedChannels::QueueStatsTotal.to_string(), - "marks": { - "down" : TOTAL_QUEUE_STATS.marks.get_down(), - "up" : TOTAL_QUEUE_STATS.marks.get_up(), - }, - "drops" : { - "down" : TOTAL_QUEUE_STATS.drops.get_down(), - "up" : TOTAL_QUEUE_STATS.drops.get_up(), - }, - } - ) - .to_string(); + let message = WsResponse::QueueStatsTotal { + marks: DownUpOrder::new( + TOTAL_QUEUE_STATS.marks.get_down(), + TOTAL_QUEUE_STATS.marks.get_up(), + ), + drops: DownUpOrder::new( + TOTAL_QUEUE_STATS.drops.get_down(), + TOTAL_QUEUE_STATS.drops.get_up(), + ), + }; channels .send(PublishedChannels::QueueStatsTotal, message) .await; diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/retransmits.rs b/src/rust/lqosd/src/node_manager/ws/ticker/retransmits.rs index 6f377630..93e1f487 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/retransmits.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/retransmits.rs @@ -1,7 +1,7 @@ +use crate::node_manager::ws::messages::WsResponse; use crate::node_manager::ws::publish_subscribe::PubSub; use crate::node_manager::ws::published_channels::PublishedChannels; use crate::throughput_tracker::min_max_median_tcp_retransmits; -use serde_json::json; use std::sync::Arc; pub async fn tcp_retransmits(channels: Arc) { @@ -14,12 +14,8 @@ pub async fn tcp_retransmits(channels: Arc) { let tcp_retransmits = min_max_median_tcp_retransmits(); - let message = json!( - { - "event": PublishedChannels::Retransmits.to_string(), - "data": tcp_retransmits, - } - ) - .to_string(); + let message = WsResponse::Retransmits { + data: tcp_retransmits, + }; channels.send(PublishedChannels::Retransmits, message).await; } diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/rtt_histogram.rs b/src/rust/lqosd/src/node_manager/ws/ticker/rtt_histogram.rs index ec22803d..01111c16 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/rtt_histogram.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/rtt_histogram.rs @@ -1,7 +1,7 @@ +use crate::node_manager::ws::messages::WsResponse; use crate::node_manager::ws::publish_subscribe::PubSub; use crate::node_manager::ws::published_channels::PublishedChannels; use lqos_bus::{BusReply, BusRequest, BusResponse}; -use serde_json::json; use std::sync::Arc; use tokio::sync::mpsc::Sender; @@ -34,13 +34,7 @@ pub async fn rtt_histo( }; for reply in replies.responses.into_iter() { if let BusResponse::RttHistogram(data) = reply { - let rtt_histo = json!( - { - "event": PublishedChannels::RttHistogram.to_string(), - "data": data, - } - ) - .to_string(); + let rtt_histo = WsResponse::RttHistogram { data }; channels .send(PublishedChannels::RttHistogram, rtt_histo) .await; diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/stormguard.rs b/src/rust/lqosd/src/node_manager/ws/ticker/stormguard.rs index c8e4262e..6958ce4e 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/stormguard.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/stormguard.rs @@ -1,7 +1,7 @@ +use crate::node_manager::ws::messages::WsResponse; use crate::node_manager::ws::publish_subscribe::PubSub; use crate::node_manager::ws::published_channels::PublishedChannels; use lqos_bus::{BusReply, BusRequest, BusResponse}; -use serde_json::json; use std::sync::Arc; use tokio::sync::mpsc::Sender; @@ -28,13 +28,9 @@ pub async fn stormguard_ticker( if let Ok(replies) = rx.await { for response in replies.responses { if let BusResponse::StormguardStats(stats) = response { - let msg = json!({ - "event": "StormguardStatus", - "data": stats, - }); - + let msg = WsResponse::StormguardStatus { data: stats }; pubsub - .send(PublishedChannels::StormguardStatus, msg.to_string()) + .send(PublishedChannels::StormguardStatus, msg) .await; } } @@ -49,13 +45,10 @@ pub async fn stormguard_ticker( if let Ok(replies) = rx.await { for response in replies.responses { if let BusResponse::StormguardDebug(stats) = response { - let msg = json!({ - "event": "StormguardDebug", - "data": stats, - }); + let msg = WsResponse::StormguardDebug { data: stats }; pubsub - .send(PublishedChannels::StormguardDebug, msg.to_string()) + .send(PublishedChannels::StormguardDebug, msg) .await; } } diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/system_info.rs b/src/rust/lqosd/src/node_manager/ws/ticker/system_info.rs index 2eb54f46..7e845304 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/system_info.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/system_info.rs @@ -1,7 +1,7 @@ +use crate::node_manager::ws::messages::{RamData, WsResponse}; use crate::node_manager::ws::publish_subscribe::PubSub; use crate::node_manager::ws::published_channels::PublishedChannels; use crate::system_stats::SystemStats; -use serde_json::json; use std::sync::Arc; pub async fn cpu_info( @@ -15,13 +15,9 @@ pub async fn cpu_info( let (tx, rx) = tokio::sync::oneshot::channel(); if let Ok(_) = system_usage_tx.send(tx) { if let Ok(usage) = rx.await { - let message = json!( - { - "event": PublishedChannels::Cpu.to_string(), - "data": usage.cpu_usage, - } - ) - .to_string(); + let message = WsResponse::Cpu { + data: usage.cpu_usage, + }; channels.send(PublishedChannels::Cpu, message).await; } } @@ -38,16 +34,12 @@ pub async fn ram_info( let (tx, rx) = tokio::sync::oneshot::channel(); if let Ok(_) = system_usage_tx.send(tx) { if let Ok(usage) = rx.await { - let message = json!( - { - "event": PublishedChannels::Ram.to_string(), - "data": { - "total" : usage.total_ram, - "used" : usage.ram_used, - }, - } - ) - .to_string(); + let message = WsResponse::Ram { + data: RamData { + total: usage.total_ram, + used: usage.ram_used, + }, + }; channels.send(PublishedChannels::Ram, message).await; } } diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/throughput.rs b/src/rust/lqosd/src/node_manager/ws/ticker/throughput.rs index 80f7b43d..07699dd7 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/throughput.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/throughput.rs @@ -1,9 +1,9 @@ +use crate::node_manager::ws::messages::{ThroughputData, WsResponse}; use crate::node_manager::ws::publish_subscribe::PubSub; use crate::node_manager::ws::published_channels::PublishedChannels; use lqos_bus::{BusReply, BusRequest, BusResponse}; use lqos_config::load_config; use lqos_utils::units::DownUpOrder; -use serde_json::json; use std::sync::Arc; use tokio::sync::mpsc::Sender; @@ -50,21 +50,17 @@ pub async fn throughput( DownUpOrder::zeroed() }; - let bps = json!( - { - "event" : PublishedChannels::Throughput.to_string(), - "data": { - "bps": bits_per_second, - "pps": packets_per_second, - "tcp_pps": tcp_packets_per_second, - "udp_pps": udp_packets_per_second, - "icmp_pps": icmp_packets_per_second, - "shaped_bps": shaped_bits_per_second, - "max": max, - } - } - ) - .to_string(); + let bps = WsResponse::Throughput { + data: ThroughputData { + bps: bits_per_second, + pps: packets_per_second, + tcp_pps: tcp_packets_per_second, + udp_pps: udp_packets_per_second, + icmp_pps: icmp_packets_per_second, + shaped_bps: shaped_bits_per_second, + max, + }, + }; channels.send(PublishedChannels::Throughput, bps).await; } } diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/top_10.rs b/src/rust/lqosd/src/node_manager/ws/ticker/top_10.rs index 7b660b77..9074bb84 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/top_10.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/top_10.rs @@ -1,8 +1,8 @@ +use crate::node_manager::ws::messages::WsResponse; use crate::node_manager::ws::publish_subscribe::PubSub; use crate::node_manager::ws::published_channels::PublishedChannels; use crate::node_manager::ws::ticker::ipstats_conversion::IpStatsWithPlan; use lqos_bus::{BusReply, BusRequest, BusResponse}; -use serde_json::json; use std::sync::Arc; use tokio::sync::mpsc::Sender; @@ -37,13 +37,7 @@ pub async fn top_10_downloaders( if let BusResponse::TopDownloaders(top) = reply { let result: Vec = top.iter().map(|stat| stat.into()).collect(); - let message = json!( - { - "event": PublishedChannels::TopDownloads.to_string(), - "data": result - } - ) - .to_string(); + let message = WsResponse::TopDownloads { data: result }; channels .send(PublishedChannels::TopDownloads, message) .await; @@ -79,13 +73,7 @@ pub async fn top_10_uploaders( if let BusResponse::TopUploaders(top) = reply { let result: Vec = top.iter().map(|stat| stat.into()).collect(); - let message = json!( - { - "event": PublishedChannels::TopUploads.to_string(), - "data": result - } - ) - .to_string(); + let message = WsResponse::TopUploads { data: result }; channels.send(PublishedChannels::TopUploads, message).await; } } @@ -116,13 +104,7 @@ pub async fn worst_10_downloaders( if let BusResponse::WorstRtt(top) = reply { let result: Vec = top.iter().map(|stat| stat.into()).collect(); - let message = json!( - { - "event": PublishedChannels::WorstRTT.to_string(), - "data": result - } - ) - .to_string(); + let message = WsResponse::WorstRTT { data: result }; channels.send(PublishedChannels::WorstRTT, message).await; } } @@ -159,13 +141,7 @@ pub async fn worst_10_retransmit( if let BusResponse::WorstRetransmits(top) = reply { let result: Vec = top.iter().map(|stat| stat.into()).collect(); - let message = json!( - { - "event": PublishedChannels::WorstRetransmits.to_string(), - "data": result - } - ) - .to_string(); + let message = WsResponse::WorstRetransmits { data: result }; channels .send(PublishedChannels::WorstRetransmits, message) .await; diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/top_flows.rs b/src/rust/lqosd/src/node_manager/ws/ticker/top_flows.rs index 7d15d272..ad561074 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/top_flows.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/top_flows.rs @@ -1,9 +1,9 @@ use std::sync::Arc; use lqos_bus::{BusReply, BusRequest, BusResponse, TopFlowType}; -use serde_json::json; use tokio::sync::mpsc::Sender; +use crate::node_manager::ws::messages::WsResponse; use crate::node_manager::ws::publish_subscribe::PubSub; use crate::node_manager::ws::published_channels::PublishedChannels; @@ -39,13 +39,7 @@ pub async fn top_flows_bytes( }; for reply in replies.responses.into_iter() { if let BusResponse::TopFlows(flows) = reply { - let message = json!( - { - "event": PublishedChannels::TopFlowsBytes.to_string(), - "data": flows, - } - ) - .to_string(); + let message = WsResponse::TopFlowsBytes { data: flows }; channels .send(PublishedChannels::TopFlowsBytes, message) .await; @@ -85,13 +79,7 @@ pub async fn top_flows_rate( }; for reply in replies.responses.into_iter() { if let BusResponse::TopFlows(flows) = reply { - let message = json!( - { - "event": PublishedChannels::TopFlowsRate.to_string(), - "data": flows, - } - ) - .to_string(); + let message = WsResponse::TopFlowsRate { data: flows }; channels .send(PublishedChannels::TopFlowsRate, message) .await; diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/tree_capacity.rs b/src/rust/lqosd/src/node_manager/ws/ticker/tree_capacity.rs index e10210d4..29d3b7e1 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/tree_capacity.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/tree_capacity.rs @@ -1,21 +1,9 @@ +use crate::node_manager::ws::messages::{NodeCapacity, WsResponse}; use crate::node_manager::ws::publish_subscribe::PubSub; use crate::node_manager::ws::published_channels::PublishedChannels; use crate::shaped_devices_tracker::NETWORK_JSON; -use serde::Serialize; -use serde_json::json; use std::sync::Arc; -#[derive(Serialize)] -struct NodeCapacity { - id: usize, - name: String, - down: f64, - up: f64, - max_down: f64, - max_up: f64, - median_rtt: f32, -} - pub async fn tree_capacity(channels: Arc) { if !channels .is_channel_alive(PublishedChannels::TreeCapacity) @@ -59,13 +47,7 @@ pub async fn tree_capacity(channels: Arc) { .collect() }; - let message = json!( - { - "event": PublishedChannels::TreeCapacity.to_string(), - "data": capacities, - } - ) - .to_string(); + let message = WsResponse::TreeCapacity { data: capacities }; channels .send(PublishedChannels::TreeCapacity, message) .await; diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/tree_summary.rs b/src/rust/lqosd/src/node_manager/ws/ticker/tree_summary.rs index c4fcfba3..083ded67 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/tree_summary.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/tree_summary.rs @@ -1,7 +1,7 @@ +use crate::node_manager::ws::messages::WsResponse; use crate::node_manager::ws::publish_subscribe::PubSub; use crate::node_manager::ws::published_channels::PublishedChannels; use lqos_bus::{BusReply, BusRequest, BusResponse}; -use serde_json::json; use std::sync::Arc; use tokio::sync::mpsc::Sender; @@ -34,13 +34,7 @@ pub async fn tree_summary( }; for reply in replies.responses.into_iter() { if let BusResponse::NetworkMap(nodes) = reply { - let message = json!( - { - "event": PublishedChannels::TreeSummary.to_string(), - "data": nodes, - } - ) - .to_string(); + let message = WsResponse::TreeSummary { data: nodes }; channels.send(PublishedChannels::TreeSummary, message).await; } } diff --git a/src/rust/lqosd/src/node_manager/ws/ticker/tree_summary_l2.rs b/src/rust/lqosd/src/node_manager/ws/ticker/tree_summary_l2.rs index ce6d4dfc..5ed39026 100644 --- a/src/rust/lqosd/src/node_manager/ws/ticker/tree_summary_l2.rs +++ b/src/rust/lqosd/src/node_manager/ws/ticker/tree_summary_l2.rs @@ -1,8 +1,8 @@ +use crate::node_manager::ws::messages::WsResponse; use crate::node_manager::ws::publish_subscribe::PubSub; use crate::node_manager::ws::published_channels::PublishedChannels; use crate::shaped_devices_tracker::NETWORK_JSON; use lqos_config::NetworkJsonTransport; -use serde_json::json; use std::collections::BTreeMap; use std::sync::Arc; @@ -58,11 +58,7 @@ pub async fn tree_summary_l2(channels: Arc) { map.into_iter().collect() }; - let message = json!({ - "event": PublishedChannels::TreeSummaryL2.to_string(), - "data": grouped, - }) - .to_string(); + let message = WsResponse::TreeSummaryL2 { data: grouped }; channels .send(PublishedChannels::TreeSummaryL2, message) .await; diff --git a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/asn.rs b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/asn.rs index 28b16ac1..03dc272f 100644 --- a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/asn.rs +++ b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/asn.rs @@ -50,6 +50,7 @@ pub struct GeoTable { impl GeoTable { const FILENAME: &'static str = "geo2.bin"; + #[allow(dead_code)] pub fn len(&self) -> (usize, usize, usize, usize) { ( self.asn_trie.len().1, diff --git a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs index d9e898ff..a024e133 100644 --- a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs +++ b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/finished_flows.rs @@ -413,6 +413,7 @@ impl TimeBuffer { .collect() } + #[allow(dead_code)] pub fn len_and_capacity(&self) -> (usize, usize) { let buffer = self.buffer.lock(); (buffer.len(), buffer.capacity()) diff --git a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/mod.rs b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/mod.rs index 0b01a416..cc42c11b 100644 --- a/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/mod.rs +++ b/src/rust/lqosd/src/throughput_tracker/flow_data/flow_analysis/mod.rs @@ -51,6 +51,7 @@ impl FlowAnalysisSystem { } } + #[allow(dead_code)] pub fn len_and_capacity() -> (usize, usize, usize, usize) { let lock = ANALYSIS.asn_table.lock(); if let Some(table) = lock.as_ref() { diff --git a/src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs b/src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs index 2f897a67..906a3319 100644 --- a/src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs +++ b/src/rust/lqosd/src/throughput_tracker/flow_data/mod.rs @@ -15,7 +15,7 @@ pub(crate) use asn_heatmap::{AsnAggregate, snapshot_asn_heatmaps, update_asn_hea use crossbeam_channel::Sender; pub(crate) use flow_analysis::{ AsnCountryListEntry, AsnListEntry, AsnProtocolListEntry, FlowActor, FlowAnalysis, - FlowAnalysisSystem, RECENT_FLOWS, RttData, expire_rtt_flows, flowbee_handle_events, + RECENT_FLOWS, RttData, expire_rtt_flows, flowbee_handle_events, flowbee_rtt_map, get_asn_name_and_country, get_flowbee_event_count_and_reset, get_asn_name_by_id, get_rtt_events_per_second, setup_flow_analysis, }; diff --git a/src/rust/lqosd/src/throughput_tracker/mod.rs b/src/rust/lqosd/src/throughput_tracker/mod.rs index 2c28b76f..a4e79c6c 100644 --- a/src/rust/lqosd/src/throughput_tracker/mod.rs +++ b/src/rust/lqosd/src/throughput_tracker/mod.rs @@ -746,7 +746,7 @@ pub fn min_max_median_rtt() -> Option { Some(result) } -#[derive(Serialize)] +#[derive(Debug, Serialize)] pub struct TcpRetransmitTotal { pub up: i32, pub down: i32,
CheckSuccess?Comment
"; - } else { - html += ""; - } - html += "" + row.comments + "