有没有办法使用 aws-sdk(节点)获取 S3 使用统计信息(如 space 已使用)?

Is there a way to get S3 usage statistics (like space utilized) using aws-sdk (node)?

我正在尝试以编程方式获取我在 S3 存储桶上使用的总大小。

我研究了与 S3 存储桶交互的 AWS-SDK 方法,但其中 none 允许我们获取 space 利用率统计信息。我不确定是否可以使用 cloudwatch API 函数来实现此目的。

编辑:尝试使用 John 的指导转化为我正在使用的节点 sdk:

var params = {
    EndTime: new Date(), /* required */
    MetricName: 'BucketSizeBytes', /* required */
    Namespace: 'AWS/S3', /* required */
    Period: 3600, /* required */
    StartTime: '2019-06-07T00:00:00Z', /* required */
    Dimensions: [
        {
            Name: 'BucketName', /* required */
            Value: config.s3BucketName /* required */
        },
        {
            Name: 'StorageType',
            Value: 'StandardStorage '
        }
    ],
    Statistics: [
        'Average'
    ],
    Unit: 'Bytes'
};
cloudwatch.getMetricStatistics(params, function (err, data) {
    if (err) console.log(err, err.stack); // an error occurred
    else console.log(data);           // successful response
});

但我每次在 return 中得到的都是一个空白的 Datapoints 数组。尝试更改日期和期间,但没有成功。

{ResponseMetadata: { RequestId: 'xxxx-xxxx-xxxx-xxxx-xxxx' },  Label: 'BucketSizeBytes',  Datapoints: []}

您可以从 Amazon CloudWatch 中检索每个存储桶的大小。

来自Monitoring Metrics with Amazon CloudWatch - Amazon S3

Metric: BucketSizeBytes

The amount of data in bytes stored in a bucket. This value is calculated by summing the size of all objects in the bucket (both current and noncurrent objects), including the size of all parts for all incomplete multipart uploads to the bucket.

因此,只需从 Amazon CloudWatch 检索指标,而不是自己计算。

下面是 AWS Command-Line Interface (CLI) 命令中的等效命令,您可以将其转换为您喜欢的 SDK:

aws cloudwatch get-metric-statistics 
--namespace AWS/S3 
--metric-name BucketSizeBytes 
--dimensions Name=BucketName,Value=my-bucket Name=StorageType,Value=StandardStorage 
--start-time 2019-06-05T00:00:00Z 
--end-time 2019-06-05T01:00:00Z 
--period 3600 
--statistics Average

结果:

{
    "Label": "BucketSizeBytes",
    "Datapoints": [
        {
            "Timestamp": "2019-06-05T00:00:00Z",
            "Average": 17582395.0,
            "Unit": "Bytes"
        }
    ]
}

请注意,根据存储类型,存在三个维度。以上只显示StandardStorage.

要查看可用的维度,请使用:

aws cloudwatch list-metrics --namespace AWS/S3

如果您遇到空 data-points 问题,请确保您的日期 ISO 字符串已初始化为午夜。这是我的 Node SDK 解决方案,用于获取以 MB 为单位的总存储桶大小:

function totalDataUsage() {
return new Promise((resolve, reject) => {
    let today = new Date();
    let yesterday = new Date();
    yesterday.setDate(today.getDate() -1)

    yesterday.setHours(0,0,0,0);
    today.setHours(0,0,0,0);

    startTime = yesterday.toISOString();
    endTime = today.toISOString();

    let params = {
        EndTime: endTime,
        MetricName: 'BucketSizeBytes',
        Namespace: 'AWS/S3',
        Period: 3600,
        StartTime: startTime,
        Dimensions: [
            {
                Name: 'StorageType',
                Value: 'StandardStorage'
            },
            {
                Name: 'BucketName',
                Value: 'your-bucket-name-here'
            }
        ],
        Statistics: ['Average'],
        Unit: 'Bytes'
    };

    cloudwatch.getMetricStatistics(params, function(err, data) {
        if(err) {
            reject(err);
        } else {
            resolve((data.Datapoints[0].Average / 1000000).toFixed(1));
        }
    });
});

totalDataUsage().then(totalSizeMB => {
    console.log(totalSizeMB);
}).catch(error => {
    console.log(error);
});