public inbox for pdm-devel@lists.proxmox.com
 help / color / mirror / Atom feed
From: Jakob Klocker <j.klocker@proxmox.com>
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	[thread overview]
Message-ID: <20261126160707.333024-3-j.klocker@proxmox.com> (raw)
In-Reply-To: <20261126160707.333024-1-j.klocker@proxmox.com>

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 <j.klocker@proxmox.com>
---
 .../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<MetricCollectionState, Error> {
 
 #[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<String>,
+    }
+
+    impl TestPveClient {
+        /// Names of all nodes in the faked cluster.
+        fn node_names(&self) -> impl Iterator<Item = String> {
+            (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<Vec<ClusterNodeIndexResponse>, 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<bool>,
             _local_only: Option<bool>,
-            _node_list: Option<String>,
+            node_list: Option<String>,
             start_time: Option<i64>,
         ) -> Result<ClusterMetrics, proxmox_client::Error> {
-            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<String> = 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<Remote> {
         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<RrdStoreRequest>) -> Vec<ClusterMetrics> {
+        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





  parent reply	other threads:[~2026-11-26 16:09 UTC|newest]

Thread overview: 6+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-26 16:07 [PATCH proxmox-datacenter-manager 0/2] fix #7731: metric collection: fetch large PVE clusters node by node Jakob Klocker
2026-11-26 16:07 ` [PATCH proxmox-datacenter-manager 1/2] " Jakob Klocker
2026-11-27  9:54   ` Lukas Wagner
2026-11-26 16:07 ` Jakob Klocker [this message]
2026-11-27  9:46   ` [PATCH proxmox-datacenter-manager 2/2] metric collection: add tests for fetching " Lukas Wagner
2026-11-27 14:05 ` superseded: [PATCH proxmox-datacenter-manager 0/2] fix #7731: metric collection: fetch large " Jakob Klocker

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261126160707.333024-3-j.klocker@proxmox.com \
    --to=j.klocker@proxmox.com \
    --cc=pdm-devel@lists.proxmox.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal