
# 模拟告警规则 - CreateAlertRuleSimulation
#### 功能介绍
模拟告警规则
#### 调用方法
请参见[如何调用API](https://support.huaweicloud.com/api-secmaster/secmaster_03_0008.html)。
#### 授权信息
账号具备所有API的调用权限，如果使用账号下的IAM用户调用当前API，该IAM用户需具备调用API所需的权限，具体权限要求请参见[权限和授权项](https://support.huaweicloud.com/api-secmaster/secmaster_03_0023.html)。
#### URI
POST /v1/{project_id}/workspaces/{workspace_id}/siem/alert-rules/simulation
表1路径参数 
| 参数           | 是否必选 | 参数类型   | 描述      |
|:---|:---|:---|:---|
| project_id   | 是    | String | 项目 ID   |
| workspace_id | 是    | String | 工作空间 ID |
   
#### 请求参数
表2请求Header参数 
| 参数           | 是否必选 | 参数类型   | 描述                             |
|:---|:---|:---|:---|
| X-Auth-Token | 是    | String | 用户Token，通过调用IAM服务获取用户Token接口获取 |
   
表3请求Body参数 
| 参数             | 是否必选 | 参数类型                                                                                      | 描述                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
|:---|:---|:---|:---|
| event_grouping | 否    | Boolean                                                                                   | 告警分组                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| from           | 是    | Long                                                                                      | 开始时间                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| pipe_id        | 是    | String                                                                                    | 数据管道 ID                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| query          | 是    | String                                                                                    | 查询语句                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| query_type     | 否    | String                                                                                    | **参数解释**: 查询语法类型 - SQL查询   - SQL    **约束限制**: 不涉及 **取值范围**: **默认值**: SQL |
| to             | 是    | Long                                                                                      | 结束时间                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| triggers       | 是    | Array of [AlertRuleTrigger] objects | 告警触发规则                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
   
 表4AlertRuleTrigger 
| 参数                | 是否必选 | 参数类型    | 描述                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
|:---|:---|:---|:---|
| accumulated_times | 否    | Integer | 累计次数                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| expression        | 是    | String  | 表达式                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| mode              | 否    | String  | **参数解释**: 指标模式 - COUNT 数量    **约束限制** 不涉及 **取值范围**: - COUNT    **默认值** 不涉及                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| operator          | 否    | String  | **参数解释**: 操作符类型 - GT 大于   - LT 小于   - EQ 等于   - NE 不等于    **约束限制** 不涉及 **取值范围**: - GT   - LT   - EQ   - NE    **默认值** 不涉及                                                                                                                                                                                                                                                                                                                                                          |
| severity          | 否    | String  | **参数解释**: 告警等级 - TIPS 提示   - LOW 低危   - MEDIUM 中危   - HIGH 高危   - FATAL 致命    **约束限制** 不涉及 **取值范围**: - TIPS   - LOW   - MEDIUM   - HIGH   - FATAL    **默认值** 不涉及 |
   
#### 响应参数
**状态码：200**
表5响应Header参数 
| 参数           | 参数类型   | 描述       |
|:---|:---|:---|
| X-request-id | String | 任务追踪请求ID |
   
表6响应Body参数 
| 参数          | 参数类型    | 描述                                                           |
|:---|:---|:---|
| alert_count | Integer | 告警数量                                                         |
| severity    | String  | 严重程度，提示、低危、中危、高危、致命。Severity. TIPS, LOW, MEDIUM, HIGH, FATAL |
   
**状态码：400**
表7响应Header参数 
| 参数           | 参数类型   | 描述       |
|:---|:---|:---|
| X-request-id | String | 任务追踪请求ID |
   
#### 请求示例
模拟一条告警规则，告警规则所属的管道ID为ead2769b-afb0-45dd-b9fa-a2953e6ac82f，查询类型为SQL，严重程度为提示。
```
{
  "event_grouping" : true,
  "from" : 1665221214000,
  "pipe_id" : "ead2769b-afb0-45dd-b9fa-a2953e6ac82f",
  "query" : "* | select status, count(*) as count group by status",
  "query_type" : "SQL",
  "to" : 1665546370000,
  "triggers" : [ {
    "expression" : 10,
    "mode" : "COUNT",
    "operator" : "GT",
    "severity" : "TIPS"
  } ]
}
```
#### 响应示例
**状态码：200**
请求成功
```
{
  "alert_count" : 100,
  "severity" : "TIPS"
}
```
#### SDK代码示例
SDK代码示例如下。
- [Java]
  模拟一条告警规则，告警规则所属的管道ID为ead2769b-afb0-45dd-b9fa-a2953e6ac82f，查询类型为SQL，严重程度为提示。
  ```
  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.secmaster.v1.region.SecMasterRegion;
  import com.huaweicloud.sdk.secmaster.v1.*;
  import com.huaweicloud.sdk.secmaster.v1.model.*;
  import java.util.List;
  import java.util.ArrayList;
  public class CreateAlertRuleSimulationSolution {
      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);
          SecMasterClient client = SecMasterClient.newBuilder()
                  .withCredential(auth)
                  .withRegion(SecMasterRegion.valueOf("<YOUR REGION>"))
                  .build();
          CreateAlertRuleSimulationRequest request = new CreateAlertRuleSimulationRequest();
          request.withWorkspaceId("{workspace_id}");
          CreateAlertRuleSimulationRequestBody body = new CreateAlertRuleSimulationRequestBody();
          List<AlertRuleTrigger> listbodyTriggers = new ArrayList<>();
          listbodyTriggers.add(
              new AlertRuleTrigger()
                  .withExpression("10")
                  .withMode(AlertRuleTrigger.ModeEnum.fromValue("COUNT"))
                  .withOperator(AlertRuleTrigger.OperatorEnum.fromValue("GT"))
                  .withSeverity(AlertRuleTrigger.SeverityEnum.fromValue("TIPS"))
          );
          body.withTriggers(listbodyTriggers);
          body.withTo(1665546370000L);
          body.withQueryType(CreateAlertRuleSimulationRequestBody.QueryTypeEnum.fromValue("SQL"));
          body.withQuery("* | select status, count(*) as count group by status");
          body.withPipeId("ead2769b-afb0-45dd-b9fa-a2953e6ac82f");
          body.withFrom(1665221214000L);
          body.withEventGrouping(true);
          request.withBody(body);
          try {
              CreateAlertRuleSimulationResponse response = client.createAlertRuleSimulation(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]
  模拟一条告警规则，告警规则所属的管道ID为ead2769b-afb0-45dd-b9fa-a2953e6ac82f，查询类型为SQL，严重程度为提示。
  ```
  # coding: utf-8
  import os
  from huaweicloudsdkcore.auth.credentials import BasicCredentials
  from huaweicloudsdksecmaster.v1.region.secmaster_region import SecMasterRegion
  from huaweicloudsdkcore.exceptions import exceptions
  from huaweicloudsdksecmaster.v1 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 = SecMasterClient.new_builder() \
          .with_credentials(credentials) \
          .with_region(SecMasterRegion.value_of("<YOUR REGION>")) \
          .build()
      try:
          request = CreateAlertRuleSimulationRequest()
          request.workspace_id = "{workspace_id}"
          listTriggersbody = [
              AlertRuleTrigger(
                  expression="10",
                  mode="COUNT",
                  operator="GT",
                  severity="TIPS"
              )
          ]
          request.body = CreateAlertRuleSimulationRequestBody(
              triggers=listTriggersbody,
              to=1665546370000,
              query_type="SQL",
              query="* | select status, count(*) as count group by status",
              pipe_id="ead2769b-afb0-45dd-b9fa-a2953e6ac82f",
              _from=1665221214000,
              event_grouping=True
          )
          response = client.create_alert_rule_simulation(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]
  模拟一条告警规则，告警规则所属的管道ID为ead2769b-afb0-45dd-b9fa-a2953e6ac82f，查询类型为SQL，严重程度为提示。
  ```
  package main
  import (
  "fmt"
  "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
      secmaster "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/secmaster/v1"
  "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/secmaster/v1/model"
      region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/secmaster/v1/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 := secmaster.SecMasterClientBuilder().
           WithRegion(region.ValueOf("<YOUR REGION>")).
           WithCredential(auth).
           SafeBuild()
      if err != nil {
          fmt.Println(err)
          return
      }
      client := secmaster.NewSecMasterClient(hcClient)
      request := &model.CreateAlertRuleSimulationRequest{}
  request.WorkspaceId = "{workspace_id}"
  modeTriggers:= model.GetAlertRuleTriggerModeEnum().COUNT
  operatorTriggers:= model.GetAlertRuleTriggerOperatorEnum().GT
  severityTriggers:= model.GetAlertRuleTriggerSeverityEnum().TIPS
  var listTriggersbody = []model.AlertRuleTrigger{
          {
              Expression: "10",
              Mode: &modeTriggers,
              Operator: &operatorTriggers,
              Severity: &severityTriggers,
          },
      }
  queryTypeCreateAlertRuleSimulationRequestBody:= model.GetCreateAlertRuleSimulationRequestBodyQueryTypeEnum().SQL
  eventGroupingCreateAlertRuleSimulationRequestBody:= true
  request.Body = &model.CreateAlertRuleSimulationRequestBody{
  Triggers: listTriggersbody,
  To: int64(1665546370000),
  QueryType: &queryTypeCreateAlertRuleSimulationRequestBody,
  Query: "* | select status, count(*) as count group by status",
  PipeId: "ead2769b-afb0-45dd-b9fa-a2953e6ac82f",
  From: int64(1665221214000),
  EventGrouping: &eventGroupingCreateAlertRuleSimulationRequestBody,
  }
  response, err := client.CreateAlertRuleSimulation(request)
  if err == nil {
          fmt.Printf("%+v\n", response)
      } else {
          fmt.Println(err)
      }
  }
  ```
- [更多]
  更多编程语言的SDK代码示例，请参见[API Explorer](https://console.huaweicloud.com/apiexplorer/#/openapi/SecMaster/sdk?api=CreateAlertRuleSimulation&version=v1)的代码示例页签，可生成自动对应的SDK代码示例。
#### 状态码
| 状态码 | 描述   |
|:---|:---|
| 200 | 请求成功 |
| 400 | 请求失败 |
   
#### 错误码
请参见[错误码](https://support.huaweicloud.com/api-secmaster/ErrorCode.html)。
