From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [IPv6:2a0f:8001:1:32::40]) by lore.proxmox.com (Postfix) with ESMTPS id B5E951FF0B4 for ; Fri, 27 Nov 2026 17:14:33 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 5F826217C0; Fri, 27 Nov 2026 17:14:22 +0100 (CET) From: Dominik Csapak To: pdm-devel@lists.proxmox.com Subject: [PATCH datacenter-manager 34/38] ui: views: map: show running remote migrations Date: Fri, 27 Nov 2026 17:12:31 +0100 Message-ID: <20261127161241.3713494-35-d.csapak@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261127161241.3713494-1-d.csapak@proxmox.com> References: <20261127161241.3713494-1-d.csapak@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-SPAM-LEVEL: Spam detection results: 0 AWL 0.248 Adjusted score from AWL reputation of From: address DMARC_MISSING 0.1 Missing DMARC policy KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment (newer systems) RCVD_IN_DNSWL_MED -2.3 Sender listed at https://www.dnswl.org/, medium trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record WEIRD_PORT 0.001 Uses non-standard port number for HTTP Message-ID-Hash: AQZNTO7L5AKLO4LW6TOSNDMYPPJWZQAY X-Message-ID-Hash: AQZNTO7L5AKLO4LW6TOSNDMYPPJWZQAY X-MailFrom: d.csapak@proxmox.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; digests; suspicious-header X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox Datacenter Manager development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: as animated lines between the locations of the source and the target remote, so one can see at a glance what is currently moved where. Each line is labeled and shows the guest and its route as tooltip. The task list does not contain the target of a migration, so read it from the start of the task log, where PVE logs the target node and the address it connects to. For a remote migration, that is the address of the target endpoint, which we match against the nodes of the other configured PVE remotes. Migrations inside of a cluster don't match any of those and are not shown. Since the target of a task never changes, the log of each task is only read once. This also shows remote migrations that were not started via PDM, as long as they use an address that is configured for the target remote. If the location of a node is not known, fall back to any other location of its remote, since that is still better than showing nothing. Migrations start and finish much faster than the other data of a view changes, so load them with their own short interval instead of with the regular refresh. Most of the time there is no change between two loads though, so the map is only updated if there is one. The view itself only renders for them if there is an error to show, and they are not loaded at all while the page is hidden. Signed-off-by: Dominik Csapak --- ui/src/dashboard/map.rs | 291 +++++++++++++++++++++++++++++++++++++-- ui/src/dashboard/mod.rs | 2 +- ui/src/dashboard/view.rs | 72 +++++++++- 3 files changed, 346 insertions(+), 19 deletions(-) diff --git a/ui/src/dashboard/map.rs b/ui/src/dashboard/map.rs index 831b1951..5ff21dab 100644 --- a/ui/src/dashboard/map.rs +++ b/ui/src/dashboard/map.rs @@ -1,33 +1,152 @@ -use std::cell::OnceCell; +use std::cell::{OnceCell, RefCell}; use std::collections::HashMap; use std::collections::HashSet; use std::hash::Hash; use std::rc::Rc; use anyhow::Error; +use futures::future::join_all; use geojson::GeoJson; +use serde::Deserialize; +use serde_json::json; use yew::virtual_dom::{VComp, VNode}; -use proxmox_yew_comp::Status; +use proxmox_yew_comp::percent_encoding::percent_encode_component; +use proxmox_yew_comp::{Status, http_get}; use pwt::css; use pwt::prelude::*; use pwt::state::{Loader, SharedState, SharedStateObserver}; use pwt::widget::canvas::Group; use pwt::widget::charts::{ - Location, MapPointData, PointsRenderArgs, WorldMap, WorldPoint, render_point_default, - render_tooltip_default, + Location, MapConnection, MapPointData, PointsRenderArgs, WorldMap, WorldPoint, + render_point_default, render_tooltip_default, }; use pwt::widget::container::span; use pwt::widget::{ActionIcon, Column, Container, Fa, Panel, Row, Tooltip, error_message}; use pwt_macros::{builder, widget}; use crate::dashboard::loading_column; -use crate::{LoadResult, navigate_to}; +use crate::{LoadResult, RemoteList, navigate_to}; use pdm_api_types::CachedLocationInfo; use pdm_api_types::Location as RemoteLocation; use pdm_api_types::remotes::RemoteType; use pdm_api_types::resource::{RemoteInfo, RemoteStatus, ResourcesStatus}; +use pdm_api_types::{RemoteUpid, TaskListItem}; + +/// A running migration of a guest, as found in the log of its task. +#[derive(Clone, PartialEq, Debug)] +pub struct RunningMigration { + /// The remote the guest is migrated away from. + remote: String, + /// The node the guest is migrated away from. + node: String, + /// The migrated guest as named by the task log, for example `VM 100`. + guest: String, + /// The node the guest is migrated to. + target_node: String, + /// The address the source node uses to reach the target node. + target_host: String, +} + +/// Remembers the migrations of the running tasks by their UPID. +/// +/// The target of a task never changes, so its log only has to be read once. +pub type RunningMigrationCache = Rc>>; + +#[derive(Deserialize)] +struct TaskLogLine { + t: String, +} + +/// Extracts the guest, the target node and its address from a line of a migration task log, +/// for example: +/// +/// `starting migration of VM 100 to node 'pve2' (192.0.2.2)` +fn parse_migration_target(line: &str) -> Option<(&str, &str, &str)> { + let (_, rest) = line.split_once("starting migration of ")?; + let (guest, rest) = rest.split_once(" to node '")?; + let (node, rest) = rest.split_once("' (")?; + let host = rest.trim_end().strip_suffix(')')?; + Some((guest, node, host)) +} + +async fn load_running_migration(task: &TaskListItem) -> Option { + let upid: RemoteUpid = task.upid.parse().ok()?; + let url = format!( + "/pve/remotes/{}/tasks/{}/log", + percent_encode_component(upid.remote()), + percent_encode_component(&task.upid), + ); + // the target is logged right at the start, so the first lines are enough + let lines: Vec = http_get(url, None).await.ok()?; + let (guest, target_node, target_host) = lines + .iter() + .find_map(|line| parse_migration_target(&line.t))?; + + Some(RunningMigration { + remote: upid.remote().to_string(), + node: task.node.clone(), + guest: guest.to_string(), + target_node: target_node.to_string(), + target_host: target_host.to_string(), + }) +} + +/// Loads the running guest migrations from the task list and the logs of the tasks. +/// +/// Migrations whose log cannot be read, or does not contain the target yet, are left out. +pub async fn load_running_migrations( + view: Option, + cache: RunningMigrationCache, +) -> Result, Error> { + let mut params = json!({ + "running": true, + "typefilter": "migrate", + "limit": 0, + }); + if let Some(view) = view { + params["view"] = view.to_string().into(); + } + let mut tasks: Vec = http_get("/remotes/tasks/list", Some(params)).await?; + tasks.retain(|task| matches!(task.worker_type.as_str(), "qmigrate" | "vzmigrate")); + + let migrations = join_all(tasks.iter().map(|task| { + let cache = cache.clone(); + async move { + let cached = cache.borrow().get(&task.upid).cloned(); + match cached { + Some(migration) => Some(migration), + None => load_running_migration(task).await, + } + } + })) + .await; + + // also drops the tasks that are not running anymore + *cache.borrow_mut() = tasks + .iter() + .zip(&migrations) + .filter_map(|(task, migration)| Some((task.upid.clone(), migration.clone()?))) + .collect(); + + Ok(migrations.into_iter().flatten().collect()) +} + +/// Returns the address of a node without its port and without the brackets of an IPv6 address. +fn host_of(hostname: &str) -> &str { + let host = match hostname.rsplit_once(':') { + Some((host, port)) + if !port.is_empty() + && port.bytes().all(|b| b.is_ascii_digit()) + && (!host.contains(':') || host.ends_with(']')) => + { + host + } + _ => hostname, + }; + host.trim_start_matches('[').trim_end_matches(']') +} #[widget(comp=DashboardMapComp, @element)] #[builder] @@ -35,20 +154,28 @@ use pdm_api_types::resource::{RemoteInfo, RemoteStatus, ResourcesStatus}; pub struct DashboardMap { status: SharedState>, locations: SharedState, Error>>, + migrations: SharedState, Error>>, } impl DashboardMap { pub fn new( status: SharedState>, locations: SharedState, Error>>, + migrations: SharedState, Error>>, ) -> Self { - yew::props!(Self { status, locations }) + yew::props!(Self { + status, + locations, + migrations, + }) } } pub enum Msg { MapLoaded, DataChanged, + MigrationsChanged, + RemoteListChanged(RemoteList), } thread_local! { @@ -59,8 +186,12 @@ thread_local! { pub struct DashboardMapComp { loader: Loader, points: Vec>, + connections: Vec, _status_observer: SharedStateObserver>, _location_observer: SharedStateObserver, Error>>, + _migration_observer: SharedStateObserver, Error>>, + remote_list: RemoteList, + _remote_list_handle: Option>, } #[derive(PartialEq, Debug)] @@ -129,6 +260,72 @@ impl DashboardMapComp { points.sort_by_cached_key(|loc| loc.data.render_title()); points } + + // A migration to another remote logs the address of the endpoint it connects to, which is + // the only hint to the target remote. Migrations inside of a cluster log an address too, + // so the source remote is never a candidate. + fn find_target_remote(&self, migration: &RunningMigration) -> Option<&str> { + self.remote_list + .iter() + .filter(|remote| remote.ty == RemoteType::Pve && remote.id != migration.remote) + .find(|remote| { + remote.nodes.iter().any(|node| { + host_of(&node.hostname).eq_ignore_ascii_case(host_of(&migration.target_host)) + }) + }) + .map(|remote| remote.id.as_str()) + } + + fn calculate_connections(&self, ctx: &Context) -> Vec { + let points = &self.points; + let read_guard = ctx.props().migrations.read(); + let Some(migrations) = &read_guard.data else { + return Vec::new(); + }; + + // a node without a known location still belongs to its remote, so fall back to any + // point of the remote + let find_point = |remote: &str, node: Option<&str>| { + let points_of_remote = || { + points + .iter() + .enumerate() + .filter(|(_, point)| point.data.remote.name == remote) + }; + points_of_remote() + .find(|(_, point)| { + node.is_some_and(|node| point.data.nodes.iter().any(|n| n == node)) + }) + .or_else(|| points_of_remote().next()) + .map(|(index, _)| index) + }; + + migrations + .iter() + .filter_map(|migration| { + let target_remote = self.find_target_remote(migration)?; + let from = find_point(&migration.remote, Some(&migration.node))?; + let to = find_point(target_remote, Some(&migration.target_node))?; + let tooltip = Row::new() + .gap(2) + .class(css::AlignItems::Center) + .with_child(span(&migration.guest)) + .with_child(span(format!("{}/{}", migration.remote, migration.node))) + .with_child(Fa::new("long-arrow-right")) + .with_child(span(format!("{target_remote}/{}", migration.target_node))); + Some( + MapConnection::new(from, to) + .label(tr!("Migration")) + .tooltip(tooltip), + ) + }) + .collect() + } + + fn update_data(&mut self, ctx: &Context) { + self.points = Self::calculate_points(ctx); + self.connections = self.calculate_connections(ctx); + } } impl yew::Component for DashboardMapComp { @@ -161,14 +358,28 @@ impl yew::Component for DashboardMapComp { .locations .add_listener(ctx.link().callback(|_| Msg::DataChanged)); - let points = Self::calculate_points(ctx); + let _migration_observer = ctx + .props() + .migrations + .add_listener(ctx.link().callback(|_| Msg::MigrationsChanged)); + + let (remote_list, _remote_list_handle) = ctx + .link() + .context(ctx.link().callback(Msg::RemoteListChanged)) + .unzip(); - Self { + let mut this = Self { loader, - points, + points: Vec::new(), + connections: Vec::new(), _status_observer, _location_observer, - } + _migration_observer, + remote_list: remote_list.unwrap_or_default(), + _remote_list_handle, + }; + this.update_data(ctx); + this } fn update(&mut self, ctx: &Context, msg: Self::Message) -> bool { @@ -179,8 +390,18 @@ impl yew::Component for DashboardMapComp { let _ = WORLD_MAP.with(|cache| cache.set(Rc::clone(world_map))); } } - Msg::DataChanged => { - self.points = Self::calculate_points(ctx); + Msg::DataChanged => self.update_data(ctx), + Msg::MigrationsChanged => { + // they are loaded far more often than they change + let connections = self.calculate_connections(ctx); + if connections == self.connections { + return false; + } + self.connections = connections; + } + Msg::RemoteListChanged(remote_list) => { + self.remote_list = remote_list; + self.update_data(ctx); } } true @@ -205,6 +426,7 @@ impl yew::Component for DashboardMapComp { .listeners(&props.listeners) .max_zoom_level(100.0) .points(self.points.clone()) + .connections(self.connections.clone()) .into() } } @@ -407,9 +629,12 @@ impl MapPointData for PoiInfo { pub fn create_map_panel( status: SharedState>, locations: SharedState, Error>>, + migrations: SharedState, Error>>, ) -> Panel { Panel::new() - .with_child(DashboardMap::new(status.clone(), locations.clone()).flex(1.0)) + .with_child( + DashboardMap::new(status.clone(), locations.clone(), migrations.clone()).flex(1.0), + ) .with_optional_child( status .read() @@ -424,4 +649,44 @@ pub fn create_map_panel( .as_ref() .map(|err| error_message(&format!("locations - {err}"))), ) + .with_optional_child( + migrations + .read() + .error + .as_ref() + .map(|err| error_message(&format!("migrations - {err}"))), + ) +} + +#[cfg(test)] +mod test { + use super::{host_of, parse_migration_target}; + + #[test] + fn test_parse_migration_target() { + assert_eq!( + parse_migration_target( + "2026-11-13 10:00:00 starting migration of VM 100 to node 'pve2' (192.0.2.2)" + ), + Some(("VM 100", "pve2", "192.0.2.2")), + ); + assert_eq!( + parse_migration_target("starting migration of CT 101 to node 'n1' (pve.example.com)\n"), + Some(("CT 101", "n1", "pve.example.com")), + ); + assert_eq!( + parse_migration_target("starting VM 100 on remote node 'pve2'"), + None + ); + } + + #[test] + fn test_host_of() { + assert_eq!(host_of("pve.example.com"), "pve.example.com"); + assert_eq!(host_of("pve.example.com:8006"), "pve.example.com"); + assert_eq!(host_of("192.0.2.2:443"), "192.0.2.2"); + assert_eq!(host_of("[2001:db8::2]:8006"), "2001:db8::2"); + assert_eq!(host_of("[2001:db8::2]"), "2001:db8::2"); + assert_eq!(host_of("2001:db8::2"), "2001:db8::2"); + } } diff --git a/ui/src/dashboard/mod.rs b/ui/src/dashboard/mod.rs index fdf08c43..3f2dc2db 100644 --- a/ui/src/dashboard/mod.rs +++ b/ui/src/dashboard/mod.rs @@ -21,7 +21,7 @@ mod guest_panel; pub use guest_panel::create_guest_panel; mod map; -pub use map::create_map_panel; +pub use map::{RunningMigration, RunningMigrationCache, create_map_panel, load_running_migrations}; mod node_status_panel; use node_status_panel::create_node_panel; diff --git a/ui/src/dashboard/view.rs b/ui/src/dashboard/view.rs index 64480310..76ae90c2 100644 --- a/ui/src/dashboard/view.rs +++ b/ui/src/dashboard/view.rs @@ -3,6 +3,7 @@ use std::rc::Rc; use anyhow::Error; use futures::join; +use gloo_timers::callback::Interval; use js_sys::Date; use serde_json::{Value, json}; use yew::virtual_dom::{VComp, VNode}; @@ -25,10 +26,11 @@ use crate::dashboard::refresh_config_edit::{ use crate::dashboard::subscription_info::create_subscriptions_dialog; use crate::dashboard::tasks::get_task_options; use crate::dashboard::{ - DashboardStatusRow, create_gauge_panel, create_guest_panel, create_map_panel, - create_node_panel, create_pbs_datastores_panel, create_refresh_config_edit_window, - create_remote_panel, create_resource_tree, create_sdn_panel, create_subscription_panel, - create_task_summary_panel, create_top_entities_panel, + DashboardStatusRow, RunningMigration, RunningMigrationCache, create_gauge_panel, + create_guest_panel, create_map_panel, create_node_panel, create_pbs_datastores_panel, + create_refresh_config_edit_window, create_remote_panel, create_resource_tree, create_sdn_panel, + create_subscription_panel, create_task_summary_panel, create_top_entities_panel, + load_running_migrations, }; use crate::remotes::AddWizard; use crate::renderer::empty_state; @@ -87,6 +89,7 @@ pub enum LoadingResult { TaskStatistics(Result), SubscriptionInfo(Result, Error>), Locations(Result, Error>), + Migrations(Result, Error>), All, } @@ -101,6 +104,7 @@ pub enum Msg { LayoutUpdate(ViewLayout), UpdateResult(Result<(), Error>), ForceSubscriptionUpdate, + ReloadMigrations, RemoteListUpdate(RemoteList), } @@ -108,6 +112,9 @@ struct ViewComp { template: LoadResult, render_args: WidgetRenderArgs, + running_migrations: RunningMigrationCache, + migrations_loading: bool, + _migration_timer: Interval, refresh_config: PersistentState, async_pool: AsyncPool, @@ -131,6 +138,7 @@ struct WidgetRenderArgs { top_entities: SharedState>, statistics: SharedState>, locations: SharedState, Error>>, + migrations: SharedState, Error>>, redraw_controller: RedrawController, } @@ -146,6 +154,7 @@ fn render_widget( top_entities, statistics, locations, + migrations, redraw_controller, } = render_args; @@ -182,7 +191,7 @@ fn render_widget( resource, remote_type, } => create_gauge_panel(*resource, *remote_type, status), - WidgetType::Map => create_map_panel(status, locations), + WidgetType::Map => create_map_panel(status, locations, migrations), WidgetType::UnknownWidget { widget_type, .. } => create_unknown_widget_panel(widget_type), }; @@ -193,7 +202,32 @@ fn render_widget( widget.border(false).class(css::FlexFit).into() } +// Migrations come and go much faster than the other data changes. +const MIGRATION_REFRESH_INTERVAL_MS: u32 = 1000; + impl ViewComp { + fn reload_migrations(&mut self, ctx: &yew::Context) { + let required = self + .template + .data + .as_ref() + .is_some_and(|template| required_api_calls(&template.layout).migrations); + // skip a turn instead of piling up requests when loading takes longer than the interval, + // and while nobody can see the result anyway + if !required || self.migrations_loading || gloo_utils::document().hidden() { + return; + } + + self.migrations_loading = true; + let link = ctx.link().clone(); + let view = ctx.props().view.clone(); + let running_migrations = self.running_migrations.clone(); + self.async_pool.spawn(async move { + let res = load_running_migrations(view, running_migrations).await; + link.send_message(Msg::LoadingResult(LoadingResult::Migrations(res))); + }); + } + fn reload(&mut self, ctx: &yew::Context) { let max_age = if self.load_finished_time.is_some() { self.refresh_config.max_age.unwrap_or(DEFAULT_MAX_AGE_S) @@ -297,6 +331,7 @@ struct RequiredApiCalls { top_entities: bool, task_statistics: bool, locations: bool, + migrations: bool, } fn required_api_calls(layout: &ViewLayout) -> RequiredApiCalls { @@ -325,6 +360,7 @@ fn required_api_calls(layout: &ViewLayout) -> RequiredApiCalls { WidgetType::Map => { api_calls.status = true; api_calls.locations = true; + api_calls.migrations = true; } WidgetType::UnknownWidget { .. } => {} } @@ -388,8 +424,15 @@ impl Component for ViewComp { statistics: SharedState::new(LoadResult::new()), subscriptions: SharedState::new(LoadResult::new()), locations: SharedState::new(LoadResult::new()), + migrations: SharedState::new(LoadResult::new()), redraw_controller: RedrawController::new(), }, + running_migrations: Default::default(), + migrations_loading: false, + _migration_timer: Interval::new(MIGRATION_REFRESH_INTERVAL_MS, { + let link = link.clone(); + move || link.send_message(Msg::ReloadMigrations) + }), } } @@ -398,6 +441,8 @@ impl Component for ViewComp { Msg::ViewTemplateLoaded(view_template) => { self.template.update(view_template); self.reload(ctx); + // don't wait for the next turn of the timer + self.reload_migrations(ctx); } Msg::LoadingResult(loading_result) => match loading_result { LoadingResult::Resources(status) => self.render_args.status.write().update(status), @@ -413,6 +458,15 @@ impl Component for ViewComp { LoadingResult::Locations(locations) => { self.render_args.locations.write().update(locations); } + LoadingResult::Migrations(migrations) => { + self.migrations_loading = false; + let had_error = self.render_args.migrations.read().error.is_some(); + let has_error = migrations.is_err(); + self.render_args.migrations.write().update(migrations); + // The map follows the migrations on its own, and they are loaded much too + // often to render the whole view each time. Only their error is shown here. + return had_error || has_error; + } LoadingResult::All => { self.loading = false; if self.load_finished_time.is_none() { @@ -423,6 +477,10 @@ impl Component for ViewComp { self.load_finished_time = Some(Date::now() / 1000.0); } }, + Msg::ReloadMigrations => { + self.reload_migrations(ctx); + return false; + } Msg::CreateWizard(remote_type) => { self.show_create_wizard = remote_type; } @@ -510,6 +568,10 @@ impl Component for ViewComp { fn changed(&mut self, ctx: &Context, _old_props: &Self::Properties) -> bool { self.async_pool = AsyncPool::new(); + // the old pool took a pending request with it + self.migrations_loading = false; + // they belong to the old view + self.render_args.migrations.write().clear(); self.load_finished_time = None; let view = ctx.props().view.clone(); self.async_pool.send_future(ctx.link().clone(), async move { -- 2.47.3