
# 创建Prometheus实例的预聚合规则 - CreateRecordingRule
#### 功能介绍
该接口用于给Prometheus实例创建预聚合规则。
#### 调用方法
请参见[如何调用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:put | Write | -           | -   | -  | -      |
     
  
 
#### URI
POST /v1/{project_id}/{prometheus_instance}/aom/api/v1/rules
表1路径参数 
| 参数                  | 是否必选 | 参数类型   | 描述                                                           |
|:---|:---|:---|:---|
| project_id          | 是    | String | 租户从IAM申请到的projectid，一般为32位字符串。                               |
| prometheus_instance | 是    | String | prometheus实例id。当前仅支持Prometheus实例类型为Prometheus for CCE 和通用实例。 |
   
#### 请求参数
表2请求Header参数 
| 参数           | 是否必选 | 参数类型   | 描述                     |
|:---|:---|:---|:---|
| X-Auth-Token | 是    | String | 从IAM服务获取的用户Token。      |
| Content-Type | 是    | String | 指定类型为application/json。 |
   
表3请求Body参数 
| 参数             | 是否必选 | 参数类型   | 描述                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
|:---|:---|:---|:---|
| recording_rule | 是    | String | 预聚合规则。 待创建的预聚合规则详细信息。支持如下子参数： - groups：规则组。一份RecordingRule.yaml可以配置多组规则组。   - name：规则组名称。规则组名称必须唯一。   - interval：规则组的执行周期。默认60s。（可选）   - rules：规则。一个规则组可以包含多条规则。   - record：规则的名称。聚合规则的名称必须符合 [Prometheus指标名称规范](https://prometheus.io/docs/concepts/data_model/#metric-names-and-labels)。   - expr：计算表达式。Prometheus监控将通过该表达式计算得出预聚合指标。计算表达式必须符合[PromQL](https://prometheus.io/docs/prometheus/latest/querying/basics/)。   - labels：指标的标签。标签必须符合[Prometheus指标标签规范](https://prometheus.io/docs/concepts/data_model/#metric-names-and-labels)。（可选）    |
   
#### 响应参数
**状态码：204**
No Content 表示请求成功，但没有内容返回。
**状态码：500**
表4响应Body参数 
| 参数         | 参数类型   | 描述    |
|:---|:---|:---|
| error_code | String | 错误码。  |
| error_msg  | String | 错误信息。 |
| error_type | String | 错误类型。 |
| trace_id   | String | 链路id。 |
   
#### 请求示例
给Prometheus实例创建预聚合规则。
```
https://{Endpoint}/v1/{project_id}/{prometheus_instance}/aom/api/v1/rules
{
  "recording_rule" : "groups:\n    - name: apiserver_request_total\n      interval: 60s\n      rules:\n        - record: job_instance_mode:apiserver_request_total:avg_rate5m\n          expr: avg by (job, instance, mode) (rate(apiserver_request_total[5m]))\n          labels:\n            team: operations\n        - record: job:apiserver_request_total:sum_rate10m\n          expr: sum by (job)(rate(apiserver_request_total[10m]))\n          labels:\n            team: operations"
}
```
#### 响应示例
**状态码：500**
预聚合规则已经存在。
```
{
  "error_code" : "AOM.4001019",
  "error_msg" : "recording rule exist for the prometheus instance"
}
```
#### SDK代码示例
SDK代码示例如下。
- [Java]
  给Prometheus实例创建预聚合规则。
  ```
  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.*;
  public class CreateRecordingRuleSolution {
      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();
          CreateRecordingRuleRequest request = new CreateRecordingRuleRequest();
          request.withPrometheusInstance("{prometheus_instance}");
          RecordingRuleRequest body = new RecordingRuleRequest();
          body.withRecordingRule("groups:
      - name: apiserver_request_total
        interval: 60s
        rules:
          - record: job_instance_mode:apiserver_request_total:avg_rate5m
            expr: avg by (job, instance, mode) (rate(apiserver_request_total[5m]))
            labels:
              team: operations
          - record: job:apiserver_request_total:sum_rate10m
            expr: sum by (job)(rate(apiserver_request_total[10m]))
            labels:
              team: operations");
          request.withBody(body);
          try {
              CreateRecordingRuleResponse response = client.createRecordingRule(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]
  给Prometheus实例创建预聚合规则。
  ```
  # 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 = CreateRecordingRuleRequest()
          request.prometheus_instance = "{prometheus_instance}"
          request.body = RecordingRuleRequest(
              recording_rule="groups:
      - name: apiserver_request_total
        interval: 60s
        rules:
          - record: job_instance_mode:apiserver_request_total:avg_rate5m
            expr: avg by (job, instance, mode) (rate(apiserver_request_total[5m]))
            labels:
              team: operations
          - record: job:apiserver_request_total:sum_rate10m
            expr: sum by (job)(rate(apiserver_request_total[10m]))
            labels:
              team: operations"
          )
          response = client.create_recording_rule(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]
  给Prometheus实例创建预聚合规则。
  ```
  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.CreateRecordingRuleRequest{}
  request.PrometheusInstance = "{prometheus_instance}"
  request.Body = &model.RecordingRuleRequest{
  RecordingRule: "groups:
      - name: apiserver_request_total
        interval: 60s
        rules:
          - record: job_instance_mode:apiserver_request_total:avg_rate5m
            expr: avg by (job, instance, mode) (rate(apiserver_request_total[5m]))
            labels:
              team: operations
          - record: job:apiserver_request_total:sum_rate10m
            expr: sum by (job)(rate(apiserver_request_total[10m]))
            labels:
              team: operations",
  }
  response, err := client.CreateRecordingRule(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=CreateRecordingRule)的代码示例页签，可生成自动对应的SDK代码示例。
#### 状态码
| 状态码 | 描述                         |
|:---|:---|
| 204 | No Content 表示请求成功，但没有内容返回。 |
| 500 | 预聚合规则已经存在。                 |
   
#### 错误码
请参见[错误码](https://support.huaweicloud.com/api-aom/ErrorCode.html)。
