all lists on 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 1/2] fix #7731: metric collection: fetch large PVE clusters node by node
Date: Thu, 26 Nov 2026 17:07:06 +0100	[thread overview]
Message-ID: <20261126160707.333024-2-j.klocker@proxmox.com> (raw)
In-Reply-To: <20261126160707.333024-1-j.klocker@proxmox.com>

On larger clusters, a single cluster-wide /cluster/metrics/export
request can take longer than pveproxy's 30 second request timeout, as
the node handling it fetches the metrics of all other cluster members
one after another. The reporter [0] measured ~2m40s for a 25-node
cluster, so no metrics were collected for such clusters at all.

For clusters with at least 3 nodes, request the metrics of each node
separately via the `node-list` parameter and merge the results. At
~6.5 seconds per node with the full metric history, even a few nodes
can exceed the timeout. PVE versions without `node-list` reject the
parameter, so the cluster-wide request is used for those instead.

Fetching the nodes in parallel through one cluster node turned out to
be unreliable. The export endpoint fetches the metrics of the requested
node with a blocking HTTP request (timeout 20s), so a node whose API
does not answer freezes the pveproxy worker handling that request for
20 seconds. A worker handles its connections one at a time, and
parallel requests often end up on the same worker. pveproxy's 5 second
inactivity timeout expires during the freeze, so the other connections
on that worker are closed: responses are cut off or requests dropped.
On a 5-node test cluster with one node's API unreachable, this lost the
metrics of a healthy node in most runs.

As metric collection runs in the background and has to be reliable
rather than fast, fetch the nodes one after another, so no request can
wait behind a blocked worker. Parallel fetching would become safe if
each node were queried directly at its own endpoint.

[0] https://bugzilla.proxmox.com/show_bug.cgi?id=7731

Signed-off-by: Jakob Klocker <j.klocker@proxmox.com>
---
 .../remote_collection_task.rs                 | 104 ++++++++++++++++--
 1 file changed, 95 insertions(+), 9 deletions(-)

diff --git a/server/src/metric_collection/remote_collection_task.rs b/server/src/metric_collection/remote_collection_task.rs
index 1e0011cb..9c3f8522 100644
--- a/server/src/metric_collection/remote_collection_task.rs
+++ b/server/src/metric_collection/remote_collection_task.rs
@@ -3,7 +3,8 @@ use std::{
     time::{Duration, Instant},
 };
 
-use anyhow::Error;
+use anyhow::{Error, format_err};
+use http::StatusCode;
 use tokio::{
     sync::{
         OwnedSemaphorePermit, Semaphore,
@@ -18,7 +19,9 @@ use proxmox_section_config::typed::SectionConfigData;
 use proxmox_sys::fs::CreateOptions;
 
 use pdm_api_types::remotes::{Remote, RemoteType};
+use pve_api_types::{ClusterMetrics, ClusterNodeIndexResponse};
 
+use crate::connection::PveClient;
 use crate::context::PdmApplication;
 use crate::metric_collection::rrd_task::CollectionStats;
 use crate::task_utils;
@@ -34,6 +37,9 @@ const METRIC_COLLECTION_STATE_FILE: &str = concat!(
     "/metric-collection-state.json"
 );
 
+/// PVE clusters with at least this many nodes are fetched node by node.
+const PER_NODE_FETCH_THRESHOLD: usize = 3;
+
 pub const MAX_CONCURRENT_CONNECTIONS: usize = 20;
 
 /// Default metric collection interval.
@@ -316,14 +322,17 @@ impl RemoteMetricCollectionTask {
             match remote.ty {
                 RemoteType::Pve => {
                     let client = app.client_factory().make_pve_client(&remote)?;
-                    let metrics = client
-                        .cluster_metrics_export(
-                            Some(true),
-                            Some(false),
-                            None,
-                            Some(status.most_recent_datapoint),
-                        )
-                        .await?;
+                    let start_time = status.most_recent_datapoint;
+                    let nodes = client.list_nodes().await?;
+
+                    let metrics = if nodes.len() >= PER_NODE_FETCH_THRESHOLD {
+                        Self::fetch_nodes_one_by_one(client.as_ref(), &remote, &nodes, start_time)
+                            .await?
+                    } else {
+                        client
+                            .cluster_metrics_export(Some(true), Some(false), None, Some(start_time))
+                            .await?
+                    };
 
                     let duration = start.elapsed();
 
@@ -377,6 +386,68 @@ impl RemoteMetricCollectionTask {
 
         (remote.id, status)
     }
+
+    /// Fetch the metrics of every node of a PVE remote with a separate request and
+    /// merge the results. The nodes are fetched one after another on purpose, as
+    /// parallel requests can block each other on the endpoint.
+    async fn fetch_nodes_one_by_one(
+        client: &PveClient,
+        remote: &Remote,
+        nodes: &[ClusterNodeIndexResponse],
+        start_time: i64,
+    ) -> Result<ClusterMetrics, Error> {
+        let mut data = Vec::new();
+        let mut succeeded = 0;
+        let mut last_error: Option<Error> = None;
+
+        for node in nodes {
+            match client
+                .cluster_metrics_export(
+                    Some(true),
+                    Some(false),
+                    Some(node.node.clone()),
+                    Some(start_time),
+                )
+                .await
+            {
+                Ok(metrics) => {
+                    succeeded += 1;
+                    data.extend(metrics.data);
+                }
+                // PVE versions without `node-list` reject it during parameter
+                // verification, use a single cluster-wide request for those.
+                Err(proxmox_client::Error::Api(StatusCode::BAD_REQUEST, msg))
+                    if msg.contains("node-list") =>
+                {
+                    log::debug!(
+                        "remote '{}' does not support 'node-list', falling back to a cluster-wide request",
+                        remote.id
+                    );
+                    return Ok(client
+                        .cluster_metrics_export(Some(true), Some(false), None, Some(start_time))
+                        .await?);
+                }
+                Err(err) => {
+                    log::warn!(
+                        "could not fetch metrics of node '{}' from '{}': {err}",
+                        node.node,
+                        remote.id
+                    );
+                    last_error = Some(err.into());
+                }
+            }
+        }
+
+        // every node failed: report a real error instead of storing nothing as success
+        if succeeded == 0 {
+            return Err(
+                last_error.unwrap_or_else(|| format_err!("remote '{}' has no nodes", remote.id))
+            );
+        }
+
+        data.sort_by_key(|metric| metric.timestamp);
+        Ok(ClusterMetrics { data })
+    }
 }
 
 /// Load the metric collection state file.
@@ -468,6 +539,21 @@ pub(super) mod tests {
 
     #[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| {
+                    serde_json::from_value(serde_json::json!({
+                        "node": format!("node-{i}"),
+                        "status": "online",
+                    }))
+                    .unwrap()
+                })
+                .collect())
+        }
+
         /// Retrieve metrics of the cluster.
         async fn cluster_metrics_export(
             &self,
-- 
2.47.3





  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 ` Jakob Klocker [this message]
2026-11-27  9:54   ` [PATCH proxmox-datacenter-manager 1/2] " Lukas Wagner
2026-11-26 16:07 ` [PATCH proxmox-datacenter-manager 2/2] metric collection: add tests for fetching " Jakob Klocker
2026-11-27  9:46   ` 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-2-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 an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal