繁体   English   中英

如何使用节点读取 aws cpu 使用情况?

[英]how to read aws cpu usage using node?

我想构建一个小应用程序,每 5 分钟读取一次 AWS CPU 使用情况,可以说,我构建了参数,调用 getMetricsStatistics 但它一直返回一个空数组,你知道为什么吗? 这是代码:

const aws = require('aws-sdk')
const dotenv = require('dotenv').config()

aws.config.setPromisesDependency()
aws.config.update({
  accessKeyId: process.env.EC2_ACCESS_KEY,
  secretAccessKey: process.env.EC2_SECRET_KEY,
  region: 'us-east-1',
})
const s3 = new aws.CloudWatch()

var params = {
  EndTime: new Date() /* required */,
  /* required */
  MetricName: 'EngineCPUUtilization',
  Namespace: 'AWS/S3',
  StartTime: new Date('Mon Dec 6 2021') /* required */,
  /* required */
  Dimensions: [
    {
      Name: 'Per-Instance Metrics' /* required */,
      Value: 'i-abbc12a7' /* required */,
    },
    {
      Name: 'StorageType',
      Value: 'AllStorageTypes',
    },
    /* more items */
  ],

  Period: 300 /* required */,
  Statistics: ['Average'] /* required */,
}
async function asyncMethod() {
  return await s3.getMetricStatistics(params, function (err, data) {
    if (err) console.log(err, err.stack)
    // an error occurred
    else {
      console.log(data)
    }
  }) // successful response
}

const d = asyncMethod()

响应始终是 data.Datapoints 中的空数组。

PS,如何获取所有存储桶的名称? 谢谢!

第一个问题是您正在调用异步方法“asyncMethod”,而您没有等待它完成(解决承诺)。 您的 asnycMethod 也有些多余且过于复杂。 我将删除所有这些并将其更改为 1) 使用 SDK 调用的 the.promise() 形式,以及 2) 使用 thenable promise 方法,这对于您要执行的操作更简单:

 return s3.getMetricStatistics(params).promise().then(d => { console.log(data) /* do stuff with d here */ }).catch(err => { console.log(err); });

此外,您不能像尝试那样将 d 设置为结果,因为 promise 将作为 d 返回,而不是回调数据值的结果。 您也不能对 asyncMethod 调用执行等待,因为您不在异步 function 中。 此外,您实际上并没有从回调中返回值。

也就是说,我认为您对 AWS SDK 进行的一般调用没有任何特别的问题,但我会检查您发送的尺寸以获得准确的设置。 我假设您确定您要查找的统计数据在指定的时间段内确实存在。

希望有帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM