
# 查询监控数据 - ShowMetricsData
#### 功能介绍
该接口用于查询指定时间范围内指标的监控数据，可以通过参数指定需要查询的数据维度，数据周期等。（该接口已不再演进，建议使用 [（推荐）POST方法查询区间数据](https://support.huaweicloud.com/api-aom/ListRangeQueryAomPromPost.html)接口。）
#### 调用方法
请参见[如何调用API](https://support.huaweicloud.com/api-aom/aom_04_0057.html)。
#### 授权信息
账号具备所有API的调用权限，如果使用账号下的IAM用户调用当前API，该IAM用户需具备调用API所需的权限。
- 如果使用角色与策略授权，具体权限要求请参见[权限和授权项](https://support.huaweicloud.com/api-aom/aom_04_0031.html)。
- 如果使用身份策略授权，需具备如下身份策略权限。
  
  | 授权项             | 访问级别 | 资源类型（\*为必须） | 条件键 | 别名             | 依赖的授权项 |
  |:---|:---|:---|:---|:---|:---|
  | aom:metric:list | List | -           | -   | aom:metric:get | -      |
     
  
 
#### URI
POST /v1/{project_id}/ams/metricdata
表1路径参数 
| 参数         | 是否必选 | 参数类型   | 描述                                                                                                     |
|:---|:---|:---|:---|
| project_id | 是    | String | 项目ID，可以从控制台获取，也可以从调用API处获取。获取方式请参见：[获取项目ID](https://support.huaweicloud.com/api-aom/aom_04_0024.html)。 |
   
表2Query参数 
| 参数        | 是否必选 | 参数类型   | 描述                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
|:---|:---|:---|:---|
| fillValue | 否    | String | 用于对查询到的监控数据进行断点插值，默认值为-1。 - -1：断点处使用-1进行表示。   - 0 ：断点处使用0进行表示。   - null：断点处使用null进行表示。   - average：断点处使用前后邻近的有效数据的平均值进行表示，如果不存在有效数据则使用null进行表示。    |
   
#### 请求参数
表3请求Header参数 
| 参数           | 是否必选 | 参数类型   | 描述                                                                                            |
|:---|:---|:---|:---|
| X-Auth-Token | 是    | String | 从IAM服务获取的用户Token。获取方式请参见：[获取Token](https://support.huaweicloud.com/api-aom/aom_04_0059.html)。 |
| Content-Type | 是    | String | 消息体的类型（格式）。指定类型为"application/json"。                                                           |
   
表4请求Body参数 
| 参数         | 是否必选 | 参数类型                                                                                        | 描述                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
|:---|:---|:---|:---|
| metrics    | 是    | Array of [MetricQueryMetricParam] objects | 指标对象列表。 取值范围 JSON数组大小不超过20                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| period     | 是    | Integer                                                                                     | 监控数据粒度。取值范围（枚举）： - 60：表示粒度为1分钟。   - 300：表示粒度为5分钟。   - 900：表示粒度为15分钟。   - 3600：表示粒度为1小时。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| statistics | 是    | Array of strings                                                                            | 统计方式。 取值范围 maximum，minimum，sum，average，sampleCount                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| timerange  | 是    | String                                                                                      | 查询时间范围，主要用于解决客户端时间和服务端时间不一致情况下，查询最近N分钟的数据。另可用于精确查询某一段时间的数据。 例如： - -1.-1.60(表示最近60分钟)，不管当前客户端是什么时间，都以服务端时间为准查询最近60分钟。   - 1650852000000.1650852300000.5(表示GMT+8 2022-04-25 10:00:00至2022-04-25    10:05:00指定的5分钟) 格式如下： startTimeInMillis.endTimeInMillis.durationInMinutes 参数解释： - startTimeInMillis: 查询的开始时间，格式为UTC毫秒，如果指定为-1，服务端将按(endTimeInMillis - durationInMinutes \* 60 \* 1000)计算开始时间。例如-1.1650852300000.5，则相当于1650852000000.1650852300000.5。   - endTimeInMillis: 查询的结束时间，格式为UTC毫秒，如果指定为-1，服务端将按(startTimeInMillis + durationInMinutes \* 60 \* 1000)计算结束时间。如果计算出的结束时间大于当前系统时间,则使用当前系统时间。例如1650852000000.-1.5，则相当于1650852000000.1650852300000.5。   - durationInMinutes：查询时间的跨度分钟数。 取值范围大于0并且大于等于(endTimeInMillis - startTimeInMillis) / (60 \* 1000) - 1。当开始时间与结束时间都设置为-1时，系统会将结束时间设置为当前时间UTC毫秒值，并按(endTimeInMillis - durationInMinutes \* 60 \* 1000)计算开始时间。如：-1.-1.60(表示最近60分钟)。    约束与限制： 单次请求中，查询时长与周期需要满足以下条件: durationInMinutes \* 60 / period \<= 1440。 |
   
 表5MetricQueryMetricParam 
| 参数         | 是否必选 | 参数类型                                                              | 描述                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
|:---|:---|:---|:---|
| dimensions | 是    | Array of [Dimension] objects | 时间序列维度列表。可通过调用[查询时间序列](https://support.huaweicloud.com/api-aom/ListSeries.html)接口，查询当前监控的时间序列名称的时间序列维度列表。取值范围：数组不能为空，同时数组中任何一个dimension对象name和value属性的值也不能为空。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| metricName | 是    | String                                                            | 指标名称。名称长度取值范围为1\~255个字符。取值范围：AOM提供的基础指标，cpuUsage、cpuCoreUsed等，或用户上报的自定义指标名称。通过 [查询标签值](https://support.huaweicloud.com/api-aom/ListLabelValuesAomPromGet.html)查询所有指标                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| namespace  | 是    | String                                                            | 指标命名空间。取值范围： - PAAS.CONTAINER：组件指标、实例指标、进程指标和容器指标的命名空间，   - PAAS.NODE： 主机指标、网络指标、磁盘指标和文件系统指标的命名空间，   - PAAS.SLA：SLA指标的命名空间，   - PAAS.AGGR：集群指标的命名空间，   - CUSTOMMETRICS：默认的自定义指标的命名空间。    或用户自定义命名空间，通过 [查询标签值](https://support.huaweicloud.com/api-aom/ListLabelValuesAomPromGet.html)查询所有命名空间的值 |
   
 表6Dimension 
| 参数    | 是否必选 | 参数类型   | 描述    |
|:---|:---|:---|:---|
| name  | 是    | String | 维度名称。 |
| value | 是    | String | 维度取值。 |
   
#### 响应参数
**状态码：200**
表7响应Body参数 
| 参数           | 参数类型                                                                           | 描述      |
|:---|:---|:---|
| errorCode    | String                                                                         | 响应码。    |
| errorMessage | String                                                                         | 响应信息描述。 |
| metrics      | Array of [MetricDataValue] objects | 指标对象列表。 |
   
 表8MetricDataValue 
| 参数         | 参数类型                                                                               | 描述     |
|:---|:---|:---|
| dataPoints | Array of [MetricDataPoints] objects   | 重点指标。  |
| metric     | [MetricQueryMetricParam] object | 查询参数集。 |
   
 表9MetricDataPoints 
| 参数         | 参数类型                                                                         | 描述      |
|:---|:---|:---|
| statistics | Array of [StatisticValue] objects | 统计方式。   |
| timestamp  | Long                                                                         | 时间戳。    |
| unit       | String                                                                       | 时间序列单位。 |
   
 表10StatisticValue 
| 参数        | 参数类型   | 描述    |
|:---|:---|:---|
| statistic | String | 统计方式。 |
| value     | Double | 统计结果。 |
   
 表11MetricQueryMetricParam 
| 参数         | 参数类型                                                               | 描述                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
|:---|:---|:---|
| dimensions | Array of [Dimension] objects | 时间序列维度列表。可通过调用[查询时间序列](https://support.huaweicloud.com/api-aom/ListSeries.html)接口，查询当前监控的时间序列名称的时间序列维度列表。取值范围：数组不能为空，同时数组中任何一个dimension对象name和value属性的值也不能为空。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| metricName | String                                                             | 指标名称。名称长度取值范围为1\~255个字符。取值范围：AOM提供的基础指标，cpuUsage、cpuCoreUsed等，或用户上报的自定义指标名称。通过 [查询标签值](https://support.huaweicloud.com/api-aom/ListLabelValuesAomPromGet.html)查询所有指标                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| namespace  | String                                                             | 指标命名空间。取值范围： - PAAS.CONTAINER：组件指标、实例指标、进程指标和容器指标的命名空间，   - PAAS.NODE： 主机指标、网络指标、磁盘指标和文件系统指标的命名空间，   - PAAS.SLA：SLA指标的命名空间，   - PAAS.AGGR：集群指标的命名空间，   - CUSTOMMETRICS：默认的自定义指标的命名空间。    或用户自定义命名空间，通过 [查询标签值](https://support.huaweicloud.com/api-aom/ListLabelValuesAomPromGet.html)查询所有命名空间的值 |
   
 表12Dimension 
| 参数    | 参数类型   | 描述    |
|:---|:---|:---|
| name  | String | 维度名称。 |
| value | String | 维度取值。 |
   
#### 请求示例
查询指标名称"cpuUsage"且所属命名空间为"PAAS.CONTAINER"的指标在最近5分钟的监控数据。
```
https://{Endpoint}/v1/{project_id}/ams/metricdata
{
  "metrics" : [ {
    "dimensions" : [ {
      "name" : "appName",
      "value" : "aomApp"
    } ],
    "metricName" : "cpuUsage",
    "namespace" : "PAAS.CONTAINER"
  } ],
  "period" : 60,
  "statistics" : [ "maximum", "minimum", "sum" ],
  "timerange" : "-1.-1.5"
}
```
#### 响应示例
**状态码：200**
OK 请求执行完成。
```
{
  "errorCode" : "SVCSTG_AMS_2000000",
  "errorMessage" : "success",
  "metrics" : [ {
    "metric" : {
      "namespace" : "PAAS.CONTAINER",
      "metricName" : "cpuUsage",
      "dimensions" : [ {
        "name" : "appName",
        "value" : "aomApp"
      } ]
    },
    "dataPoints" : [ {
      "timestamp" : 1467892800000,
      "unit" : "Percent",
      "statistics" : [ {
        "statistic" : "maximum",
        "value" : 23
      } ]
    } ]
  } ]
}
```
#### SDK代码示例
SDK代码示例如下。
- [Java]
  查询指标名称"cpuUsage"且所属命名空间为"PAAS.CONTAINER"的指标在最近5分钟的监控数据。
  ```
  package com.huaweicloud.sdk.test;
  import com.huaweicloud.sdk.core.auth.ICredential;
  import com.huaweicloud.sdk.core.auth.BasicCredentials;
  import com.huaweicloud.sdk.core.exception.ConnectionException;
  import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
  import com.huaweicloud.sdk.core.exception.ServiceResponseException;
  import com.huaweicloud.sdk.aom.v2.region.AomRegion;
  import com.huaweicloud.sdk.aom.v2.*;
  import com.huaweicloud.sdk.aom.v2.model.*;
  import java.util.List;
  import java.util.ArrayList;
  public class ShowMetricsDataSolution {
      public static void main(String[] args) {
          // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
          // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
          String ak = System.getenv("CLOUD_SDK_AK");
          String sk = System.getenv("CLOUD_SDK_SK");
          String projectId = "{project_id}";
          ICredential auth = new BasicCredentials()
                  .withProjectId(projectId)
                  .withAk(ak)
                  .withSk(sk);
          AomClient client = AomClient.newBuilder()
                  .withCredential(auth)
                  .withRegion(AomRegion.valueOf("<YOUR REGION>"))
                  .build();
          ShowMetricsDataRequest request = new ShowMetricsDataRequest();
          QueryMetricDataParam body = new QueryMetricDataParam();
          List<String> listbodyStatistics = new ArrayList<>();
          listbodyStatistics.add("maximum");
          listbodyStatistics.add("minimum");
          listbodyStatistics.add("sum");
          List<Dimension> listMetricsDimensions = new ArrayList<>();
          listMetricsDimensions.add(
              new Dimension()
                  .withName("appName")
                  .withValue("aomApp")
          );
          List<MetricQueryMetricParam> listbodyMetrics = new ArrayList<>();
          listbodyMetrics.add(
              new MetricQueryMetricParam()
                  .withDimensions(listMetricsDimensions)
                  .withMetricName("cpuUsage")
                  .withNamespace("PAAS.CONTAINER")
          );
          body.withTimerange("-1.-1.5");
          body.withStatistics(listbodyStatistics);
          body.withPeriod(60);
          body.withMetrics(listbodyMetrics);
          request.withBody(body);
          try {
              ShowMetricsDataResponse response = client.showMetricsData(request);
              System.out.println(response.toString());
          } catch (ConnectionException e) {
              e.printStackTrace();
          } catch (RequestTimeoutException e) {
              e.printStackTrace();
          } catch (ServiceResponseException e) {
              e.printStackTrace();
              System.out.println(e.getHttpStatusCode());
              System.out.println(e.getRequestId());
              System.out.println(e.getErrorCode());
              System.out.println(e.getErrorMsg());
          }
      }
  }
  ```
- [Python]
  查询指标名称"cpuUsage"且所属命名空间为"PAAS.CONTAINER"的指标在最近5分钟的监控数据。
  ```
  # coding: utf-8
  import os
  from huaweicloudsdkcore.auth.credentials import BasicCredentials
  from huaweicloudsdkaom.v2.region.aom_region import AomRegion
  from huaweicloudsdkcore.exceptions import exceptions
  from huaweicloudsdkaom.v2 import *
  if __name__ == "__main__":
      # The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
      # In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
      ak = os.environ["CLOUD_SDK_AK"]
      sk = os.environ["CLOUD_SDK_SK"]
      projectId = "{project_id}"
      credentials = BasicCredentials(ak, sk, projectId)
      client = AomClient.new_builder() \
          .with_credentials(credentials) \
          .with_region(AomRegion.value_of("<YOUR REGION>")) \
          .build()
      try:
          request = ShowMetricsDataRequest()
          listStatisticsbody = [
              "maximum",
              "minimum",
              "sum"
          ]
          listDimensionsMetrics = [
              Dimension(
                  name="appName",
                  value="aomApp"
              )
          ]
          listMetricsbody = [
              MetricQueryMetricParam(
                  dimensions=listDimensionsMetrics,
                  metric_name="cpuUsage",
                  namespace="PAAS.CONTAINER"
              )
          ]
          request.body = QueryMetricDataParam(
              timerange="-1.-1.5",
              statistics=listStatisticsbody,
              period=60,
              metrics=listMetricsbody
          )
          response = client.show_metrics_data(request)
          print(response)
      except exceptions.ClientRequestException as e:
          print(e.status_code)
          print(e.request_id)
          print(e.error_code)
          print(e.error_msg)
  ```
- [Go]
  查询指标名称"cpuUsage"且所属命名空间为"PAAS.CONTAINER"的指标在最近5分钟的监控数据。
  ```
  package main
  import (
  "fmt"
  "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
      aom "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/aom/v2"
  "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/aom/v2/model"
      region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/aom/v2/region"
  )
  func main() {
      // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
      // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
      ak := os.Getenv("CLOUD_SDK_AK")
      sk := os.Getenv("CLOUD_SDK_SK")
      projectId := "{project_id}"
      auth, err := basic.NewCredentialsBuilder().
          WithAk(ak).
          WithSk(sk).
          WithProjectId(projectId).
          SafeBuild()
      if err != nil {
          fmt.Println(err)
          return
      }
      hcClient, err := aom.AomClientBuilder().
           WithRegion(region.ValueOf("<YOUR REGION>")).
           WithCredential(auth).
           SafeBuild()
      if err != nil {
          fmt.Println(err)
          return
      }
      client := aom.NewAomClient(hcClient)
      request := &model.ShowMetricsDataRequest{}
  var listStatisticsbody = []string{
          "maximum",
      "minimum",
      "sum",
      }
  var listDimensionsMetrics = []model.Dimension{
          {
              Name: "appName",
              Value: "aomApp",
          },
      }
  var listMetricsbody = []model.MetricQueryMetricParam{
          {
              Dimensions: listDimensionsMetrics,
              MetricName: "cpuUsage",
              Namespace: "PAAS.CONTAINER",
          },
      }
  request.Body = &model.QueryMetricDataParam{
  Timerange: "-1.-1.5",
  Statistics: listStatisticsbody,
  Period: int32(60),
  Metrics: listMetricsbody,
  }
  response, err := client.ShowMetricsData(request)
  if err == nil {
          fmt.Printf("%+v\n", response)
      } else {
          fmt.Println(err)
      }
  }
  ```
- [更多]
  更多编程语言的SDK代码示例，请参见[API Explorer](https://console.huaweicloud.com/apiexplorer/#/openapi/AOM/sdk?api=ShowMetricsData)的代码示例页签，可生成自动对应的SDK代码示例。
#### 状态码
| 状态码 | 描述                                                                                            |
|:---|:---|
| 200 | OK 请求执行完成。                                                                                    |
| 400 | BadRequest 非法请求。建议直接修改该请求，不要重试该请求。                                                            |
| 401 | Unauthorized 在客户端提供认证信息后，返回该状态码，表明服务端指出客户端所提供的认证信息不正确或非法。                                     |
| 403 | Forbidden 请求被拒绝访问。返回该状态码，表明请求能够到达服务端，且服务端能够理解用户请求，但是拒绝做更多的事情，因为该请求被设置为拒绝访问，建议直接修改该请求，不要重试该请求。 |
| 500 | InternalServerError 表明服务端能被请求访问到，但是不能理解用户的请求。                                                 |
| 503 | ServiceUnavailable 被请求的服务无效。建议直接修改该请求，不要重试该请求。                                                |
   
#### 错误码
请参见[错误码](https://support.huaweicloud.com/api-aom/ErrorCode.html)。
