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 65A881FF0B3 for ; Thu, 26 Nov 2026 17:09:13 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 28A332170B; Thu, 26 Nov 2026 17:09:09 +0100 (CET) From: Jakob Klocker To: pdm-devel@lists.proxmox.com Subject: [PATCH proxmox-datacenter-manager 2/2] metric collection: add tests for fetching PVE clusters node by node Date: Thu, 26 Nov 2026 17:07:07 +0100 Message-ID: <20261126160707.333024-3-j.klocker@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261126160707.333024-1-j.klocker@proxmox.com> References: <20261126160707.333024-1-j.klocker@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Bm-Milter-Handled: 55990f41-d878-4baa-be0a-ee34c49e34d2 X-Bm-Transport-Timestamp: 1795709343709 X-SPAM-LEVEL: Spam detection results: 0 AWL 1.084 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 Message-ID-Hash: BAWO6YZQ4FYOPFC7ZQBHYAXJJCSL4YX2 X-Message-ID-Hash: BAWO6YZQ4FYOPFC7ZQBHYAXJJCSL4YX2 X-MailFrom: j.klocker@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: Cover large clusters fetched node by node, a single failing node, all nodes failing, and the fallback for PVE versions without `node-list`. Signed-off-by: Jakob Klocker --- .../remote_collection_task.rs | 282 ++++++++++++++++-- 1 file changed, 262 insertions(+), 20 deletions(-) diff --git a/server/src/metric_collection/remote_collection_task.rs b/server/src/metric_collection/remote_collection_task.rs index 9c3f8522..d6bfdce5 100644 --- a/server/src/metric_collection/remote_collection_task.rs +++ b/server/src/metric_collection/remote_collection_task.rs @@ -465,6 +465,8 @@ pub(super) fn load_state() -> Result { #[cfg(test)] pub(super) mod tests { + use std::collections::HashSet; + use anyhow::bail; use http::StatusCode; @@ -498,8 +500,16 @@ pub(super) mod tests { Ok(Arc::new(TestPveClient { fail: remote.id.contains("fail"), now: self.now, + nodes: if remote.id.contains("large") { + PER_NODE_FETCH_THRESHOLD + 2 + } else { + PER_NODE_FETCH_THRESHOLD - 1 + }, + node_list_unsupported: remote.id.contains("old"), + failing_node: remote.id.contains("partial").then(|| "node-0".to_string()), })) } + /// Create a new API client for PVE remotes, but with a specific endpoint. fn make_pve_client_with_endpoint( &self, @@ -535,18 +545,27 @@ pub(super) mod tests { struct TestPveClient { now: i64, fail: bool, + nodes: usize, + node_list_unsupported: bool, + failing_node: Option, + } + + impl TestPveClient { + /// Names of all nodes in the faked cluster. + fn node_names(&self) -> impl Iterator { + (0..self.nodes).map(|i| format!("node-{i}")) + } } #[async_trait::async_trait] impl pve_api_types::client::PveClient for TestPveClient { /// List the nodes of the cluster. async fn list_nodes(&self) -> Result, proxmox_client::Error> { - // Fewer nodes than PER_NODE_FETCH_THRESHOLD, so the existing tests keep - // using a single cluster-wide request. - Ok((0..PER_NODE_FETCH_THRESHOLD - 1) - .map(|i| { + Ok(self + .node_names() + .map(|node| { serde_json::from_value(serde_json::json!({ - "node": format!("node-{i}"), + "node": node, "status": "online", })) .unwrap() @@ -559,10 +578,30 @@ pub(super) mod tests { &self, _history: Option, _local_only: Option, - _node_list: Option, + node_list: Option, start_time: Option, ) -> Result { - if self.fail { + if node_list.is_some() && self.node_list_unsupported { + let msg = "Parameter verification failed.\n\n\ + node-list: property is not defined in schema"; + return Err(proxmox_client::Error::Api( + StatusCode::BAD_REQUEST, + msg.into(), + )); + } + + // Like PVE, only return data for the requested nodes if `node-list` is set. + let nodes: Vec = match node_list { + Some(list) => list.split(',').map(String::from).collect(), + None => self.node_names().collect(), + }; + + if self.fail + || self + .failing_node + .as_ref() + .is_some_and(|failing| nodes.contains(failing)) + { return Err(proxmox_client::Error::Api( StatusCode::INTERNAL_SERVER_ERROR, "internal server error".into(), @@ -584,8 +623,8 @@ pub(super) mod tests { value: 0.1, }; - for i in 0..5 { - let id = format!("node/node-{i}"); + for node in &nodes { + let id = format!("node/{node}"); data.push(point(&id, "cpu_current", time, Gauge)); } @@ -597,6 +636,17 @@ pub(super) mod tests { } } + fn make_remote(name: &str) -> Remote { + Remote { + ty: RemoteType::Pve, + id: name.into(), + nodes: Vec::new(), + authid: Authid::root_auth_id().clone(), + token: "".into(), + web_url: None, + } + } + fn make_remote_config() -> SectionConfigData { let mut sections = SectionConfigData::default(); @@ -604,17 +654,7 @@ pub(super) mod tests { let status = if i >= 2 { "fail" } else { "pass" }; let name = format!("pve-{i}-{status}"); - sections.insert( - name.clone(), - Remote { - ty: pdm_api_types::remotes::RemoteType::Pve, - id: name.clone(), - nodes: Vec::new(), - authid: Authid::root_auth_id().clone(), - token: "".into(), - web_url: None, - }, - ); + sections.insert(name.clone(), make_remote(&name)); } sections @@ -642,6 +682,29 @@ pub(super) mod tests { number_of_requests } + /// Like `fake_rrd_task`, but returns the received PVE metrics. + async fn collecting_rrd_task(mut rx: Receiver) -> Vec { + let mut received = Vec::new(); + + while let Some(request) = rx.recv().await { + if let RrdStoreRequest::Pve { + metrics, channel, .. + } = request + { + let most_recent_timestamp = + metrics.data.iter().map(|e| e.timestamp).max().unwrap_or(0); + + received.push(metrics); + + let _ = channel.send(RrdStoreResult { + most_recent_timestamp, + }); + } + } + + received + } + const NOW: i64 = 1000; struct TestContextFactory(); @@ -761,4 +824,183 @@ pub(super) mod tests { drop(task); assert_eq!(handle.await.unwrap(), 1); } + + #[tokio::test] + async fn test_fetch_remotes_large_cluster_per_node() { + let remote = "pve-large-pass"; + + let (tx, rx) = tokio::sync::mpsc::channel(10); + let handle = tokio::task::spawn(collecting_rrd_task(rx)); + + let mut config = SectionConfigData::default(); + config.insert(remote.to_string(), make_remote(remote)); + + let state_file = tempfile::NamedTempFile::new().unwrap(); + let state = MetricCollectionState::new(state_file.path().into(), get_create_options()); + + let (_control_tx, control_rx) = tokio::sync::mpsc::channel(10); + + let app = TestContextFactory().make_pdm_application().unwrap(); + + let mut task = RemoteMetricCollectionTask { + app, + state, + metric_data_tx: tx, + control_message_rx: control_rx, + }; + + // Act + task.fetch_remotes(&config, &[remote.to_string()]).await; + + // Assert + let status = task.state.get_status(remote).unwrap(); + assert!(status.error.is_none()); + assert!(NOW - status.most_recent_datapoint <= 10); + + drop(task); + let requests = handle.await.unwrap(); + + // All nodes are merged into a single request to the RRD task. + assert_eq!(requests.len(), 1); + let data = &requests[0].data; + + let nodes: HashSet<&str> = data.iter().map(|p| p.id.as_str()).collect(); + assert_eq!(nodes.len(), PER_NODE_FETCH_THRESHOLD + 2); + + // Every node was fetched exactly once, so there are no duplicate data points. + let mut seen = HashSet::new(); + assert!( + data.iter() + .all(|p| seen.insert((p.id.as_str(), p.timestamp))) + ); + + // The merged data is sorted by timestamp. + assert!(data.windows(2).all(|w| w[0].timestamp <= w[1].timestamp)); + } + + #[tokio::test] + async fn test_fetch_remotes_large_cluster_one_node_fails() { + let remote = "pve-large-partial"; + + let (tx, rx) = tokio::sync::mpsc::channel(10); + let handle = tokio::task::spawn(collecting_rrd_task(rx)); + + let mut config = SectionConfigData::default(); + config.insert(remote.to_string(), make_remote(remote)); + + let state_file = tempfile::NamedTempFile::new().unwrap(); + let state = MetricCollectionState::new(state_file.path().into(), get_create_options()); + + let (_control_tx, control_rx) = tokio::sync::mpsc::channel(10); + + let app = TestContextFactory().make_pdm_application().unwrap(); + + let mut task = RemoteMetricCollectionTask { + app, + state, + metric_data_tx: tx, + control_message_rx: control_rx, + }; + + // Act + task.fetch_remotes(&config, &[remote.to_string()]).await; + + // Assert + // A single failing node must not fail the whole remote. + let status = task.state.get_status(remote).unwrap(); + assert!(status.error.is_none()); + assert!(status.last_collection.is_some()); + + drop(task); + let requests = handle.await.unwrap(); + assert_eq!(requests.len(), 1); + + // Every node except the failing one delivered data. + let nodes: HashSet<&str> = requests[0].data.iter().map(|p| p.id.as_str()).collect(); + assert_eq!(nodes.len(), PER_NODE_FETCH_THRESHOLD + 1); + assert!(!nodes.contains("node/node-0")); + } + + #[tokio::test] + async fn test_fetch_remotes_large_cluster_all_nodes_fail() { + let remote = "pve-large-fail"; + + let (tx, rx) = tokio::sync::mpsc::channel(10); + let handle = tokio::task::spawn(collecting_rrd_task(rx)); + + let mut config = SectionConfigData::default(); + config.insert(remote.to_string(), make_remote(remote)); + + let state_file = tempfile::NamedTempFile::new().unwrap(); + let state = MetricCollectionState::new(state_file.path().into(), get_create_options()); + + let (_control_tx, control_rx) = tokio::sync::mpsc::channel(10); + + let app = TestContextFactory().make_pdm_application().unwrap(); + + let mut task = RemoteMetricCollectionTask { + app, + state, + metric_data_tx: tx, + control_message_rx: control_rx, + }; + + // Act + task.fetch_remotes(&config, &[remote.to_string()]).await; + + // Assert + // The actual node error is reported, not the generic fallback message. + let status = task.state.get_status(remote).unwrap(); + assert!( + status + .error + .as_ref() + .unwrap() + .contains("internal server error") + ); + assert_eq!(status.last_collection, None); + + drop(task); + assert!(handle.await.unwrap().is_empty()); + } + + #[tokio::test] + async fn test_fetch_remotes_large_cluster_without_node_list() { + let remote = "pve-large-old-pass"; + + let (tx, rx) = tokio::sync::mpsc::channel(10); + let handle = tokio::task::spawn(collecting_rrd_task(rx)); + + let mut config = SectionConfigData::default(); + config.insert(remote.to_string(), make_remote(remote)); + + let state_file = tempfile::NamedTempFile::new().unwrap(); + let state = MetricCollectionState::new(state_file.path().into(), get_create_options()); + + let (_control_tx, control_rx) = tokio::sync::mpsc::channel(10); + + let app = TestContextFactory().make_pdm_application().unwrap(); + + let mut task = RemoteMetricCollectionTask { + app, + state, + metric_data_tx: tx, + control_message_rx: control_rx, + }; + + // Act + task.fetch_remotes(&config, &[remote.to_string()]).await; + + // Assert + let status = task.state.get_status(remote).unwrap(); + assert!(status.error.is_none()); + + drop(task); + let requests = handle.await.unwrap(); + assert_eq!(requests.len(), 1); + + // The cluster-wide fallback returned the data of all nodes. + let nodes: HashSet<&str> = requests[0].data.iter().map(|p| p.id.as_str()).collect(); + assert_eq!(nodes.len(), PER_NODE_FETCH_THRESHOLD + 2); + } } -- 2.47.3