* [PATCH proxmox-datacenter-manager 1/2] fix #7731: metric collection: fetch large PVE clusters node by node
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
2026-11-27 9:54 ` Lukas Wagner
2026-11-26 16:07 ` [PATCH proxmox-datacenter-manager 2/2] metric collection: add tests for fetching " Jakob Klocker
2026-11-27 14:05 ` superseded: [PATCH proxmox-datacenter-manager 0/2] fix #7731: metric collection: fetch large " Jakob Klocker
2 siblings, 1 reply; 6+ messages in thread
From: Jakob Klocker @ 2026-11-26 16:07 UTC (permalink / raw)
To: pdm-devel
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
^ permalink raw reply related [flat|nested] 6+ messages in thread* [PATCH proxmox-datacenter-manager 2/2] metric collection: add tests for fetching PVE clusters node by node
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-26 16:07 ` 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
2 siblings, 1 reply; 6+ messages in thread
From: Jakob Klocker @ 2026-11-26 16:07 UTC (permalink / raw)
To: pdm-devel
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
^ permalink raw reply related [flat|nested] 6+ messages in thread