1 Commits

Author SHA1 Message Date
cb1f9f4091 Update Rust crate uuid to v1.10.0
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-07-10 00:11:01 +00:00
109 changed files with 21811 additions and 4987 deletions

View File

@ -5,14 +5,13 @@ name: default
steps:
- name: web_build
image: node:23
image: node:22
volumes:
- name: web_app
path: /tmp/web_build
commands:
- cd virtweb_frontend
- npm install --legacy-peer-deps # TODO : remove when mui-file-input is updated
- npm run lint
- npm install
- npm run build
- mv dist /tmp/web_build
@ -26,7 +25,6 @@ steps:
- rustup component add clippy
- cd virtweb_backend
- cargo clippy -- -D warnings
- cargo clippy --examples -- -D warnings
- cargo test
- name: backend_compile
@ -36,8 +34,6 @@ steps:
path: /usr/local/cargo/registry
- name: web_app
path: /tmp/web_build
- name: release
path: /tmp/release
depends_on:
- backend_check
- web_build
@ -47,30 +43,10 @@ steps:
- mv /tmp/web_build/dist static
- cargo build --release
- ls -lah target/release/virtweb_backend
- cp target/release/virtweb_backend /tmp/release
- name: gitea_release
image: plugins/gitea-release
depends_on:
- backend_compile
when:
event:
- tag
volumes:
- name: release
path: /tmp/release
environment:
PLUGIN_API_KEY:
from_secret: API_KEY
settings:
base_url: https://gitea.communiquons.org
files: /tmp/release/*
checksum: sha512
volumes:
- name: rust_registry
temp: {}
- name: web_app
temp: {}
- name: release
temp: {}

View File

@ -1,3 +1,9 @@
{
"extends": ["local>renovate/presets"]
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"packageRules": [
{
"matchUpdateTypes": ["major", "minor", "patch"],
"automerge": true
}
]
}

File diff suppressed because it is too large Load Diff

View File

@ -1,48 +1,48 @@
[package]
name = "virtweb_backend"
version = "0.1.0"
edition = "2024"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
log = "0.4.27"
env_logger = "0.11.7"
clap = { version = "4.5.34", features = ["derive", "env"] }
light-openid = { version = "1.0.4", features = ["crypto-wrapper"] }
lazy_static = "1.5.0"
actix = "0.13.5"
actix-web = "4.10.2"
log = "0.4.21"
env_logger = "0.11.3"
clap = { version = "4.5.4", features = ["derive", "env"] }
light-openid = { version = "1.0.2", features = ["crypto-wrapper"] }
lazy_static = "1.4.0"
actix = "0.13.3"
actix-web = "4.5.1"
actix-remote-ip = "0.1.0"
actix-session = { version = "0.10.1", features = ["cookie-session"] }
actix-identity = "0.8.0"
actix-cors = "0.7.1"
actix-files = "0.6.6"
actix-ws = "0.3.0"
actix-http = "3.10.0"
serde = { version = "1.0.219", features = ["derive"] }
serde_json = "1.0.140"
quick-xml = { version = "0.37.3", features = ["serialize", "overlapped-lists"] }
futures-util = "0.3.31"
anyhow = "1.0.97"
actix-multipart = "0.7.2"
tempfile = "3.19.1"
reqwest = { version = "0.12.15", features = ["stream"] }
url = "2.5.4"
virt = "0.4.2"
sysinfo = { version = "0.34.2", features = ["serde"] }
uuid = { version = "1.16.0", features = ["v4", "serde"] }
lazy-regex = "3.4.1"
thiserror = "2.0.12"
image = "0.25.6"
rand = "0.9.0"
bytes = "1.10.1"
tokio = { version = "1.44.1", features = ["rt", "time", "macros"] }
futures = "0.3.31"
ipnetwork = { version = "0.21.1", features = ["serde"] }
num = "0.4.3"
rust-embed = { version = "8.6.0" }
mime_guess = "2.0.5"
actix-session = { version = "0.9.0", features = ["cookie-session"] }
actix-identity = "0.7.1"
actix-cors = "0.7.0"
actix-files = "0.6.5"
actix-web-actors = "4.3.0"
actix-http = "3.6.0"
serde = { version = "1.0.199", features = ["derive"] }
serde_json = "1.0.116"
quick-xml = { version = "0.33.0", features = ["serialize", "overlapped-lists"] }
futures-util = "0.3.30"
anyhow = "1.0.82"
actix-multipart = "0.6.1"
tempfile = "3.10.1"
reqwest = { version = "0.12.4", features = ["stream"] }
url = "2.5.0"
virt = "0.3.1"
sysinfo = { version = "0.30.11", features = ["serde"] }
uuid = { version = "1.8.0", features = ["v4", "serde"] }
lazy-regex = "3.1.0"
thiserror = "1.0.59"
image = "0.25.1"
rand = "0.8.5"
bytes = "1.6.0"
tokio = "1.37.0"
futures = "0.3.30"
ipnetwork = "0.20.0"
num = "0.4.2"
rust-embed = { version = "8.3.0" }
mime_guess = "2.0.4"
dotenvy = "0.15.7"
nix = { version = "0.29.0", features = ["net"] }
basic-jwt = "0.3.0"
nix = { version = "0.28.0", features = ["net"] }
basic-jwt = "0.2.0"

View File

@ -1,8 +1,9 @@
services:
oidc:
image: dexidp/dex
image: qlik/simple-oidc-provider
environment:
- REDIRECTS=http://localhost:3000/oidc_cb,http://localhost:5173/oidc_cb
- PORT=9001
ports:
- 9001:9001
volumes:
- ./docker/dex:/conf:ro
command: [ "dex", "serve", "/conf/dex.config.yaml" ]
- 9001:9001

View File

@ -1,27 +0,0 @@
issuer: http://127.0.0.1:9001/dex
storage:
type: memory
web:
http: 0.0.0.0:9001
oauth2:
# Automate some clicking
# Note: this might actually make some tests pass that otherwise wouldn't.
skipApprovalScreen: false
connectors:
# Note: this might actually make some tests pass that otherwise wouldn't.
- type: mockCallback
id: mock
name: Example
# Basic OP test suite requires two clients.
staticClients:
- id: foo
secret: bar
redirectURIs:
- http://localhost:3000/oidc_cb
- http://localhost:5173/oidc_cb
name: Project

View File

@ -55,13 +55,12 @@ fn main() {
let jwt = key.sign_jwt(&claims).expect("Failed to sign JWT!");
let err = Command::new("curl")
Command::new("curl")
.args(["-X", &args.verb])
.args(["-H", &format!("x-token-id: {}", args.token_id)])
.args(["-H", &format!("x-token-content: {jwt}")])
.args(args.run)
.arg(full_url)
.exec();
panic!("Failed to run cURL! {err}")
panic!("Failed to run curl!")
}

View File

@ -31,7 +31,7 @@ impl LibVirtActor {
"Will connect to hypvervisor at address '{}'",
hypervisor_uri
);
let conn = Connect::open(Some(hypervisor_uri))?;
let conn = Connect::open(hypervisor_uri)?;
Ok(Self { m: conn })
}

View File

@ -1,3 +1,3 @@
pub mod libvirt_actor;
pub mod vnc_handler;
pub mod vnc_actor;
pub mod vnc_tokens_actor;

View File

@ -0,0 +1,209 @@
use actix::{Actor, ActorContext, AsyncContext, Handler, StreamHandler};
use actix_http::ws::Item;
use actix_web_actors::ws;
use actix_web_actors::ws::Message;
use bytes::Bytes;
use image::EncodableLayout;
use std::path::Path;
use std::time::{Duration, Instant};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::unix::{OwnedReadHalf, OwnedWriteHalf};
use tokio::net::UnixStream;
/// How often heartbeat pings are sent
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
/// How long before lack of client response causes a timeout
const CLIENT_TIMEOUT: Duration = Duration::from_secs(20);
#[derive(thiserror::Error, Debug)]
enum VNCError {
#[error("Socket file does not exists!")]
SocketDoesNotExists,
}
pub struct VNCActor {
/// Qemu -> WS
read_half: Option<OwnedReadHalf>,
/// WS -> Qemu
write_half: OwnedWriteHalf,
// Client must respond to ping at a specific interval, otherwise we drop connection
hb: Instant,
}
impl VNCActor {
pub async fn new(socket_path: &str) -> anyhow::Result<Self> {
let socket_path = Path::new(socket_path);
if !socket_path.exists() {
return Err(VNCError::SocketDoesNotExists.into());
}
let socket = UnixStream::connect(socket_path).await?;
let (read_half, write_half) = socket.into_split();
Ok(Self {
read_half: Some(read_half),
write_half,
hb: Instant::now(),
})
}
/// helper method that sends ping to client every second.
///
/// also this method checks heartbeats from client
fn hb(&self, ctx: &mut ws::WebsocketContext<Self>) {
ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {
// check client heartbeats
if Instant::now().duration_since(act.hb) > CLIENT_TIMEOUT {
// heartbeat timed out
log::warn!("WebSocket Client heartbeat failed, disconnecting!");
ctx.stop();
return;
}
ctx.ping(b"");
});
}
fn send_to_socket(&mut self, bytes: Bytes, ctx: &mut ws::WebsocketContext<Self>) {
log::trace!("Received {} bytes for VNC socket", bytes.len());
if let Err(e) = futures::executor::block_on(self.write_half.write(bytes.as_bytes())) {
log::error!("Failed to relay bytes to VNC socket {e}");
ctx.close(None);
}
}
fn start_qemu_to_ws_end(&mut self, ctx: &mut ws::WebsocketContext<Self>) {
let mut read_half = self.read_half.take().unwrap();
let addr = ctx.address();
let future = async move {
let mut buff: [u8; 5000] = [0; 5000];
loop {
match read_half.read(&mut buff).await {
Ok(mut l) => {
if l == 0 {
log::warn!("Got empty read!");
// Ugly hack made to wait for next byte
let mut one_byte_buff: [u8; 1] = [0; 1];
match read_half.read_exact(&mut one_byte_buff).await {
Ok(b) => {
if b == 0 {
log::error!("Did not get a byte !");
let _ = addr.send(CloseWebSocketReq).await;
break;
}
buff[0] = one_byte_buff[0];
l = 1;
}
Err(e) => {
log::error!("Failed to read 1 BYTE from remote socket. Stopping now... {:?}", e);
break;
}
}
}
let to_send = SendBytesReq(Vec::from(&buff[0..l]));
if let Err(e) = addr.send(to_send).await {
log::error!("Failed to send to websocket. Stopping now... {:?}", e);
return;
}
}
Err(e) => {
log::error!("Failed to read from remote socket. Stopping now... {:?}", e);
break;
}
};
}
log::info!("Exited read loop");
};
tokio::spawn(future);
}
}
impl Actor for VNCActor {
type Context = ws::WebsocketContext<Self>;
fn started(&mut self, ctx: &mut Self::Context) {
self.hb(ctx);
self.start_qemu_to_ws_end(ctx);
}
}
impl StreamHandler<Result<Message, ws::ProtocolError>> for VNCActor {
fn handle(&mut self, msg: Result<Message, ws::ProtocolError>, ctx: &mut Self::Context) {
match msg {
Ok(Message::Ping(msg)) => ctx.pong(&msg),
Ok(Message::Text(_text)) => {
log::error!("Received unexpected text on VNC WebSocket!");
}
Ok(Message::Binary(bin)) => {
log::info!("Forward {} bytes to VNC server", bin.len());
self.send_to_socket(bin, ctx);
}
Ok(Message::Continuation(msg)) => match msg {
Item::FirstText(_) => {
log::error!("Received unexpected split text!");
ctx.close(None);
}
Item::FirstBinary(bin) | Item::Continue(bin) | Item::Last(bin) => {
self.send_to_socket(bin, ctx);
}
},
Ok(Message::Pong(_)) => {
log::trace!("Received PONG message");
self.hb = Instant::now();
}
Ok(Message::Close(r)) => {
log::info!("WebSocket closed. Reason={r:?}");
ctx.close(r);
}
Ok(Message::Nop) => {
log::debug!("Received Nop message")
}
Err(e) => {
log::error!("WebSocket protocol error! {e}");
ctx.close(None)
}
}
}
}
#[derive(actix::Message)]
#[rtype(result = "()")]
pub struct SendBytesReq(Vec<u8>);
impl Handler<SendBytesReq> for VNCActor {
type Result = ();
fn handle(&mut self, msg: SendBytesReq, ctx: &mut Self::Context) -> Self::Result {
log::trace!("Send {} bytes to WS", msg.0.len());
ctx.binary(msg.0);
}
}
#[derive(actix::Message)]
#[rtype(result = "()")]
pub struct CloseWebSocketReq;
impl Handler<CloseWebSocketReq> for VNCActor {
type Result = ();
fn handle(&mut self, _msg: CloseWebSocketReq, ctx: &mut Self::Context) -> Self::Result {
log::trace!("Close websocket, because VNC socket has terminated");
ctx.close(None);
}
}

View File

@ -1,129 +0,0 @@
use actix_http::ws::Message;
use futures_util::StreamExt as _;
use std::time::{Duration, Instant};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::UnixStream;
use tokio::select;
use tokio::time::interval;
/// How often heartbeat pings are sent
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
/// How long before lack of client response causes a timeout
const CLIENT_TIMEOUT: Duration = Duration::from_secs(20);
/// Broadcast text & binary messages received from a client, respond to ping messages, and monitor
/// connection health to detect network issues and free up resources.
pub async fn handle(
mut session: actix_ws::Session,
mut msg_stream: actix_ws::MessageStream,
mut socket: UnixStream,
) {
log::info!("Connected to websocket");
let mut last_heartbeat = Instant::now();
let mut interval = interval(HEARTBEAT_INTERVAL);
let mut buf_socket = [0u8; 1024];
let reason = loop {
// waits for either `msg_stream` to receive a message from the client, the broadcast channel
// to send a message, or the heartbeat interval timer to tick, yielding the value of
// whichever one is ready first
select! {
// heartbeat interval ticked
_tick = interval.tick() => {
// if no heartbeat ping/pong received recently, close the connection
if Instant::now().duration_since(last_heartbeat) > CLIENT_TIMEOUT {
log::info!(
"client has not sent heartbeat in over {CLIENT_TIMEOUT:?}; disconnecting"
);
break None;
}
// send heartbeat ping
let _ = session.ping(b"").await;
}
msg = msg_stream.next() => {
let msg = match msg {
// received message from WebSocket client
Some(Ok(msg)) => msg,
// client WebSocket stream error
Some(Err(err)) => {
log::error!("{err}");
break None;
}
// client WebSocket stream ended
None => break None
};
log::debug!("msg: {msg:?}");
match msg {
Message::Text(_) => {
log::error!("Received unexpected text on VNC WebSocket!");
}
Message::Binary(bin) => {
log::info!("Forward {} bytes to VNC server", bin.len());
if let Err(e) = socket.write(&bin).await {
log::error!("Failed to relay bytes to VNC socket {e}");
break None;
}
}
Message::Close(reason) => {
break reason;
}
Message::Ping(bytes) => {
last_heartbeat = Instant::now();
let _ = session.pong(&bytes).await;
}
Message::Pong(_) => {
last_heartbeat = Instant::now();
}
Message::Continuation(_) => {
log::warn!("no support for continuation frames");
}
// no-op; ignore
Message::Nop => {}
};
}
// Forward socket packet to WS client
count = socket.read(&mut buf_socket) => {
let count = match count {
Ok(count) => count,
Err(e) => {
log::error!("[VNC] Failed to read from upstream! {e}");
break None;
}
};
if count == 0 {
log::warn!("[VNC] infinite loop (upstream), closing connection");
break None;
}
if let Err(e)=session.binary(buf_socket[0..count].to_vec()).await{
log::error!("[VNC] Failed to forward messages to upstream, will close connection! {e}");
break None
}
}
}
};
// attempt to close connection gracefully
let _ = session.close(reason).await;
log::info!("Disconnected from websocket");
}

View File

@ -68,7 +68,7 @@ pub struct AppConfig {
#[arg(
long,
env,
default_value = "http://localhost:9001/dex/.well-known/openid-configuration"
default_value = "http://localhost:9001/.well-known/openid-configuration"
)]
pub oidc_configuration_url: String,

View File

@ -2,9 +2,9 @@
use crate::api_tokens;
use crate::api_tokens::{NewToken, TokenID, TokenRights};
use crate::controllers::HttpResult;
use crate::controllers::api_tokens_controller::rest_token::RestToken;
use actix_web::{HttpResponse, web};
use crate::controllers::HttpResult;
use actix_web::{web, HttpResponse};
use basic_jwt::JWTPrivateKey;
/// Create a special module for REST token to enforce usage of constructor function

View File

@ -1,6 +1,6 @@
use actix_remote_ip::RemoteIP;
use actix_web::web::Data;
use actix_web::{HttpResponse, Responder, web};
use actix_web::{web, HttpResponse, Responder};
use light_openid::basic_state_manager::BasicStateManager;
use crate::app_config::AppConfig;

View File

@ -1,148 +0,0 @@
use crate::controllers::{HttpResult, LibVirtReq};
use crate::extractors::group_vm_id_extractor::GroupVmIdExtractor;
use crate::libvirt_rest_structures::vm::VMInfo;
use actix_web::HttpResponse;
use std::collections::HashMap;
/// Get the list of groups
pub async fn list(client: LibVirtReq) -> HttpResult {
let groups = match client.get_full_groups_list().await {
Err(e) => {
log::error!("Failed to get the list of groups! {e}");
return Ok(HttpResponse::InternalServerError()
.json(format!("Failed to get the list of groups! {e}")));
}
Ok(l) => l,
};
Ok(HttpResponse::Ok().json(groups))
}
/// Get information about the VMs of a group
pub async fn vm_info(vms_xml: GroupVmIdExtractor) -> HttpResult {
let mut vms = Vec::new();
for vm in vms_xml.0 {
vms.push(VMInfo::from_domain(vm)?)
}
Ok(HttpResponse::Ok().json(vms))
}
#[derive(Default, serde::Serialize)]
pub struct TreatmentResult {
ok: usize,
failed: usize,
}
/// Start the VMs of a group
pub async fn vm_start(client: LibVirtReq, vms: GroupVmIdExtractor) -> HttpResult {
let mut res = TreatmentResult::default();
for vm in vms.0 {
if let Some(uuid) = vm.uuid {
match client.start_domain(uuid).await {
Ok(_) => res.ok += 1,
Err(_) => res.failed += 1,
}
}
}
Ok(HttpResponse::Ok().json(res))
}
/// Shutdown the VMs of a group
pub async fn vm_shutdown(client: LibVirtReq, vms: GroupVmIdExtractor) -> HttpResult {
let mut res = TreatmentResult::default();
for vm in vms.0 {
if let Some(uuid) = vm.uuid {
match client.shutdown_domain(uuid).await {
Ok(_) => res.ok += 1,
Err(_) => res.failed += 1,
}
}
}
Ok(HttpResponse::Ok().json(res))
}
/// Suspend the VMs of a group
pub async fn vm_suspend(client: LibVirtReq, vms: GroupVmIdExtractor) -> HttpResult {
let mut res = TreatmentResult::default();
for vm in vms.0 {
if let Some(uuid) = vm.uuid {
match client.suspend_domain(uuid).await {
Ok(_) => res.ok += 1,
Err(_) => res.failed += 1,
}
}
}
Ok(HttpResponse::Ok().json(res))
}
/// Resume the VMs of a group
pub async fn vm_resume(client: LibVirtReq, vms: GroupVmIdExtractor) -> HttpResult {
let mut res = TreatmentResult::default();
for vm in vms.0 {
if let Some(uuid) = vm.uuid {
match client.resume_domain(uuid).await {
Ok(_) => res.ok += 1,
Err(_) => res.failed += 1,
}
}
}
Ok(HttpResponse::Ok().json(res))
}
/// Kill the VMs of a group
pub async fn vm_kill(client: LibVirtReq, vms: GroupVmIdExtractor) -> HttpResult {
let mut res = TreatmentResult::default();
for vm in vms.0 {
if let Some(uuid) = vm.uuid {
match client.kill_domain(uuid).await {
Ok(_) => res.ok += 1,
Err(_) => res.failed += 1,
}
}
}
Ok(HttpResponse::Ok().json(res))
}
/// Reset the VMs of a group
pub async fn vm_reset(client: LibVirtReq, vms: GroupVmIdExtractor) -> HttpResult {
let mut res = TreatmentResult::default();
for vm in vms.0 {
if let Some(uuid) = vm.uuid {
match client.reset_domain(uuid).await {
Ok(_) => res.ok += 1,
Err(_) => res.failed += 1,
}
}
}
Ok(HttpResponse::Ok().json(res))
}
/// Get the screenshot of the VMs of a group
pub async fn vm_screenshot(client: LibVirtReq, vms: GroupVmIdExtractor) -> HttpResult {
if vms.0.is_empty() {
return Ok(HttpResponse::NoContent().finish());
}
let image = if vms.0.len() == 1 {
client.screenshot_domain(vms.0[0].uuid.unwrap()).await?
} else {
return Ok(
HttpResponse::UnprocessableEntity().json("Cannot return multiple VM screenshots!!")
);
};
Ok(HttpResponse::Ok().content_type("image/png").body(image))
}
/// Get the state of the VMs
pub async fn vm_state(client: LibVirtReq, vms: GroupVmIdExtractor) -> HttpResult {
let mut states = HashMap::new();
for vm in vms.0 {
if let Some(uuid) = vm.uuid {
states.insert(uuid, client.get_domain_state(uuid).await?);
}
}
Ok(HttpResponse::Ok().json(states))
}

View File

@ -3,9 +3,9 @@ use crate::constants;
use crate::controllers::HttpResult;
use crate::utils::files_utils;
use actix_files::NamedFile;
use actix_multipart::form::MultipartForm;
use actix_multipart::form::tempfile::TempFile;
use actix_web::{HttpRequest, HttpResponse, web};
use actix_multipart::form::MultipartForm;
use actix_web::{web, HttpRequest, HttpResponse};
use futures_util::StreamExt;
use std::fs::File;
use std::io::Write;

View File

@ -1,14 +1,13 @@
use crate::libvirt_client::LibVirtClient;
use actix_http::StatusCode;
use actix_web::body::BoxBody;
use actix_web::{HttpResponse, web};
use actix_web::{web, HttpResponse};
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::io::ErrorKind;
pub mod api_tokens_controller;
pub mod auth_controller;
pub mod groups_controller;
pub mod iso_controller;
pub mod network_controller;
pub mod nwfilter_controller;

View File

@ -1,7 +1,7 @@
use crate::controllers::{HttpResult, LibVirtReq};
use crate::libvirt_lib_structures::XMLUuid;
use crate::libvirt_rest_structures::net::NetworkInfo;
use actix_web::{HttpResponse, web};
use actix_web::{web, HttpResponse};
#[derive(serde::Serialize, serde::Deserialize)]
pub struct NetworkID {

View File

@ -2,7 +2,7 @@ use crate::constants;
use crate::controllers::{HttpResult, LibVirtReq};
use crate::libvirt_lib_structures::XMLUuid;
use crate::libvirt_rest_structures::nw_filter::NetworkFilter;
use actix_web::{HttpResponse, web};
use actix_web::{web, HttpResponse};
#[derive(serde::Serialize, serde::Deserialize)]
pub struct NetworkFilterID {

View File

@ -40,7 +40,6 @@ struct ServerConstraints {
vnc_token_duration: u64,
vm_name_size: LenConstraints,
vm_title_size: LenConstraints,
group_id_size: LenConstraints,
memory_size: LenConstraints,
disk_name_size: LenConstraints,
disk_size: LenConstraints,
@ -73,7 +72,6 @@ pub async fn static_config(local_auth: LocalAuthEnabled) -> impl Responder {
vm_name_size: LenConstraints { min: 2, max: 50 },
vm_title_size: LenConstraints { min: 0, max: 50 },
group_id_size: LenConstraints { min: 3, max: 50 },
memory_size: LenConstraints {
min: constants::MIN_VM_MEMORY,
max: constants::MAX_VM_MEMORY,
@ -136,13 +134,16 @@ pub async fn server_info(client: LibVirtReq) -> HttpResult {
system.refresh_all();
let mut components = Components::new();
components.refresh(true);
components.refresh_list();
components.refresh();
let mut disks = Disks::new();
disks.refresh(true);
disks.refresh_list();
disks.refresh();
let mut networks = Networks::new();
networks.refresh(true);
networks.refresh_list();
networks.refresh();
Ok(HttpResponse::Ok().json(ServerInfo {
hypervisor: client.get_info().await?,
@ -170,7 +171,7 @@ pub async fn network_hook_status() -> HttpResult {
pub async fn number_vcpus() -> HttpResult {
let mut system = System::new();
system.refresh_cpu_all();
system.refresh_cpu();
let number_cpus = system.cpus().len();
assert_ne!(number_cpus, 0, "Got invlid number of CPU!");

View File

@ -18,7 +18,7 @@ mod serve_static_debug {
#[cfg(not(debug_assertions))]
mod serve_static_release {
use actix_web::{HttpResponse, Responder, web};
use actix_web::{web, HttpResponse, Responder};
use rust_embed::RustEmbed;
#[derive(RustEmbed)]

View File

@ -1,12 +1,11 @@
use crate::actors::vnc_handler;
use crate::actors::vnc_actor::VNCActor;
use crate::actors::vnc_tokens_actor::VNCTokensManager;
use crate::controllers::{HttpResult, LibVirtReq};
use crate::libvirt_lib_structures::XMLUuid;
use crate::libvirt_lib_structures::domain::DomainState;
use crate::libvirt_lib_structures::XMLUuid;
use crate::libvirt_rest_structures::vm::VMInfo;
use actix_web::{HttpRequest, HttpResponse, rt, web};
use std::path::Path;
use tokio::net::UnixStream;
use actix_web::{web, HttpRequest, HttpResponse};
use actix_web_actors::ws;
#[derive(serde::Serialize)]
struct VMInfoAndState {
@ -22,7 +21,7 @@ struct VMUuid {
/// Create a new VM
pub async fn create(client: LibVirtReq, req: web::Json<VMInfo>) -> HttpResult {
let domain = match req.0.as_domain() {
let domain = match req.0.as_tomain() {
Ok(d) => d,
Err(e) => {
log::error!("Failed to extract domain info! {e}");
@ -84,8 +83,6 @@ pub async fn get_single(client: LibVirtReq, id: web::Path<SingleVMUUidReq>) -> H
}
};
log::debug!("INFO={info:#?}");
let state = client.get_domain_state(id.uid).await?;
Ok(HttpResponse::Ok().json(VMInfoAndState {
@ -115,7 +112,7 @@ pub async fn update(
id: web::Path<SingleVMUUidReq>,
req: web::Json<VMInfo>,
) -> HttpResult {
let mut domain = match req.0.as_domain() {
let mut domain = match req.0.as_tomain() {
Ok(d) => d,
Err(e) => {
log::error!("Failed to extract domain info! {e}");
@ -325,19 +322,5 @@ pub async fn vnc(
};
log::info!("Start VNC connection on socket {socket_path}");
let socket_path = Path::new(&socket_path);
if !socket_path.exists() {
log::error!("VNC socket path {socket_path:?} does not exist!");
return Ok(HttpResponse::ServiceUnavailable().json("VNC socket path does not exists!"));
}
let socket = UnixStream::connect(socket_path).await?;
let (res, session, msg_stream) = actix_ws::handle(&req, stream)?;
// spawn websocket handler (and don't await it) so that the response is returned immediately
rt::spawn(vnc_handler::handle(session, msg_stream, socket));
Ok(res)
Ok(ws::start(VNCActor::new(&socket_path).await?, &req, stream)?)
}

View File

@ -1,7 +1,7 @@
use actix_identity::Identity;
use actix_web::dev::Payload;
use actix_web::{Error, FromRequest, HttpMessage, HttpRequest};
use futures_util::future::{Ready, ready};
use futures_util::future::{ready, Ready};
use std::fmt::Display;
pub struct AuthExtractor {

View File

@ -1,66 +0,0 @@
use crate::controllers::LibVirtReq;
use crate::libvirt_lib_structures::XMLUuid;
use crate::libvirt_lib_structures::domain::DomainXML;
use crate::libvirt_rest_structures::vm::VMGroupId;
use actix_http::Payload;
use actix_web::error::ErrorBadRequest;
use actix_web::web::Query;
use actix_web::{Error, FromRequest, HttpRequest, web};
use std::future::Future;
use std::pin::Pin;
pub struct GroupVmIdExtractor(pub Vec<DomainXML>);
#[derive(serde::Deserialize)]
struct GroupIDInPath {
gid: VMGroupId,
}
#[derive(serde::Deserialize)]
struct FilterVM {
vm_id: Option<XMLUuid>,
}
impl FromRequest for GroupVmIdExtractor {
type Error = Error;
type Future = Pin<Box<dyn Future<Output = Result<Self, Self::Error>>>>;
fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
let req = req.clone();
Box::pin(async move {
let Ok(group_id) =
web::Path::<GroupIDInPath>::from_request(&req, &mut Payload::None).await
else {
return Err(ErrorBadRequest("Group ID not specified in path!"));
};
let group_id = group_id.into_inner().gid;
let filter_vm = match Query::<FilterVM>::from_request(&req, &mut Payload::None).await {
Ok(v) => v,
Err(e) => {
log::error!("Failed to extract VM id from request! {e}");
return Err(ErrorBadRequest("Failed to extract VM id from request!"));
}
};
let Ok(client) = LibVirtReq::from_request(&req, &mut Payload::None).await else {
return Err(ErrorBadRequest("Failed to extract client handle!"));
};
let vms = match client.get_full_group_vm_list(&group_id).await {
Ok(vms) => vms,
Err(e) => {
log::error!("Failed to get the VMs of the group {group_id:?}: {e}");
return Err(ErrorBadRequest("Failed to get the VMs of the group!"));
}
};
// Filter (if requested by the user)
Ok(GroupVmIdExtractor(match filter_vm.vm_id {
None => vms,
Some(id) => vms.into_iter().filter(|vms| vms.uuid == Some(id)).collect(),
}))
})
}
}

View File

@ -1,7 +1,7 @@
use crate::app_config::AppConfig;
use actix_web::dev::Payload;
use actix_web::{Error, FromRequest, HttpRequest};
use futures_util::future::{Ready, ready};
use futures_util::future::{ready, Ready};
use std::ops::Deref;
#[derive(Debug, Copy, Clone, PartialEq)]

View File

@ -1,4 +1,3 @@
pub mod api_auth_extractor;
pub mod auth_extractor;
pub mod group_vm_id_extractor;
pub mod local_auth_extractor;

View File

@ -1,15 +1,14 @@
use crate::actors::libvirt_actor;
use crate::actors::libvirt_actor::LibVirtActor;
use crate::libvirt_lib_structures::XMLUuid;
use crate::libvirt_lib_structures::domain::{DomainState, DomainXML};
use crate::libvirt_lib_structures::network::NetworkXML;
use crate::libvirt_lib_structures::nwfilter::NetworkFilterXML;
use crate::libvirt_lib_structures::XMLUuid;
use crate::libvirt_rest_structures::hypervisor::HypervisorInfo;
use crate::libvirt_rest_structures::net::NetworkInfo;
use crate::libvirt_rest_structures::nw_filter::NetworkFilter;
use crate::libvirt_rest_structures::vm::{VMGroupId, VMInfo};
use crate::libvirt_rest_structures::vm::VMInfo;
use actix::Addr;
use std::collections::HashSet;
#[derive(Clone)]
pub struct LibVirtClient(pub Addr<LibVirtActor>);
@ -108,35 +107,6 @@ impl LibVirtClient {
.await?
}
/// Get the full list of groups
pub async fn get_full_groups_list(&self) -> anyhow::Result<Vec<VMGroupId>> {
let domains = self.get_full_domains_list().await?;
let mut out = HashSet::new();
for d in domains {
if let Some(g) = VMInfo::from_domain(d)?.group {
out.insert(g);
}
}
let mut out: Vec<_> = out.into_iter().collect();
out.sort();
Ok(out)
}
/// Get the full list of VMs of a given group
pub async fn get_full_group_vm_list(
&self,
group: &VMGroupId,
) -> anyhow::Result<Vec<DomainXML>> {
let vms = self.get_full_domains_list().await?;
let mut out = Vec::new();
for vm in vms {
if VMInfo::from_domain(vm.clone())?.group == Some(group.clone()) {
out.push(vm);
}
}
Ok(out)
}
/// Update a network configuration
pub async fn update_network(
&self,

View File

@ -1,25 +1,7 @@
use crate::libvirt_lib_structures::XMLUuid;
/// VirtWeb specific metadata
#[derive(serde::Serialize, serde::Deserialize, Default, Debug, Clone)]
#[serde(rename = "virtweb", default)]
pub struct DomainMetadataVirtWebXML {
#[serde(rename = "@xmlns:virtweb", default)]
pub ns: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub group: Option<String>,
}
/// Domain metadata
#[derive(serde::Serialize, serde::Deserialize, Default, Debug, Clone)]
#[serde(rename = "metadata")]
pub struct DomainMetadataXML {
#[serde(rename = "virtweb:metadata", default)]
pub virtweb: DomainMetadataVirtWebXML,
}
/// OS information
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "os")]
pub struct OSXML {
#[serde(rename = "@firmware", default)]
@ -29,7 +11,7 @@ pub struct OSXML {
}
/// OS Type information
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "os")]
pub struct OSTypeXML {
#[serde(rename = "@arch")]
@ -41,7 +23,7 @@ pub struct OSTypeXML {
}
/// OS Loader information
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "loader")]
pub struct OSLoaderXML {
#[serde(rename = "@secure")]
@ -49,39 +31,39 @@ pub struct OSLoaderXML {
}
/// Hypervisor features
#[derive(serde::Serialize, serde::Deserialize, Clone, Default, Debug)]
#[derive(serde::Serialize, serde::Deserialize, Default)]
#[serde(rename = "features")]
pub struct FeaturesXML {
pub acpi: ACPIXML,
}
/// ACPI feature
#[derive(serde::Serialize, serde::Deserialize, Clone, Default, Debug)]
#[derive(serde::Serialize, serde::Deserialize, Default)]
#[serde(rename = "acpi")]
pub struct ACPIXML {}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "mac")]
pub struct NetMacAddress {
#[serde(rename = "@address")]
pub address: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "source")]
pub struct NetIntSourceXML {
#[serde(rename = "@network")]
pub network: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "model")]
pub struct NetIntModelXML {
#[serde(rename = "@type")]
pub r#type: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "filterref")]
pub struct NetIntFilterParameterXML {
#[serde(rename = "@name")]
@ -90,7 +72,7 @@ pub struct NetIntFilterParameterXML {
pub value: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "filterref")]
pub struct NetIntfilterRefXML {
#[serde(rename = "@filter")]
@ -99,7 +81,7 @@ pub struct NetIntfilterRefXML {
pub parameters: Vec<NetIntFilterParameterXML>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "interface")]
pub struct DomainNetInterfaceXML {
#[serde(rename = "@type")]
@ -113,14 +95,14 @@ pub struct DomainNetInterfaceXML {
pub filterref: Option<NetIntfilterRefXML>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "input")]
pub struct DomainInputXML {
#[serde(rename = "@type")]
pub r#type: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "backend")]
pub struct TPMBackendXML {
#[serde(rename = "@type")]
@ -130,7 +112,7 @@ pub struct TPMBackendXML {
pub r#version: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "tpm")]
pub struct TPMDeviceXML {
#[serde(rename = "@model")]
@ -139,7 +121,7 @@ pub struct TPMDeviceXML {
}
/// Devices information
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "devices")]
pub struct DevicesXML {
/// Graphics (used for VNC)
@ -168,7 +150,7 @@ pub struct DevicesXML {
}
/// Graphics information
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "graphics")]
pub struct GraphicsXML {
#[serde(rename = "@type")]
@ -178,14 +160,14 @@ pub struct GraphicsXML {
}
/// Video device information
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "video")]
pub struct VideoXML {
pub model: VideoModelXML,
}
/// Video model device information
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "model")]
pub struct VideoModelXML {
#[serde(rename = "@type")]
@ -193,7 +175,7 @@ pub struct VideoModelXML {
}
/// Disk information
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "disk")]
pub struct DiskXML {
#[serde(rename = "@type")]
@ -211,7 +193,7 @@ pub struct DiskXML {
pub address: Option<DiskAddressXML>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "driver")]
pub struct DiskDriverXML {
#[serde(rename = "@name")]
@ -222,14 +204,14 @@ pub struct DiskDriverXML {
pub r#cache: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "source")]
pub struct DiskSourceXML {
#[serde(rename = "@file")]
pub file: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "target")]
pub struct DiskTargetXML {
#[serde(rename = "@dev")]
@ -238,18 +220,18 @@ pub struct DiskTargetXML {
pub bus: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "readonly")]
pub struct DiskReadOnlyXML {}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "boot")]
pub struct DiskBootXML {
#[serde(rename = "@order")]
pub order: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "address")]
pub struct DiskAddressXML {
#[serde(rename = "@type")]
@ -269,7 +251,7 @@ pub struct DiskAddressXML {
}
/// Domain RAM information
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "memory")]
pub struct DomainMemoryXML {
#[serde(rename = "@unit")]
@ -279,7 +261,7 @@ pub struct DomainMemoryXML {
pub memory: usize,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "topology")]
pub struct DomainCPUTopology {
#[serde(rename = "@sockets")]
@ -290,14 +272,14 @@ pub struct DomainCPUTopology {
pub threads: usize,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "cpu")]
pub struct DomainVCPUXML {
#[serde(rename = "$value")]
pub body: usize,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "cpu")]
pub struct DomainCPUXML {
#[serde(rename = "@mode")]
@ -306,7 +288,7 @@ pub struct DomainCPUXML {
}
/// Domain information, see https://libvirt.org/formatdomain.html
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename = "domain")]
pub struct DomainXML {
/// Domain type (kvm)
@ -318,9 +300,6 @@ pub struct DomainXML {
pub genid: Option<uuid::Uuid>,
pub title: Option<String>,
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub metadata: Option<DomainMetadataXML>,
pub os: OSXML,
#[serde(default)]
pub features: FeaturesXML,
@ -340,32 +319,10 @@ pub struct DomainXML {
pub on_crash: String,
}
const METADATA_START_MARKER: &str =
"<virtweb:metadata xmlns:virtweb=\"https://virtweb.communiquons.org\">";
const METADATA_END_MARKER: &str = "</virtweb:metadata>";
impl DomainXML {
/// Decode Domain structure from XML definition
pub fn parse_xml(xml: &str) -> anyhow::Result<Self> {
let mut res: Self = quick_xml::de::from_str(xml)?;
// Handle custom metadata parsing issue
//
// https://github.com/tafia/quick-xml/pull/797
if xml.contains(METADATA_START_MARKER) && xml.contains(METADATA_END_MARKER) {
let s = xml
.split_once(METADATA_START_MARKER)
.unwrap()
.1
.split_once(METADATA_END_MARKER)
.unwrap()
.0;
let s = format!("<virtweb>{s}</virtweb>");
let metadata: DomainMetadataVirtWebXML = quick_xml::de::from_str(&s)?;
res.metadata = Some(DomainMetadataXML { virtweb: metadata });
}
Ok(res)
Ok(quick_xml::de::from_str(xml)?)
}
/// Turn this domain into its XML definition

View File

@ -1,4 +1,4 @@
#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, Eq, PartialEq, Hash)]
#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug)]
pub struct XMLUuid(pub uuid::Uuid);
impl XMLUuid {

View File

@ -1,5 +1,5 @@
use crate::libvirt_lib_structures::XMLUuid;
use crate::libvirt_lib_structures::network::*;
use crate::libvirt_lib_structures::XMLUuid;
use crate::libvirt_rest_structures::LibVirtStructError::StructureExtraction;
use crate::nat::nat_definition::Nat;
use crate::nat::nat_lib;

View File

@ -1,9 +1,9 @@
use crate::libvirt_lib_structures::XMLUuid;
use crate::libvirt_lib_structures::nwfilter::{
NetworkFilterRefXML, NetworkFilterRuleProtocolAllXML, NetworkFilterRuleProtocolArpXML,
NetworkFilterRuleProtocolIpvx, NetworkFilterRuleProtocolLayer4, NetworkFilterRuleProtocolMac,
NetworkFilterRuleXML, NetworkFilterXML,
};
use crate::libvirt_lib_structures::XMLUuid;
use crate::libvirt_rest_structures::LibVirtStructError;
use crate::libvirt_rest_structures::LibVirtStructError::{
NetworkFilterExtraction, StructureExtraction,

View File

@ -1,7 +1,7 @@
use crate::app_config::AppConfig;
use crate::constants;
use crate::libvirt_lib_structures::XMLUuid;
use crate::libvirt_lib_structures::domain::*;
use crate::libvirt_lib_structures::XMLUuid;
use crate::libvirt_rest_structures::LibVirtStructError;
use crate::libvirt_rest_structures::LibVirtStructError::StructureExtraction;
use crate::utils::disks_utils::Disk;
@ -10,11 +10,6 @@ use crate::utils::files_utils::convert_size_unit_to_mb;
use lazy_regex::regex;
use num::Integer;
#[derive(
Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, Ord, PartialOrd,
)]
pub struct VMGroupId(pub String);
#[derive(serde::Serialize, serde::Deserialize)]
pub enum BootType {
UEFI,
@ -64,9 +59,6 @@ pub struct VMInfo {
pub genid: Option<XMLUuid>,
pub title: Option<String>,
pub description: Option<String>,
/// Group associated with the VM (VirtWeb specific field)
#[serde(skip_serializing_if = "Option::is_none")]
pub group: Option<VMGroupId>,
pub boot_type: BootType,
pub architecture: VMArchitecture,
/// VM allocated memory, in megabytes
@ -87,7 +79,7 @@ pub struct VMInfo {
impl VMInfo {
/// Turn this VM into a domain
pub fn as_domain(&self) -> anyhow::Result<DomainXML> {
pub fn as_tomain(&self) -> anyhow::Result<DomainXML> {
if !regex!("^[a-zA-Z0-9]+$").is_match(&self.name) {
return Err(StructureExtraction("VM name is invalid!").into());
}
@ -113,12 +105,6 @@ impl VMInfo {
}
}
if let Some(group) = &self.group {
if !regex!("^[a-zA-Z0-9]+$").is_match(&group.0) {
return Err(StructureExtraction("VM group name is invalid!").into());
}
}
if self.memory < constants::MIN_VM_MEMORY || self.memory > constants::MAX_VM_MEMORY {
return Err(StructureExtraction("VM memory is invalid!").into());
}
@ -296,12 +282,6 @@ impl VMInfo {
title: self.title.clone(),
description: self.description.clone(),
metadata: Some(DomainMetadataXML {
virtweb: DomainMetadataVirtWebXML {
ns: "https://virtweb.communiquons.org".to_string(),
group: self.group.clone().map(|g| g.0),
},
}),
os: OSXML {
r#type: OSTypeXML {
arch: match self.architecture {
@ -389,13 +369,6 @@ impl VMInfo {
genid: domain.genid.map(XMLUuid),
title: domain.title,
description: domain.description,
group: domain
.metadata
.clone()
.unwrap_or_default()
.virtweb
.group
.map(VMGroupId),
boot_type: match domain.os.loader {
None => BootType::UEFI,
Some(l) => match l.secure.as_str() {

View File

@ -1,17 +1,17 @@
use actix::Actor;
use actix_cors::Cors;
use actix_identity::IdentityMiddleware;
use actix_identity::config::LogoutBehaviour;
use actix_multipart::form::MultipartFormConfig;
use actix_identity::IdentityMiddleware;
use actix_multipart::form::tempfile::TempFileConfig;
use actix_multipart::form::MultipartFormConfig;
use actix_remote_ip::RemoteIPConfig;
use actix_session::SessionMiddleware;
use actix_session::storage::CookieSessionStore;
use actix_session::SessionMiddleware;
use actix_web::cookie::{Key, SameSite};
use actix_web::http::header;
use actix_web::middleware::Logger;
use actix_web::web::Data;
use actix_web::{App, HttpServer, web};
use actix_web::{web, App, HttpServer};
use light_openid::basic_state_manager::BasicStateManager;
use std::time::Duration;
use virtweb_backend::actors::libvirt_actor::LibVirtActor;
@ -22,7 +22,7 @@ use virtweb_backend::constants::{
MAX_INACTIVITY_DURATION, MAX_SESSION_DURATION, SESSION_COOKIE_NAME,
};
use virtweb_backend::controllers::{
api_tokens_controller, auth_controller, groups_controller, iso_controller, network_controller,
api_tokens_controller, auth_controller, iso_controller, network_controller,
nwfilter_controller, server_controller, static_controller, vm_controller,
};
use virtweb_backend::libvirt_client::LibVirtClient;
@ -210,44 +210,6 @@ async fn main() -> std::io::Result<()> {
web::get().to(vm_controller::vnc_token),
)
.route("/api/vnc", web::get().to(vm_controller::vnc))
// Groups controller
.route("/api/group/list", web::get().to(groups_controller::list))
.route(
"/api/group/{gid}/vm/info",
web::get().to(groups_controller::vm_info),
)
.route(
"/api/group/{gid}/vm/start",
web::get().to(groups_controller::vm_start),
)
.route(
"/api/group/{gid}/vm/shutdown",
web::get().to(groups_controller::vm_shutdown),
)
.route(
"/api/group/{gid}/vm/suspend",
web::get().to(groups_controller::vm_suspend),
)
.route(
"/api/group/{gid}/vm/resume",
web::get().to(groups_controller::vm_resume),
)
.route(
"/api/group/{gid}/vm/kill",
web::get().to(groups_controller::vm_kill),
)
.route(
"/api/group/{gid}/vm/reset",
web::get().to(groups_controller::vm_reset),
)
.route(
"/api/group/{gid}/vm/screenshot",
web::get().to(groups_controller::vm_screenshot),
)
.route(
"/api/group/{gid}/vm/state",
web::get().to(groups_controller::vm_state),
)
// Network controller
.route(
"/api/network/create",

View File

@ -1,4 +1,4 @@
use std::future::{Ready, ready};
use std::future::{ready, Ready};
use std::rc::Rc;
use crate::app_config::AppConfig;
@ -8,8 +8,8 @@ use crate::extractors::auth_extractor::AuthExtractor;
use actix_web::body::EitherBody;
use actix_web::dev::Payload;
use actix_web::{
dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
Error, FromRequest, HttpResponse,
dev::{Service, ServiceRequest, ServiceResponse, Transform, forward_ready},
};
use futures_util::future::LocalBoxFuture;
@ -68,10 +68,7 @@ where
.unwrap();
if !AppConfig::get().is_allowed_ip(remote_ip.0) {
log::error!(
"An attempt to access VirtWeb from an unauthorized network has been intercepted! {:?}",
remote_ip
);
log::error!("An attempt to access VirtWeb from an unauthorized network has been intercepted! {:?}", remote_ip);
return Ok(req
.into_response(
HttpResponse::MethodNotAllowed()
@ -89,8 +86,8 @@ where
Ok(auth) => auth,
Err(e) => {
log::error!(
"Failed to extract API authentication information from request! {e}"
);
"Failed to extract API authentication information from request! {e}"
);
return Ok(req
.into_response(HttpResponse::PreconditionFailed().finish())
.map_into_right_body());

View File

@ -49,9 +49,7 @@ pub async fn sub_main() -> anyhow::Result<()> {
let args = NatArgs::parse();
if !args.network_file().exists() {
log::warn!(
"Cannot do anything for the network, because the NAT configuration file does not exixsts!"
);
log::warn!("Cannot do anything for the network, because the NAT configuration file does not exixsts!");
return Ok(());
}
@ -186,9 +184,7 @@ fn toggle_port_forwarding(
false => "tcp",
};
log::info!(
"Forward (add={enable}) incoming {protocol} connections for {host_ip}:{host_port} to {guest_ip}:{guest_port} int {net_interface}"
);
log::info!("Forward (add={enable}) incoming {protocol} connections for {host_ip}:{host_port} to {guest_ip}:{guest_port} int {net_interface}");
// Rule 1
let cmd = Command::new(program)

View File

@ -57,7 +57,7 @@ pub fn is_net_interface_name_valid<D: AsRef<str>>(int: D) -> bool {
/// Get the list of available network interfaces
pub fn net_list() -> Vec<String> {
let mut networks = Networks::new();
networks.refresh(true);
networks.refresh_list();
networks
.list()

View File

@ -1,6 +1,12 @@
use rand::distr::{Alphanumeric, SampleString};
use rand::distributions::Alphanumeric;
use rand::Rng;
/// Generate a random string
pub fn rand_str(len: usize) -> String {
Alphanumeric.sample_string(&mut rand::rng(), len)
let s: String = rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(len)
.map(char::from)
.collect();
s
}

View File

@ -9,7 +9,7 @@ make
The release file will be available in `virtweb_backend/target/release/virtweb_backend`.
This is the only artifact that must be copied to the server. It is recommended to copy it to the `/usr/local/bin` directory.
This is the only artifcat that must be copied to the server. It is recommended to copy it to the `/usr/local/bin` directory.
## Install requirements
In order to work properly, VirtWeb relies on `libvirt`, `qemu` and `kvm`:

View File

@ -1,12 +1,46 @@
# Virtweb frontend
Built with Vite + React + TypeScript
# Getting Started with Create React App
## Get dependencies
```bash
npm install
```
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
# Run for developpment
```bash
npm run dev
```
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).

View File

@ -1,54 +0,0 @@
import js from "@eslint/js";
import reactDom from "eslint-plugin-react-dom";
import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh";
import reactX from "eslint-plugin-react-x";
import globals from "globals";
import tseslint from "typescript-eslint";
export default tseslint.config(
{ ignores: ["dist"] },
{
extends: [
js.configs.recommended,
...tseslint.configs.strictTypeChecked,
...tseslint.configs.stylisticTypeChecked,
],
files: ["**/*.{ts,tsx}"],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
parserOptions: {
project: ["./tsconfig.node.json", "./tsconfig.app.json"],
tsconfigRootDir: import.meta.dirname,
},
},
plugins: {
"react-hooks": reactHooks,
"react-refresh": reactRefresh,
"react-x": reactX,
"react-dom": reactDom,
},
rules: {
...reactHooks.configs.recommended.rules,
"react-refresh/only-export-components": [
"warn",
{ allowConstantExport: true },
],
...reactX.configs["recommended-typescript"].rules,
...reactDom.configs.recommended.rules,
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/no-misused-promises": "off",
"@typescript-eslint/no-floating-promises": "off",
"@typescript-eslint/restrict-template-expressions": "off",
"@typescript-eslint/no-extraneous-class": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-unsafe-assignment": "off",
"@typescript-eslint/no-unsafe-return": "off",
"@typescript-eslint/no-unsafe-call": "off",
"@typescript-eslint/no-unsafe-member-access": "off",
"@typescript-eslint/no-unsafe-argument": "off",
"react-refresh/only-export-components": "off",
},
}
);

File diff suppressed because it is too large Load Diff

View File

@ -3,51 +3,63 @@
"version": "0.1.0",
"type": "module",
"private": true,
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.0",
"@fontsource/roboto": "^5.2.5",
"@emotion/react": "^11.11.1",
"@emotion/styled": "^11.11.0",
"@fontsource/roboto": "^5.0.13",
"@mdi/js": "^7.2.96",
"@mdi/react": "^1.6.1",
"@mui/icons-material": "^7.0.0",
"@mui/material": "^7.0.0",
"@mui/x-charts": "^7.28.0",
"@mui/x-data-grid": "^7.28.1",
"date-and-time": "^3.6.0",
"filesize": "^10.1.6",
"@mui/icons-material": "^5.14.7",
"@mui/material": "^5.14.7",
"@mui/x-charts": "^7.3.0",
"@mui/x-data-grid": "^7.3.0",
"@testing-library/jest-dom": "^6.4.2",
"@testing-library/react": "^16.0.0",
"@testing-library/user-event": "^14.5.2",
"@types/humanize-duration": "^3.27.1",
"@types/jest": "^29.5.12",
"@types/react": "^18.2.79",
"@types/react-dom": "^18.2.25",
"@types/react-syntax-highlighter": "^15.5.11",
"@types/uuid": "^10.0.0",
"@vitejs/plugin-react": "^4.2.1",
"date-and-time": "^3.1.1",
"filesize": "^10.0.12",
"humanize-duration": "^3.29.0",
"mui-file-input": "^7.0.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-router-dom": "^7.4.0",
"react-syntax-highlighter": "^15.6.1",
"react-vnc": "^3.0.7",
"uuid": "^11.1.0",
"mui-file-input": "^4.0.4",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.23.0",
"react-syntax-highlighter": "^15.5.0",
"react-vnc": "^1.0.0",
"typescript": "^4.0.0",
"uuid": "^10.0.0",
"vite": "^5.2.10",
"vite-tsconfig-paths": "^4.2.2",
"web-vitals": "^3.5.2",
"xml-formatter": "^3.6.0"
},
"devDependencies": {
"@eslint/js": "^9.21.0",
"@types/humanize-duration": "^3.27.1",
"@types/jest": "^29.5.14",
"@types/react": "^19.0.12",
"@types/react-dom": "^19.0.4",
"@types/react-syntax-highlighter": "^15.5.13",
"@types/uuid": "^10.0.0",
"@vitejs/plugin-react": "^4.3.4",
"eslint": "^9.21.0",
"eslint-plugin-react-dom": "^1.38.3",
"eslint-plugin-react-hooks": "^5.1.0",
"eslint-plugin-react-refresh": "^0.4.19",
"eslint-plugin-react-x": "^1.38.3",
"globals": "^15.15.0",
"typescript": "^5.8.2",
"typescript-eslint": "^8.24.1",
"vite": "^6.2.3"
"scripts": {
"start": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

View File

@ -51,10 +51,7 @@ export function App() {
const context: AuthContext = {
signedIn: signedIn,
setSignedIn: (s) => {
setSignedIn(s);
location.reload();
},
setSignedIn: (s) => setSignedIn(s),
};
const router = createBrowserRouter(
@ -100,12 +97,12 @@ export function App() {
);
return (
<AuthContextK value={context}>
<AuthContextK.Provider value={context}>
<RouterProvider router={router} />
</AuthContextK>
</AuthContextK.Provider>
);
}
export function useAuth(): AuthContext {
return React.use(AuthContextK)!;
return React.useContext(AuthContextK)!;
}

View File

@ -26,7 +26,7 @@ export class APIClient {
* Get backend URL
*/
static backendURL(): string {
const URL = String(import.meta.env.VITE_APP_BACKEND ?? "");
const URL = import.meta.env.VITE_APP_BACKEND ?? "";
if (URL.length === 0) throw new Error("Backend URL undefined!");
return URL;
}
@ -44,7 +44,7 @@ export class APIClient {
*/
static async exec(args: RequestParams): Promise<APIResponse> {
let body: string | undefined | FormData = undefined;
const headers: any = {};
let headers: any = {};
// JSON request
if (args.jsonData) {
@ -66,25 +66,22 @@ export class APIClient {
if (args.upProgress) {
const res: XMLHttpRequest = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", (e) => {
args.upProgress!(e.loaded / e.total);
});
xhr.addEventListener("load", () => {
resolve(xhr);
});
xhr.addEventListener("error", () => {
reject(new Error("File upload failed"));
});
xhr.addEventListener("abort", () => {
reject(new Error("File upload aborted"));
});
xhr.addEventListener("timeout", () => {
reject(new Error("File upload timeout"));
});
xhr.upload.addEventListener("progress", (e) =>
args.upProgress!(e.loaded / e.total)
);
xhr.addEventListener("load", () => resolve(xhr));
xhr.addEventListener("error", () =>
reject(new Error("File upload failed"))
);
xhr.addEventListener("abort", () =>
reject(new Error("File upload aborted"))
);
xhr.addEventListener("timeout", () =>
reject(new Error("File upload timeout"))
);
xhr.open(args.method, url, true);
xhr.withCredentials = true;
for (const key in headers) {
// eslint-disable-next-line no-prototype-builtins
if (headers.hasOwnProperty(key))
xhr.setRequestHeader(key, headers[key]);
}

View File

@ -1,15 +0,0 @@
import { APIClient } from "./ApiClient";
export class GroupApi {
/**
* Get the entire list of networks
*/
static async GetList(): Promise<string[]> {
return (
await APIClient.exec({
method: "GET",
uri: "/group/list",
})
).data;
}
}

View File

@ -140,7 +140,7 @@ export interface NWFilter {
rules: NWFilterRule[];
}
export function NWFilterURL(n: NWFilter, edit = false): string {
export function NWFilterURL(n: NWFilter, edit: boolean = false): string {
return `/nwfilter/${n.uuid}${edit ? "/edit" : ""}`;
}
@ -221,7 +221,7 @@ export class NWFilterApi {
static async Delete(n: NWFilter): Promise<void> {
await APIClient.exec({
method: "DELETE",
uri: `/nwfilter/${n.uuid!}`,
uri: `/nwfilter/${n.uuid}`,
});
}
}

View File

@ -53,7 +53,7 @@ export interface NetworkInfo {
export type NetworkStatus = "Started" | "Stopped";
export function NetworkURL(n: NetworkInfo, edit = false): string {
export function NetworkURL(n: NetworkInfo, edit: boolean = false): string {
return `/net/${n.uuid}${edit ? "/edit" : ""}`;
}

View File

@ -16,7 +16,6 @@ export interface ServerConstraints {
vnc_token_duration: number;
vm_name_size: LenConstraint;
vm_title_size: LenConstraint;
group_id_size: LenConstraint;
memory_size: LenConstraint;
disk_name_size: LenConstraint;
disk_size: LenConstraint;
@ -74,7 +73,7 @@ interface SystemInfo {
secs: number;
nanos: number;
};
global_cpu_usage: number;
global_cpu_info: GlobalCPUInfo;
cpus: CpuCore[];
physical_core_count: number;
total_memory: number;
@ -95,6 +94,14 @@ interface SystemInfo {
host_name: string;
}
interface GlobalCPUInfo {
cpu_usage: number;
name: string;
vendor_id: string;
brand: string;
frequency: number;
}
interface CpuCore {
cpu_usage: number;
name: string;

View File

@ -20,7 +20,7 @@ export interface APIToken {
max_inactivity?: number;
}
export function APITokenURL(t: APIToken, edit = false): string {
export function APITokenURL(t: APIToken, edit: boolean = false): string {
return `/token/${t.id}${edit ? "/edit" : ""}`;
}

View File

@ -63,7 +63,6 @@ interface VMInfoInterface {
genid?: string;
title?: string;
description?: string;
group?: string;
boot_type: "UEFI" | "UEFISecureBoot";
architecture: "i686" | "x86_64";
memory: number;
@ -81,7 +80,6 @@ export class VMInfo implements VMInfoInterface {
genid?: string;
title?: string;
description?: string;
group?: string;
boot_type: "UEFI" | "UEFISecureBoot";
architecture: "i686" | "x86_64";
number_vcpu: number;
@ -98,7 +96,6 @@ export class VMInfo implements VMInfoInterface {
this.genid = int.genid;
this.title = int.title;
this.description = int.description;
this.group = int.group;
this.boot_type = int.boot_type;
this.architecture = int.architecture;
this.number_vcpu = int.number_vcpu;

View File

@ -39,7 +39,7 @@ export function AlertDialogProvider(p: PropsWithChildren): React.ReactElement {
return (
<>
<AlertContextK value={hook}>{p.children}</AlertContextK>
<AlertContextK.Provider value={hook}>{p.children}</AlertContextK.Provider>
<Dialog
open={open}
@ -67,5 +67,5 @@ export function AlertDialogProvider(p: PropsWithChildren): React.ReactElement {
}
export function useAlert(): AlertContext {
return React.use(AlertContextK)!;
return React.useContext(AlertContextK)!;
}

View File

@ -59,13 +59,13 @@ export function ConfirmDialogProvider(
return (
<>
<ConfirmContextK value={hook}>
<ConfirmContextK.Provider value={hook}>
{p.children}
</ConfirmContextK>
</ConfirmContextK.Provider>
<Dialog
open={open}
onClose={() => { handleClose(false); }}
onClose={() => handleClose(false)}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
@ -76,10 +76,10 @@ export function ConfirmDialogProvider(
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={() => { handleClose(false); }} autoFocus>
<Button onClick={() => handleClose(false)} autoFocus>
{cancelButton ?? "Cancel"}
</Button>
<Button onClick={() => { handleClose(true); }} color="error">
<Button onClick={() => handleClose(true)} color="error">
{confirmButton ?? "Confirm"}
</Button>
</DialogActions>
@ -89,5 +89,5 @@ export function ConfirmDialogProvider(
}
export function useConfirm(): ConfirmContext {
return React.use(ConfirmContextK)!;
return React.useContext(ConfirmContextK)!;
}

View File

@ -6,10 +6,10 @@ import {
} from "@mui/material";
import React, { PropsWithChildren } from "react";
interface LoadingMessageContext {
type LoadingMessageContext = {
show: (message: string) => void;
hide: () => void;
}
};
const LoadingMessageContextK =
React.createContext<LoadingMessageContext | null>(null);
@ -34,9 +34,9 @@ export function LoadingMessageProvider(
return (
<>
<LoadingMessageContextK value={hook}>
<LoadingMessageContextK.Provider value={hook}>
{p.children}
</LoadingMessageContextK>
</LoadingMessageContextK.Provider>
<Dialog open={open}>
<DialogContent>
@ -60,5 +60,5 @@ export function LoadingMessageProvider(
}
export function useLoadingMessage(): LoadingMessageContext {
return React.use(LoadingMessageContextK)!;
return React.useContext(LoadingMessageContextK)!;
}

View File

@ -24,9 +24,9 @@ export function SnackbarProvider(p: PropsWithChildren): React.ReactElement {
return (
<>
<SnackbarContextK value={hook}>
<SnackbarContextK.Provider value={hook}>
{p.children}
</SnackbarContextK>
</SnackbarContextK.Provider>
<Snackbar
open={open}
@ -39,5 +39,5 @@ export function SnackbarProvider(p: PropsWithChildren): React.ReactElement {
}
export function useSnackbar(): SnackbarContext {
return React.use(SnackbarContextK)!;
return React.useContext(SnackbarContextK)!;
}

View File

@ -7,6 +7,7 @@ import React from "react";
import ReactDOM from "react-dom/client";
import { App } from "./App";
import "./index.css";
import reportWebVitals from "./reportWebVitals";
import { LoadServerConfig } from "./widgets/LoadServerConfig";
import { ThemeProvider, createTheme } from "@mui/material";
import { LoadingMessageProvider } from "./hooks/providers/LoadingMessageProvider";
@ -21,7 +22,7 @@ const darkTheme = createTheme({
});
const root = ReactDOM.createRoot(
document.getElementById("root")!
document.getElementById("root") as HTMLElement
);
root.render(
<React.StrictMode>
@ -40,3 +41,8 @@ root.render(
</ThemeProvider>
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

View File

@ -0,0 +1,15 @@
import { ReportHandler } from 'web-vitals';
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;

View File

@ -116,7 +116,7 @@ function EditApiTokenRouteInner(p: {
const [changed, setChanged] = React.useState(false);
const [, updateState] = React.useState<any>();
const forceUpdate = React.useCallback(() => { updateState({}); }, []);
const forceUpdate = React.useCallback(() => updateState({}), []);
const valueChanged = () => {
setChanged(true);

View File

@ -99,7 +99,7 @@ function EditNetworkFilterRouteInner(p: {
const [changed, setChanged] = React.useState(false);
const [, updateState] = React.useState<any>();
const forceUpdate = React.useCallback(() => { updateState({}); }, []);
const forceUpdate = React.useCallback(() => updateState({}), []);
const valueChanged = () => {
setChanged(true);

View File

@ -97,7 +97,7 @@ function EditNetworkRouteInner(p: {
const [changed, setChanged] = React.useState(false);
const [, updateState] = React.useState<any>();
const forceUpdate = React.useCallback(() => { updateState({}); }, []);
const forceUpdate = React.useCallback(() => updateState({}), []);
const valueChanged = () => {
setChanged(true);

View File

@ -15,7 +15,7 @@ export function CreateVMRoute(): React.ReactElement {
const alert = useAlert();
const navigate = useNavigate();
const [vm, setVM] = React.useState(VMInfo.NewEmpty());
const [vm, setVM] = React.useState(VMInfo.NewEmpty);
const create = async (v: VMInfo) => {
try {
@ -103,9 +103,7 @@ function EditVMInner(p: {
const [changed, setChanged] = React.useState(false);
const [, updateState] = React.useState<any>();
const forceUpdate = React.useCallback(() => {
updateState({});
}, []);
const forceUpdate = React.useCallback(() => updateState({}), []);
const valueChanged = () => {
setChanged(true);

View File

@ -96,7 +96,7 @@ function UploadIsoFileCard(p: {
p.onFileUploaded();
} catch (e) {
console.error(e);
await alert(`Failed to perform file upload! ${e}`);
await alert("Failed to perform file upload! " + e);
}
setUploadProgress(null);
@ -120,9 +120,7 @@ function UploadIsoFileCard(p: {
value={value}
onChange={handleChange}
style={{ flex: 1 }}
slotProps={{
htmlInput: { accept: ServerApi.Config.iso_mimetypes.join(",") },
}}
inputProps={{ accept: ServerApi.Config.iso_mimetypes.join(",") }}
/>
{value && <Button onClick={upload}>Upload file</Button>}
@ -149,8 +147,6 @@ function UploadIsoFileFromUrlCard(p: {
loadingMessage.show("Downloading file from URL...");
await IsoFilesApi.UploadFromURL(url, actualFileName);
p.onFileUploaded();
setURL("");
setFilename(null);
snackbar("Successfully downloaded file!");
@ -168,18 +164,14 @@ function UploadIsoFileFromUrlCard(p: {
label="URL"
value={url}
style={{ flex: 3 }}
onChange={(e) => {
setURL(e.target.value);
}}
onChange={(e) => setURL(e.target.value)}
/>
<span style={{ width: "10px" }}></span>
<TextField
label="Filename"
value={actualFileName}
style={{ flex: 2 }}
onChange={(e) => {
setFilename(e.target.value);
}}
onChange={(e) => setFilename(e.target.value)}
/>
{url !== "" && actualFileName !== "" && (
<Button onClick={upload}>Upload file</Button>
@ -206,7 +198,7 @@ function IsoFilesList(p: {
try {
const blob = await IsoFilesApi.Download(entry, setDlProgress);
downloadBlob(blob, entry.filename);
await downloadBlob(blob, entry.filename);
} catch (e) {
console.error(e);
alert("Failed to download iso file!");
@ -244,7 +236,7 @@ function IsoFilesList(p: {
</Typography>
);
const columns: GridColDef<IsoFile>[] = [
const columns: GridColDef[] = [
{ field: "filename", headerName: "File name", flex: 3 },
{
field: "size",
@ -309,6 +301,7 @@ function IsoFilesList(p: {
getRowId={(c) => c.filename}
rows={p.list}
columns={columns}
autoHeight={true}
/>
</VirtWebPaper>
</>

View File

@ -66,7 +66,7 @@ function NetworkFiltersListRouteInner(p: {
const onlyBuiltin = visibleFilters === VisibleFilters.Builtin;
return p.list.filter((f) => NWFilterIsBuiltin(f) === onlyBuiltin);
}, [visibleFilters, p.list]);
}, [visibleFilters]);
return (
<VirtWebRouteContainer
@ -78,9 +78,7 @@ function NetworkFiltersListRouteInner(p: {
size="small"
value={visibleFilters}
exclusive
onChange={(_ev, v) => {
setVisibleFilters(v);
}}
onChange={(_ev, v) => setVisibleFilters(v)}
aria-label="visible filters"
>
<ToggleButton value={VisibleFilters.All}>All</ToggleButton>
@ -132,8 +130,8 @@ function NetworkFiltersListRouteInner(p: {
</TableCell>
<TableCell>
<ul>
{t.join_filters.map((f) => (
<li key={f}>{f}</li>
{t.join_filters.map((f, n) => (
<li key={n}>{f}</li>
))}
</ul>
</TableCell>

View File

@ -1,4 +1,3 @@
/* eslint-disable react-x/no-array-index-key */
import {
mdiHarddisk,
mdiInformation,
@ -9,6 +8,7 @@ import {
import Icon from "@mdi/react";
import {
Box,
Grid,
LinearProgress,
Table,
TableBody,
@ -17,10 +17,7 @@ import {
TableRow,
Typography,
} from "@mui/material";
import Grid from "@mui/material/Grid";
import { PieChart } from "@mui/x-charts";
import { filesize } from "filesize";
import humanizeDuration from "humanize-duration";
import React from "react";
import {
DiskInfo,
@ -31,6 +28,8 @@ import {
import { AsyncWidget } from "../widgets/AsyncWidget";
import { VirtWebPaper } from "../widgets/VirtWebPaper";
import { VirtWebRouteContainer } from "../widgets/VirtWebRouteContainer";
import humanizeDuration from "humanize-duration";
import { filesize } from "filesize";
export function SysInfoRoute(): React.ReactElement {
const [info, setInfo] = React.useState<ServerSystemInfo>();
@ -66,7 +65,7 @@ export function SysInfoRouteInner(p: {
<VirtWebRouteContainer label="Sysinfo">
<Grid container spacing={2}>
{/* Memory */}
<Grid size={{ xs: 4 }}>
<Grid xs={4}>
<Box flexGrow={1}>
<Typography style={{ textAlign: "center" }}>Memory</Typography>
<PieChart
@ -98,7 +97,7 @@ export function SysInfoRouteInner(p: {
</Grid>
{/* Disk usage */}
<Grid size={{ xs: 4 }}>
<Grid xs={4}>
<Box flexGrow={1}>
<Typography style={{ textAlign: "center" }}>Disk usage</Typography>
<PieChart
@ -126,7 +125,7 @@ export function SysInfoRouteInner(p: {
</Grid>
{/* CPU usage */}
<Grid size={{ xs: 4 }}>
<Grid xs={4}>
<Box flexGrow={1}>
<Typography style={{ textAlign: "center" }}>CPU usage</Typography>
<PieChart
@ -135,13 +134,13 @@ export function SysInfoRouteInner(p: {
data: [
{
id: 1,
value: 100 - p.info.system.global_cpu_usage,
value: 100 - p.info.system.global_cpu_info.cpu_usage,
label: "Free",
},
{
id: 2,
value: p.info.system.global_cpu_usage,
value: p.info.system.global_cpu_info.cpu_usage,
label: "Used",
},
],
@ -181,18 +180,18 @@ export function SysInfoRouteInner(p: {
label="CPU info"
icon={<Icon size={"1rem"} path={mdiMemory} />}
entries={[
{ label: "Brand", value: p.info.system.cpus[0].brand },
{ label: "Brand", value: p.info.system.global_cpu_info.brand },
{
label: "Vendor ID",
value: p.info.system.cpus[0].vendor_id,
value: p.info.system.global_cpu_info.vendor_id,
},
{
label: "CPU usage",
value: p.info.system.cpus[0].cpu_usage,
value: p.info.system.global_cpu_info.cpu_usage,
},
{
label: "Name",
value: p.info.system.cpus[0].name,
value: p.info.system.global_cpu_info.name,
},
{
label: "CPU model",
@ -237,7 +236,7 @@ export function SysInfoRouteInner(p: {
function SysInfoDetailsTable(p: {
label: string;
icon: React.ReactElement;
entries: { label: string; value: string | number }[];
entries: Array<{ label: string; value: string | number }>;
}): React.ReactElement {
return (
<VirtWebPaper

View File

@ -1,4 +1,3 @@
/* eslint-disable react-x/no-array-index-key */
import VisibilityIcon from "@mui/icons-material/Visibility";
import {
Button,
@ -100,9 +99,9 @@ export function TokensListRouteInner(p: {
{t.max_inactivity && timeDiff(0, t.max_inactivity)}
</TableCell>
<TableCell>
{t.rights.map((r, n) => {
{t.rights.map((r) => {
return (
<div key={n}>
<div>
{r.verb} {r.path}
</div>
);

View File

@ -1,5 +1,3 @@
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
import KeyboardArrowUpIcon from "@mui/icons-material/KeyboardArrowUp";
import VisibilityIcon from "@mui/icons-material/Visibility";
import {
Button,
@ -9,7 +7,6 @@ import {
TableBody,
TableCell,
TableContainer,
TableFooter,
TableHead,
TableRow,
Tooltip,
@ -17,27 +14,19 @@ import {
import { filesize } from "filesize";
import React from "react";
import { useNavigate } from "react-router-dom";
import { GroupApi } from "../api/GroupApi";
import { VMApi, VMInfo, VMState } from "../api/VMApi";
import { VMApi, VMInfo } from "../api/VMApi";
import { AsyncWidget } from "../widgets/AsyncWidget";
import { RouterLink } from "../widgets/RouterLink";
import { VirtWebRouteContainer } from "../widgets/VirtWebRouteContainer";
import { VMStatusWidget } from "../widgets/vms/VMStatusWidget";
export function VMListRoute(): React.ReactElement {
const [groups, setGroups] = React.useState<(string | undefined)[]>();
const [list, setList] = React.useState<VMInfo[] | undefined>();
const loadKey = React.useRef(1);
const load = async () => {
const groups: (string | undefined)[] = await GroupApi.GetList();
const list = await VMApi.GetList();
if (list.find((v) => !v.group) !== undefined) groups.push(undefined);
setGroups(groups);
setList(list);
setList(await VMApi.GetList());
};
const reload = () => {
@ -62,7 +51,7 @@ export function VMListRoute(): React.ReactElement {
</>
}
>
<VMListWidget list={list!} groups={groups!} onReload={reload} />
<VMListWidget list={list!} onReload={reload} />
</VirtWebRouteContainer>
)}
/>
@ -70,37 +59,11 @@ export function VMListRoute(): React.ReactElement {
}
function VMListWidget(p: {
groups: (string | undefined)[];
list: VMInfo[];
onReload: () => void;
}): React.ReactElement {
const navigate = useNavigate();
const [hiddenGroups, setHiddenGroups] = React.useState<
Set<string | undefined>
>(new Set());
const [runningVMs, setRunningVMs] = React.useState<Set<string>>(new Set());
const toggleHiddenGroup = (g: string | undefined) => {
if (hiddenGroups.has(g)) hiddenGroups.delete(g);
else hiddenGroups.add(g);
setHiddenGroups(new Set([...hiddenGroups]));
};
const updateVMState = (v: VMInfo, s: VMState) => {
const running = s !== "Shutoff";
if (runningVMs.has(v.name) === running) {
return;
}
if (running) runningVMs.add(v.name);
else runningVMs.delete(v.name);
setRunningVMs(new Set([...runningVMs]));
};
return (
<TableContainer component={Paper}>
<Table>
@ -109,104 +72,39 @@ function VMListWidget(p: {
<TableCell>Name</TableCell>
<TableCell>Description</TableCell>
<TableCell>Memory</TableCell>
<TableCell>vCPU</TableCell>
<TableCell>Status</TableCell>
<TableCell>Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{p.groups.map((g) => (
<React.Fragment key={g}>
{p.groups.length > 1 && (
<TableRow>
<TableCell
style={{ paddingBottom: 2, paddingTop: 2 }}
colSpan={6}
>
<IconButton
size="small"
onClick={() => {
toggleHiddenGroup(g);
}}
>
{!hiddenGroups.has(g) ? (
<KeyboardArrowUpIcon />
) : (
<KeyboardArrowDownIcon />
)}
{p.list.map((row) => (
<TableRow
hover
key={row.name}
sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
onDoubleClick={() => navigate(row.ViewURL)}
>
<TableCell component="th" scope="row">
{row.name}
</TableCell>
<TableCell>{row.description ?? ""}</TableCell>
<TableCell>{filesize(row.memory * 1000 * 1000)}</TableCell>
<TableCell>
<VMStatusWidget vm={row} />
</TableCell>
<TableCell>
<Tooltip title="View this VM">
<RouterLink to={row.ViewURL}>
<IconButton>
<VisibilityIcon />
</IconButton>
{g ?? "default"}
</TableCell>
</TableRow>
)}
{!hiddenGroups.has(g) &&
p.list
.filter((row) => row.group === g)
.map((row) => (
<TableRow
hover
key={row.name}
sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
onDoubleClick={() => navigate(row.ViewURL)}
>
<TableCell component="th" scope="row">
{row.name}
</TableCell>
<TableCell>{row.description ?? ""}</TableCell>
<TableCell>{vmMemoryToHuman(row.memory)}</TableCell>
<TableCell>{row.number_vcpu}</TableCell>
<TableCell>
<VMStatusWidget
vm={row}
onChange={(s) => {
updateVMState(row, s);
}}
/>
</TableCell>
<TableCell>
<Tooltip title="View this VM">
<RouterLink to={row.ViewURL}>
<IconButton>
<VisibilityIcon />
</IconButton>
</RouterLink>
</Tooltip>
</TableCell>
</TableRow>
))}
</React.Fragment>
</RouterLink>
</Tooltip>
</TableCell>
</TableRow>
))}
</TableBody>
<TableFooter>
<TableRow>
<TableCell></TableCell>
<TableCell></TableCell>
<TableCell>
{vmMemoryToHuman(
p.list
.filter((v) => runningVMs.has(v.name))
.reduce((s, v) => s + v.memory, 0)
)}
{" / "}
{vmMemoryToHuman(p.list.reduce((s, v) => s + v.memory, 0))}
</TableCell>
<TableCell>
{p.list
.filter((v) => runningVMs.has(v.name))
.reduce((s, v) => s + v.number_vcpu, 0)}
{" / "}
{p.list.reduce((s, v) => s + v.number_vcpu, 0)}
</TableCell>
<TableCell></TableCell>
<TableCell></TableCell>
</TableRow>
</TableFooter>
</Table>
</TableContainer>
);
}
function vmMemoryToHuman(size: number): string {
return filesize(size * 1000 * 1000);
}

View File

@ -1,16 +1,17 @@
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import FullscreenIcon from "@mui/icons-material/Fullscreen";
import FullscreenExitIcon from "@mui/icons-material/FullscreenExit";
import KeyboardAltIcon from "@mui/icons-material/KeyboardAlt";
import { IconButton, Tooltip } from "@mui/material";
import React, { useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { VncScreen, VncScreenHandle } from "react-vnc";
import { VncScreen } from "react-vnc";
import { ServerApi } from "../api/ServerApi";
import { VMApi, VMInfo } from "../api/VMApi";
import { useSnackbar } from "../hooks/providers/SnackbarProvider";
import { time } from "../utils/DateUtils";
import { AsyncWidget } from "../widgets/AsyncWidget";
import RFB from "react-vnc/dist/types/noVNC/core/rfb";
import KeyboardAltIcon from "@mui/icons-material/KeyboardAlt";
interface VNCTokenInfo {
url: string;
@ -42,10 +43,9 @@ function VNCInner(p: { vm: VMInfo }): React.ReactElement {
const [token, setToken] = React.useState<VNCTokenInfo | undefined>();
const [counter, setCounter] = React.useState(1);
const [connected, setConnected] = React.useState(false);
const [rfb, setRFB] = React.useState<RFB | undefined>();
const vncRef = React.useRef<HTMLDivElement>(null);
const vncScreenRef = React.useRef<VncScreenHandle>(null);
const vncRef = React.createRef<HTMLDivElement>();
const connect = async (force: boolean) => {
try {
@ -71,7 +71,7 @@ function VNCInner(p: { vm: VMInfo }): React.ReactElement {
};
const disconnected = () => {
setConnected(false);
setRFB(undefined);
connect(true);
};
@ -91,9 +91,7 @@ function VNCInner(p: { vm: VMInfo }): React.ReactElement {
connect(false);
if (vncRef.current) {
vncRef.current.onfullscreenchange = () => {
setCounter(counter + 1);
};
vncRef.current.onfullscreenchange = () => setCounter(counter + 1);
}
});
@ -120,9 +118,9 @@ function VNCInner(p: { vm: VMInfo }): React.ReactElement {
)}
{/* Keystrokes */}
{connected && (
{rfb && (
<Tooltip title="Send Ctrl+Alt+Del">
<IconButton onClick={() => vncScreenRef.current?.sendCtrlAltDel()}>
<IconButton onClick={() => rfb?.sendCtrlAltDel()}>
<KeyboardAltIcon />
</IconButton>
</Tooltip>
@ -139,15 +137,12 @@ function VNCInner(p: { vm: VMInfo }): React.ReactElement {
}}
>
<VncScreen
ref={vncScreenRef}
url={token.url}
onDisconnect={() => {
console.info("VNC disconnected " + token.url);
console.info("VNC disconnected " + token?.url);
disconnected();
}}
onConnect={() => {
setConnected(true);
}}
onConnect={(rfb) => setRFB(rfb)}
/>
</div>
</div>

View File

@ -1,5 +1,4 @@
import VisibilityIcon from '@mui/icons-material/Visibility';
import VisibilityOffIcon from '@mui/icons-material/VisibilityOff';
import { Visibility, VisibilityOff } from "@mui/icons-material";
import {
Alert,
CircularProgress,
@ -36,7 +35,7 @@ export function LoginRoute(): React.ReactElement {
const canSubmit = username.length > 0 && password.length > 0;
const [showPassword, setShowPassword] = React.useState(false);
const handleClickShowPassword = () => { setShowPassword((show) => !show); };
const handleClickShowPassword = () => setShowPassword((show) => !show);
const handleMouseDownPassword = (
event: React.MouseEvent<HTMLButtonElement>
@ -105,7 +104,7 @@ export function LoginRoute(): React.ReactElement {
label="Username"
name="username"
value={username}
onChange={(e) => { setUsername(e.target.value); }}
onChange={(e) => setUsername(e.target.value)}
autoComplete="username"
autoFocus
/>
@ -120,7 +119,7 @@ export function LoginRoute(): React.ReactElement {
type={showPassword ? "text" : "password"}
id="password"
value={password}
onChange={(e) => { setPassword(e.target.value); }}
onChange={(e) => setPassword(e.target.value)}
autoComplete="current-password"
endAdornment={
<InputAdornment position="end">
@ -131,7 +130,7 @@ export function LoginRoute(): React.ReactElement {
onMouseDown={handleMouseDownPassword}
edge="end"
>
{showPassword ? <VisibilityOffIcon /> : <VisibilityIcon />}
{showPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</Tooltip>
</InputAdornment>

View File

@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';

View File

@ -1,4 +1,4 @@
export function downloadBlob(blob: Blob, filename: string) {
export async function downloadBlob(blob: Blob, filename: string) {
const url = URL.createObjectURL(blob);
const link = document.createElement("a");

View File

@ -2,9 +2,8 @@
* Generate a random MAC address
*/
export function randomMacAddress(prefix: string | undefined): string {
prefix = prefix ?? "";
let mac = "XX:XX:XX:XX:XX:XX";
mac = prefix + mac.slice(prefix.length);
mac = prefix + mac.slice(prefix?.length);
return mac.replace(/X/g, () =>
"0123456789abcdef".charAt(Math.floor(Math.random() * 16))

View File

@ -19,7 +19,7 @@ export function AsyncWidget(p: {
}): React.ReactElement {
const [state, setState] = useState(State.Loading);
const counter = useRef<any>(null);
const counter = useRef<any | null>(null);
const load = async () => {
try {
@ -67,7 +67,7 @@ export function AsyncWidget(p: {
<Button onClick={load}>Try again</Button>
{p.errAdditionalElement?.()}
{p.errAdditionalElement && p.errAdditionalElement()}
</Box>
)
);

View File

@ -13,9 +13,11 @@ import {
List,
ListItemButton,
ListItemIcon,
ListItemText
ListItemSecondaryAction,
ListItemText,
} from "@mui/material";
import { Outlet, useLocation } from "react-router-dom";
import { isDebug } from "../utils/DebugUtils";
import { RouterLink } from "./RouterLink";
import { VirtWebAppBar } from "./VirtWebAppBar";
@ -94,6 +96,7 @@ function NavLink(p: {
icon: React.ReactElement;
uri: string;
label: string;
secondaryAction?: React.ReactElement;
}): React.ReactElement {
const location = useLocation();
return (
@ -101,6 +104,9 @@ function NavLink(p: {
<ListItemButton selected={p.uri === location.pathname}>
<ListItemIcon>{p.icon}</ListItemIcon>
<ListItemText primary={p.label} />
{p.secondaryAction && (
<ListItemSecondaryAction>{p.secondaryAction}</ListItemSecondaryAction>
)}
</ListItemButton>
</RouterLink>
);

View File

@ -38,7 +38,10 @@ export function BaseLoginPage() {
<Grid container component="main" sx={{ height: "100vh" }}>
<CssBaseline />
<Grid
size={{ xs: false, sm: 4, md: 7 }}
item
xs={false}
sm={4}
md={7}
sx={{
backgroundImage: "url(/login_splash.jpg)",
backgroundRepeat: "no-repeat",
@ -50,12 +53,7 @@ export function BaseLoginPage() {
backgroundPosition: "center",
}}
/>
<Grid
size={{ xs: 12, sm: 8, md: 5 }}
component={Paper}
elevation={6}
square
>
<Grid item xs={12} sm={8} md={5} component={Paper} elevation={6} square>
<Box
sx={{
my: 8,

View File

@ -31,16 +31,14 @@ export function ConfigImportExportButtons(p: {
fileEl.click();
// Wait for a file to be chosen
await new Promise((res) => {
fileEl.addEventListener("change", () => {
res(null);
});
});
await new Promise((res, _rej) =>
fileEl.addEventListener("change", () => res(null))
);
if ((fileEl.files?.length ?? 0) === 0) return null;
// Import conf
const file = fileEl.files![0];
let file = fileEl.files![0];
const content = await file.text();
p.importConf?.(JSON.parse(content));
} catch (e) {

View File

@ -23,7 +23,7 @@ export function StateActionButton<S>(p: {
p.onExecuted();
} catch (e) {
console.error(e);
alert(`Failed to perform action! ${e}`);
alert("Failed to perform action! " + e);
}
};

View File

@ -1,4 +1,3 @@
/* eslint-disable react-x/no-array-index-key */
import { Box, Tab, Tabs } from "@mui/material";
export interface TabWidgetOption<E> {
@ -25,9 +24,7 @@ export function TabsWidget<E>(p: {
<Box sx={{ borderBottom: 1, borderColor: "divider" }}>
<Tabs
value={currTabIndex}
onChange={(_ev, newVal) => {
updateActiveTab(newVal);
}}
onChange={(_ev, newVal) => updateActiveTab(newVal)}
>
{activeOptions.map((o, index) => (
<Tab key={index} label={o.label} style={{ color: o.color }} />

View File

@ -17,7 +17,7 @@ export function CheckboxInput(p: {
<Checkbox
disabled={!p.editable}
checked={p.checked}
onChange={(e) => { p.onValueChange(e.target.checked); }}
onChange={(e) => p.onValueChange(e.target.checked)}
/>
}
label={p.label}

View File

@ -1,7 +1,5 @@
/* eslint-disable @typescript-eslint/prefer-nullish-coalescing */
import { Paper, Typography } from "@mui/material";
import { Grid, Paper, Typography } from "@mui/material";
import React, { PropsWithChildren } from "react";
import Grid from "@mui/material/Grid";
export function EditSection(
p: {
@ -11,7 +9,7 @@ export function EditSection(
} & PropsWithChildren
): React.ReactElement {
return (
<Grid size={{ sm: 12, md: p.fullWidth ? 12 : 6 }}>
<Grid item sm={12} md={p.fullWidth ? 12 : 6}>
<Paper style={{ margin: "10px", padding: "10px" }}>
{(p.title || p.actions) && (
<span

View File

@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-unnecessary-condition */
import React from "react";
import { TextInput } from "./TextInput";
@ -33,7 +32,7 @@ export function IPInputWithMask(p: {
const currValue =
p.ipAndMask ??
`${p.ip ?? ""}${p.mask || showSlash.current ? "/" : ""}${p.mask ?? ""}`;
(p.ip ?? "") + (p.mask || showSlash.current ? "/" : "") + (p.mask ?? "");
const { onValueChange, ...props } = p;
return (
@ -45,7 +44,7 @@ export function IPInputWithMask(p: {
return;
}
const split = v.split("/");
const split = v?.split("/");
const ip =
p.version === 4 ? sanitizeIpV4(split[0]) : sanitizeIpV6(split[0]);
let mask = undefined;
@ -70,7 +69,7 @@ export function IPInputWithMask(p: {
function sanitizeIpV4(s: string | undefined): string | undefined {
if (s === "" || s === undefined) return s;
const split = s.split(".");
let split = s.split(".");
if (split.length > 4) split.splice(4);
let needAnotherIteration = false;
@ -107,7 +106,7 @@ function sanitizeIpV6(s: string | undefined): string | undefined {
const num = parseInt(e, 16);
if (isNaN(num)) return "0";
const s = num.toString(16);
let s = num.toString(16);
if (num > 0xffff) {
needAnotherIteration = true;
return s.slice(0, 4) + ":" + s.slice(4);

View File

@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-unnecessary-condition */
import { TextInput } from "./TextInput";
export function MACInput(p: {
@ -33,7 +32,7 @@ function sanitizeMacAddress(s: string | undefined): string | undefined {
const num = parseInt(e, 16);
if (isNaN(num)) return "0";
const s = num.toString(16).padStart(2, "0");
let s = num.toString(16).padStart(2, "0");
if (num > 0xff) {
needAnotherIteration = true;
return s.slice(0, 2) + ":" + s.slice(2);

View File

@ -12,7 +12,7 @@ export function NWFConnStateInput(p: {
label="Connection state"
value={p.value}
onValueChange={(s) => {
p.onChange(s as any);
p.onChange?.(s as any);
}}
options={[
{ label: "None", value: undefined },

View File

@ -1,5 +1,3 @@
/* eslint-disable react-x/no-array-index-key */
/* eslint-disable react-hooks/exhaustive-deps */
import React from "react";
import { useNavigate } from "react-router-dom";
import { NWFilter, NWFilterURL } from "../../api/NWFilterApi";

View File

@ -13,7 +13,7 @@ export function NWFilterPriorityInput(p: {
value={p.value?.toString()}
type="number"
onValueChange={(v) => {
p.onChange(v && v !== "" ? Number(v) : undefined);
p.onChange?.(v && v !== "" ? Number(v) : undefined);
}}
size={ServerApi.Config.constraints.nwfilter_priority}
helperText="A lower priority value is accessed before one with a higher value"

View File

@ -1,4 +1,3 @@
/* eslint-disable react-x/no-array-index-key */
import ArrowDownwardIcon from "@mui/icons-material/ArrowDownward";
import ArrowUpwardIcon from "@mui/icons-material/ArrowUpward";
import DeleteIcon from "@mui/icons-material/Delete";
@ -67,19 +66,9 @@ export function NWFilterRules(p: {
deleteRule(n);
}}
onGoDown={
n < p.rules.length - 1
? () => {
swapRules(n, n + 1);
}
: undefined
}
onGoUp={
n > 0
? () => {
swapRules(n, n - 1);
}
: undefined
n < p.rules.length - 1 ? () => swapRules(n, n + 1) : undefined
}
onGoUp={n > 0 ? () => swapRules(n, n - 1) : undefined}
{...p}
/>
))}
@ -164,9 +153,7 @@ function NWRuleEdit(p: {
editable={p.editable}
onChange={p.onChange}
selector={s}
onDelete={() => {
deleteSelector(n);
}}
onDelete={() => deleteSelector(n)}
/>
))}
</CardContent>

View File

@ -25,7 +25,9 @@ export function NWFilterSelectInput(p: {
value={selectedValue}
onDelete={p.editable ? () => p.onChange?.(undefined) : undefined}
onClick={
!p.editable ? () => navigate(NWFilterURL(selectedValue)) : undefined
!p.editable && selectedValue
? () => navigate(NWFilterURL(selectedValue))
: undefined
}
/>
);
@ -46,7 +48,7 @@ export function NWFilterSelectInput(p: {
renderInput={(params) => (
<TextField {...params} variant="standard" label={p.label} />
)}
renderOption={(_props, option) => (
renderOption={(_props, option, _state) => (
<NWFilterItem
dense
onClick={() => {

View File

@ -1,10 +1,10 @@
/* eslint-disable react-x/no-array-index-key */
import { mdiIp } from "@mdi/js";
import Icon from "@mdi/react";
import DeleteIcon from "@mui/icons-material/Delete";
import {
Avatar,
Button,
Grid,
IconButton,
ListItem,
ListItemAvatar,
@ -19,7 +19,6 @@ import { useConfirm } from "../../hooks/providers/ConfirmDialogProvider";
import { IPInput } from "./IPInput";
import { MACInput } from "./MACInput";
import { TextInput } from "./TextInput";
import Grid from "@mui/material/Grid";
export function NetDHCPHostReservations(p: {
editable: boolean;
@ -40,7 +39,7 @@ export function NetDHCPHostReservations(p: {
<>
<Grid container>
{p.dhcp.hosts.map((h, num) => (
<Grid key={num} size={{ sm: 12, md: 6 }} style={{ padding: "10px" }}>
<Grid key={num} sm={12} md={6} item style={{ padding: "10px" }}>
<HostReservationWidget
key={num}
{...p}
@ -131,7 +130,7 @@ function HostReservationWidget(p: {
value={p.host.mac}
onValueChange={(v) => {
p.host.mac = v!;
p.onChange();
p.onChange?.();
}}
/>
)}
@ -143,7 +142,7 @@ function HostReservationWidget(p: {
value={p.host.ip}
onValueChange={(v) => {
p.host.ip = v!;
p.onChange();
p.onChange?.();
}}
/>
</div>

View File

@ -5,11 +5,11 @@ import {
Card,
CardActions,
CardContent,
Grid,
IconButton,
Tooltip,
Typography,
} from "@mui/material";
import Grid from "@mui/material/Grid";
import React, { PropsWithChildren } from "react";
import { NatEntry } from "../../api/NetworksApi";
import { ServerApi } from "../../api/ServerApi";
@ -54,7 +54,6 @@ export function NetNatConfiguration(p: {
<>
{p.nat.map((e, num) => (
<NatEntryForm
// eslint-disable-next-line react-x/no-array-index-key
key={num}
{...p}
entry={e}
@ -296,7 +295,7 @@ function NATEntryProp(
p: PropsWithChildren<{ label?: string }>
): React.ReactElement {
return (
<Grid size={{ sm: 12, md: 6 }} style={{ padding: "20px" }}>
<Grid item sm={12} md={6} style={{ padding: "20px" }}>
{p.label && (
<Typography variant="h6" style={{ marginBottom: "10px" }}>
{p.label}

View File

@ -12,7 +12,7 @@ export function PortInput(p: {
value={p.value?.toString() ?? ""}
type="number"
onValueChange={(v) => {
p.onChange(sanitizePort(v));
p.onChange?.(sanitizePort(v));
}}
checkValue={(v) => Number(v) <= 65535}
/>

View File

@ -24,13 +24,10 @@ export function RadioGroupInput(p: {
<RadioGroup
row
value={p.value}
onChange={(_ev, v) => {
p.onValueChange(v);
}}
onChange={(_ev, v) => p.onValueChange?.(v)}
>
{p.options.map((o) => (
<FormControlLabel
key={o.value}
disabled={!p.editable}
value={o.value}
control={<Radio />}

View File

@ -33,7 +33,7 @@ export function SelectInput(p: {
<Select
value={p.value ?? ""}
label={p.label}
onChange={(e) => { p.onValueChange(e.target.value); }}
onChange={(e) => p.onValueChange(e.target.value)}
>
{p.options.map((e) => (
<MenuItem

View File

@ -2,7 +2,7 @@ import { TextField } from "@mui/material";
import { LenConstraint } from "../../api/ServerApi";
/**
* Text input property edition
* Couple / Member property edition
*/
export function TextInput(p: {
label?: string;
@ -42,14 +42,12 @@ export function TextInput(p: {
e.target.value.length === 0 ? undefined : e.target.value
)
}
slotProps={{
htmlInput: {
maxLength: p.size?.max,
},
input: {
readOnly: !p.editable,
type: p.type,
},
inputProps={{
maxLength: p.size?.max,
}}
InputProps={{
readOnly: !p.editable,
type: p.type,
}}
variant={"standard"}
style={p.style ?? { width: "100%", marginBottom: "15px" }}

View File

@ -40,7 +40,6 @@ export function VMDisksList(p: {
{/* disks list */}
{p.vm.disks.map((d, num) => (
<DiskInfo
// eslint-disable-next-line react-x/no-array-index-key
key={num}
editable={p.editable}
disk={d}

View File

@ -1,4 +1,3 @@
/* eslint-disable react-x/no-array-index-key */
import DeleteIcon from "@mui/icons-material/Delete";
import {
Button,

View File

@ -1,17 +1,16 @@
/* eslint-disable react-x/no-array-index-key */
import { mdiNetworkOutline } from "@mdi/js";
import Icon from "@mdi/react";
import DeleteIcon from "@mui/icons-material/Delete";
import {
Avatar,
Button,
Grid,
IconButton,
ListItem,
ListItemAvatar,
ListItemText,
Tooltip,
} from "@mui/material";
import Grid from "@mui/material/Grid";
import { NWFilter } from "../../api/NWFilterApi";
import { NetworkInfo } from "../../api/NetworksApi";
import { ServerApi } from "../../api/ServerApi";
@ -52,6 +51,7 @@ export function VMNetworksList(p: {
{p.vm.networks.map((n, num) => (
<EditSection key={num}>
<NetworkInfoWidget
key={num}
network={n}
removeFromList={() => {
p.vm.networks.splice(num, 1);

View File

@ -19,7 +19,7 @@ export function VMSelectIsoInput(p: {
attachedISOs: string[];
onChange: (newVal: string[]) => void;
}): React.ReactElement {
if (p.attachedISOs.length === 0 && !p.editable) return <></>;
if (!p.attachedISOs && !p.editable) return <></>;
return (
<>
@ -27,7 +27,7 @@ export function VMSelectIsoInput(p: {
const iso = p.isoList.find((d) => d.filename === isoName);
return (
<ListItem
key={isoName}
key={num}
secondaryAction={
p.editable && (
<IconButton
@ -69,11 +69,12 @@ export function VMSelectIsoInput(p: {
}
}}
options={p.isoList.map((i) => {
return {
label: `${i.filename} ${filesize(i.size)}`,
value: i.filename,
};
})}
return {
label: `${i.filename} ${filesize(i.size)}`,
value: i.filename,
};
})
}
/>
</>
);

View File

@ -1,5 +1,4 @@
import { Button, Checkbox } from "@mui/material";
import Grid from "@mui/material/Grid";
import { Button, Checkbox, Grid } from "@mui/material";
import React from "react";
import { useNavigate } from "react-router-dom";
import { IpConfig, NetworkApi, NetworkInfo } from "../../api/NetworksApi";
@ -25,7 +24,7 @@ interface DetailsProps {
}
export function NetworkDetails(p: DetailsProps): React.ReactElement {
const [nicsList, setNicsList] = React.useState<string[] | undefined>();
const [nicsList, setNicsList] = React.useState<string[] | any>();
const load = async () => {
setNicsList(await ServerApi.GetNetworksList());
@ -36,7 +35,7 @@ export function NetworkDetails(p: DetailsProps): React.ReactElement {
loadKey={"1"}
load={load}
errMsg="Failed to load the list of host network cards!"
build={() => <NetworkDetailsInner nicsList={nicsList!} {...p} />}
build={() => <NetworkDetailsInner nicsList={nicsList} {...p} />}
/>
);
}
@ -260,7 +259,7 @@ function IPSection(p: {
const confirm = useConfirm();
const toggleNetwork = async () => {
if (p.config) {
if (!!p.config) {
if (
!(await confirm(
`Do you really want to disable IPv${p.version} on this network? Specific configuration will be deleted!`
@ -268,11 +267,11 @@ function IPSection(p: {
)
return;
p.onChange(undefined);
p.onChange?.(undefined);
return;
}
p.onChange({
p.onChange?.({
bridge_address: p.version === 4 ? "192.168.1.1" : "fd00::1",
prefix: p.version === 4 ? 24 : 8,
});
@ -298,7 +297,7 @@ function IPSection(p: {
p.config!.dhcp = undefined;
}
p.onChange(p.config);
p.onChange?.(p.config);
};
const toggleNAT = async (v: boolean) => {
@ -306,7 +305,7 @@ function IPSection(p: {
p.config!.nat = [];
} else {
if (
(p.config?.nat?.length ?? 0) > 0 &&
(p.config?.nat?.length ?? 0 > 0) &&
!(await confirm(
`Do you really want to disable IPv${p.version} NAT port forwarding on this network? Specific configuration will be deleted!`
))
@ -315,7 +314,7 @@ function IPSection(p: {
p.config!.nat = undefined;
}
p.onChange(p.config);
p.onChange?.(p.config);
};
if (!p.config && !p.editable) return <></>;
@ -338,10 +337,10 @@ function IPSection(p: {
editable={p.editable}
label="Bridge address"
version={p.version}
value={p.config.bridge_address}
value={p.config?.bridge_address}
onValueChange={(v) => {
p.config!.bridge_address = v ?? "";
p.onChange(p.config);
p.onChange?.(p.config);
}}
/>
@ -352,7 +351,7 @@ function IPSection(p: {
type="number"
onValueChange={(v) => {
p.config!.prefix = Number(v);
p.onChange(p.config);
p.onChange?.(p.config);
}}
size={
p.version === 4 ? { min: 0, max: 32 } : { min: 0, max: 128 }
@ -407,7 +406,7 @@ function IPSection(p: {
dhcp={p.config.dhcp}
onChange={(d) => {
p.config!.dhcp = d;
p.onChange(p.config);
p.onChange?.(p.config);
}}
/>
</EditSection>
@ -431,7 +430,7 @@ function IPSection(p: {
nat={p.config.nat}
onChange={(n) => {
p.config!.nat = n;
p.onChange(p.config);
p.onChange?.(p.config);
}}
/>
)}

View File

@ -29,13 +29,13 @@ export function NetworkStatusWidget(p: {
}
};
const changedAction = () => { setState(undefined); };
const changedAction = () => setState(undefined);
React.useEffect(() => {
refresh();
const i = setInterval(() => refresh(), 3000);
return () => { clearInterval(i); };
return () => clearInterval(i);
});
if (state === undefined)

View File

@ -1,5 +1,4 @@
import { Button } from "@mui/material";
import Grid from "@mui/material/Grid";
import { Button, Grid } from "@mui/material";
import React, { ReactElement } from "react";
import { useNavigate } from "react-router-dom";
import {
@ -7,7 +6,6 @@ import {
NWFilterApi,
NWFilterIsBuiltin,
} from "../../api/NWFilterApi";
import { ServerApi } from "../../api/ServerApi";
import { useAlert } from "../../hooks/providers/AlertDialogProvider";
import { useConfirm } from "../../hooks/providers/ConfirmDialogProvider";
import { useSnackbar } from "../../hooks/providers/SnackbarProvider";
@ -15,11 +13,12 @@ import { AsyncWidget } from "../AsyncWidget";
import { TabsWidget } from "../TabsWidget";
import { XMLAsyncWidget } from "../XMLWidget";
import { EditSection } from "../forms/EditSection";
import { NWFSelectReferencedFilters } from "../forms/NWFSelectReferencedFilters";
import { NWFilterPriorityInput } from "../forms/NWFilterPriorityInput";
import { NWFilterRules } from "../forms/NWFilterRules";
import { SelectInput } from "../forms/SelectInput";
import { TextInput } from "../forms/TextInput";
import { ServerApi } from "../../api/ServerApi";
import { SelectInput } from "../forms/SelectInput";
import { NWFSelectReferencedFilters } from "../forms/NWFSelectReferencedFilters";
import { NWFilterRules } from "../forms/NWFilterRules";
import { NWFilterPriorityInput } from "../forms/NWFilterPriorityInput";
interface DetailsProps {
nwfilter: NWFilter;
@ -28,9 +27,7 @@ interface DetailsProps {
}
export function NWFilterDetails(p: DetailsProps): ReactElement {
const [nwFiltersList, setNwFiltersList] = React.useState<
NWFilter[] | undefined
>();
const [nwFiltersList, setNwFiltersList] = React.useState<NWFilter[] | any>();
const load = async () => {
setNwFiltersList(await NWFilterApi.GetList());
@ -42,7 +39,7 @@ export function NWFilterDetails(p: DetailsProps): ReactElement {
load={load}
errMsg="Failed to load the list of network filters!"
build={() => (
<NetworkFilterDetailsInner nwFiltersList={nwFiltersList!} {...p} />
<NetworkFilterDetailsInner nwFiltersList={nwFiltersList} {...p} />
)}
/>
);
@ -118,7 +115,7 @@ function NetworkFilterDetailsTabGeneral(
p.nwfilter.name = v ?? "";
p.onChange?.();
}}
checkValue={(v) => /^[a-zA-Z0-9_-]+$/.test(v)}
checkValue={(v) => /^[a-zA-Z0-9\_\-]+$/.test(v)}
size={ServerApi.Config.constraints.nwfilter_name_size}
/>

View File

@ -1,8 +1,6 @@
import { Button } from "@mui/material";
import Grid from "@mui/material/Grid";
import { Button, Grid } from "@mui/material";
import React from "react";
import { useNavigate } from "react-router-dom";
import { GroupApi } from "../../api/GroupApi";
import { NWFilter, NWFilterApi } from "../../api/NWFilterApi";
import { NetworkApi, NetworkInfo } from "../../api/NetworksApi";
import { ServerApi } from "../../api/ServerApi";
@ -36,14 +34,12 @@ interface DetailsProps {
export function APITokenDetails(p: DetailsProps): React.ReactElement {
const [vms, setVMs] = React.useState<VMInfo[]>();
const [groups, setGroups] = React.useState<string[]>();
const [networks, setNetworks] = React.useState<NetworkInfo[]>();
const [nwFilters, setNetworkFilters] = React.useState<NWFilter[]>();
const [tokens, setTokens] = React.useState<APIToken[]>();
const load = async () => {
setVMs(await VMApi.GetList());
setGroups(await GroupApi.GetList());
setNetworks(await NetworkApi.GetList());
setNetworkFilters(await NWFilterApi.GetList());
setTokens(await TokensApi.GetList());
@ -57,7 +53,6 @@ export function APITokenDetails(p: DetailsProps): React.ReactElement {
build={() => (
<APITokenDetailsInner
vms={vms!}
groups={groups!}
networks={networks!}
nwFilters={nwFilters!}
tokens={tokens!}
@ -77,7 +72,6 @@ enum TokenTab {
type DetailsInnerProps = DetailsProps & {
vms: VMInfo[];
groups: string[];
networks: NetworkInfo[];
nwFilters: NWFilter[];
tokens: APIToken[];
@ -161,14 +155,14 @@ function APITokenTabGeneral(p: DetailsInnerProps): React.ReactElement {
{p.status === TokenWidgetStatus.Create && (
<RadioGroupInput
{...p}
editable={true}
editable={p.status === TokenWidgetStatus.Create}
options={[
{ label: "IPv4", value: "4" },
{ label: "IPv6", value: "6" },
]}
value={ipVersion.toString()}
onValueChange={(v) => {
setIpVersion(Number(v) as 4 | 6);
setIpVersion(Number(v) as any);
}}
label="Token IP restriction version"
/>

View File

@ -63,7 +63,6 @@ export function TokenRawRightsEditor(p: {
</TableHead>
<TableBody>
{p.token.rights.map((r, num) => (
// eslint-disable-next-line react-x/no-array-index-key
<TableRow key={num} hover>
<TableCell style={{ width: "100px" }}>
<SelectInput
@ -96,11 +95,7 @@ export function TokenRawRightsEditor(p: {
</TableCell>
{p.editable && (
<TableCell style={{ width: "100px" }}>
<IconButton
onClick={() => {
deleteRule(num);
}}
>
<IconButton onClick={() => deleteRule(num)}>
<Tooltip title="Remove the rule">
<DeleteIcon />
</Tooltip>

Some files were not shown because too many files have changed in this diff Show More