Add State filter in monitoring client library for node js in GCP

23 Views Asked by At

I am trying to Fetch the timeseries data and I am using @google/monitoring package for node js to connect with gcp monitoring api and fetch the data. I am able to fetch the data for CPU utilisation but when comes to memory/Ram utilisation, As per MQL query I need to add metric.state==used in filter type but as soon as I add that thing in metric it says 'The comparison operand: 'state' cannot be used with the prefix 'metric'.

const { MetricServiceClient } = require('@google-cloud/monitoring');

exports.getInstanceRamUtilization = async(instanceid) => {
  const projectId = process.env.PROJECT_ID; 
  const client = new MetricServiceClient();

  try {
    // Fetch Memory utilization metrics for instance
    const [timeSeries] = await client.listTimeSeries({
    name: `projects/${projectId}`,
    filter: `resource.type="gce_instance" AND resource.labels.instance_id="${instanceid}" AND metric.type="agent.googleapis.com/memory/percent_used" AND metric.type="used"`,
    interval: {
      startTime: {
        seconds: Date.now() / 1000 - 60 * 60 * 3, // Fetch data for the last 3 hours
      },
      endTime: {
        seconds: Date.now() / 1000,
      },
    },
    });

    console.log(timeSeries);
    const instanceMetrics = timeSeries.map(series => ({
      metric: series.metric.type,
      values: series.points.map(point => ({
        timestamp: new Date(point.interval.startTime.seconds * 1000),
        value: point.value.doubleValue, // Assuming RAM utilization is a percentage
      })),
      current_value: series.points[0].value.doubleValue,
      instance: instanceid,
    }));

    return instanceMetrics;

  } catch (error) {
    console.error('Error retrieving memory of instance:', error);
    throw new Error('Failed to retrieve MEMORY Utilisation'); // Throw a custom error or rethrow the original error
  }
};

1

There are 1 best solutions below

0
Ron Etch On

Using the GCP Metrics explorer, the following MQL can be used to create chart for the memory utilization:

fetch gce_instance 
| metric 'agent.googleapis.com/memory/percent_used' 
| filter (resource.instance_id == '1234567890') 
| filter (resource.zone == 'us-central1-a') 
| filter (metric.state == 'used') 
| group_by 2m, [value_percent_used_mean: mean(value.percent_used)] 
| every 2m

On your filter, you can try to use "| metric.state == 'used" or use the whole MQL query depending on your requirements.