当无匹配值时将PromQL sum算子默认值设为0的方法
Fix PromQL Query for GKE Node Cost Calculation (Handle Missing Preemptible Nodes)
The Problem
You’re using this PromQL query to calculate GKE node costs, which works perfectly when your cluster has preemptible nodes:
sum( kube_node_status_capacity_cpu_cores * on(node) group_left(label_cloud_google_com_gke_nodepool) kube_node_labels{ label_cloud_google_com_gke_preemptible = "true" } ) * 5.10 + sum( kube_node_status_capacity_cpu_cores * on(node) group_left(label_cloud_google_com_gke_nodepool) kube_node_labels{ label_cloud_google_com_gke_preemptible = "" } ) * 16.95
But when there are no preemptible nodes in the cluster, the first sum() returns an empty result. PromQL can’t perform arithmetic with empty sets, so the entire query fails.
The Solution
Add the or vector(0) fallback to the first sum() clause to force it to return 0 instead of an empty result when no preemptible nodes exist. Here’s the adjusted query:
(sum( kube_node_status_capacity_cpu_cores * on(node) group_left(label_cloud_google_com_gke_nodepool) kube_node_labels{ label_cloud_google_com_gke_preemptible = "true" } ) or vector(0)) * 5.10 + sum( kube_node_status_capacity_cpu_cores * on(node) group_left(label_cloud_google_com_gke_nodepool) kube_node_labels{ label_cloud_google_com_gke_preemptible = "" } ) * 16.95
How It Works
- The
or vector(0)acts as a safety net: if the precedingsum()finds no matching preemptible nodes, it replaces the empty result with a single time series holding a value of 0. - This ensures the multiplication and addition operations run smoothly, even when your cluster has no preemptible nodes.
- The second
sum()for non-preemptible nodes will continue working as expected—every non-preemptible node has an empty string value for thelabel_cloud_google_com_gke_preemptiblelabel, so it will always return a valid sum unless your cluster has no nodes at all (a separate edge case).
内容的提问来源于stack exchange,提问作者Punit Agrawal
相关产品推荐
相关产品推荐

