Default sum operator to 0 when values dont exist

5/18/2018

I am using the following query to calculate the cost of nodes in our GKE cluster (new lines added for readability)

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

It WORKS if the cluster has preemptible nodes because there is at least one node with label_cloud_google_com_gke_preemptible = "true" and hence the first sum operator returns a value.

It FAILS when the cluster has NO preemtible nodes because there is no node with label_cloud_google_com_gke_preemptible = "true" and hence the first sum returns no value

Is it possible to modify the query so that the first sum returns a 0 value instead?

-- Punit Agrawal
google-kubernetes-engine
prometheus
promql

1 Answer

5/19/2018

You can use or to insert a value if one is not present:

  (
      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 
    or
      vector(0)
  )
+ 
  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
-- brian-brazil
Source: StackOverflow