Search code examples
node.jskubernetesgoogle-kubernetes-enginemetrics

How to get usage metrics for Kubernetes pods on GKE from external node.js script


I need to get the usage metrics (CPU and RAM) for my Kubernetes pods, but since other components of my app use this data, I need to query for it through Node.js rather than use the Metrics explorer dropdown on the GCP console to just see the data visualized in a chart. I have tried the API at https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/query which seems most like what I'm looking for. However, after testing on my project, I got an empty response, even though the same query in the Metrics Explorer displayed data on the charts. If anyone has tips on how to use this API properly, I'd appreciate it.


Solution

  • I have reproduced your use-case and successfully executed the query and got the Cumulative amount of consumed CPU time on all cores in nanoseconds with 200 OK response.

    1. After creating the GKE Cluster, navigate to metrics explorer and select the metric, metric.type="kubernetes.io/container/cpu/core_usage_time" and you can see the data in the chart for the cluster. Now click the "MQL" button to get the same query in MQL syntax.

    2. Now to get the same data by calling the projects.timeSeries.query, try in the “Try this API” box in API Explorer by entering the project's ID using the format projects/[PROJECT_ID] in the name parameter. Make sure to replace [PROJECT_ID] with your project's ID.

    3. In the request body add the query as
      "query": "fetch k8s_container::kubernetes.io/container/cpu/core_usage_time| within 5m"

    Syntax for Request Body:

    {

     "query": "fetch k8s_container::kubernetes.io/container/cpu/core_usage_time| within 5m"
      
    

    }

    Now, click on the Execute button to get the Cumulative amount of consumed CPU time on all cores with 200 OK response.

    Refer to the link for more information on retrieving data with timeseries.query.