Help Center/ SecMaster/ API Reference/ API/ Metric Query/ Querying Metrics in Batches
Updated on 2024-12-13 GMT+08:00

Querying Metrics in Batches

Function

This API is used to query metrics in batches.

Calling Method

For details, see Calling APIs.

URI

POST /v1/{project_id}/workspaces/{workspace_id}/sa/metrics/hits

Table 1 Path Parameters

Parameter

Mandatory

Type

Description

project_id

Yes

String

Project ID.

workspace_id

Yes

String

Workspace ID.

Table 2 Query Parameters

Parameter

Mandatory

Type

Description

timespan

No

String

The time range for querying metrics. The format is ISO8601, for example, 2007-03-01T13:00:00Z/2008-05-11T15:30:00Z, 2007-03-01T13:00:00Z/P1Y2M10DT2H30M, or P1Y2M10DT2H30M/2008-05-11T15:30:00Z.

cache

No

Boolean

Indicates whether to enable the cache. The default value is true. The value false indicates that the cache is disabled.

Request Parameters

Table 3 Request header parameters

Parameter

Mandatory

Type

Description

X-Auth-Token

Yes

String

User token. It can be obtained by calling the IAM API used to obtain a user token. The value of X-Subject-Token in the response header is a token.

Table 4 Request body parameters

Parameter

Mandatory

Type

Description

metric_ids

Yes

Array of strings

Specifies the metric ID list to be queried. For details about how to obtain the existing metrics, see the related information in the appendix.

workspace_ids

No

Array of strings

Workspace list. This API is mandatory when the metric supports obtaining data of multiple workspaces.

params

No

Array of Map<String,String> objects

Indicates the parameter list of the metric to be queried. Each element in the list is in K-V format of <String, String>. The number of elements must be the same as that of the metric_ids list. For details, see the appendix.

interactive_params

No

Array of Map<String,String> objects

For query the interactive parameters, if the metric supports interactive parameters, enter a parameter list in the K-V format of <String, String>. For details, see the appendix.

field_ids

No

Array of strings

Metric card ID list

Response Parameters

Status code: 200

Table 5 Response body parameters

Parameter

Type

Description

[items]

Array of ShowMetricResultResponseBody objects

Table 6 ShowMetricResultResponseBody

Parameter

Type

Description

metric_id

String

Metric ID

result

result object

Metric query result.

metric_format

Array of MetricFormat objects

Metric format. The value is fixed based on different metrics.

log_msg

String

Result log information

status

String

Query result status. The options are as follows: SUCCESS: The query is successful. FAILED: The query fails. FALLBACK: The default value is used.

Table 7 result

Parameter

Type

Description

labels

Array of strings

Title of the metric query result table

datarows

Array<Array<Object>>

Metric query result table.

effective_column

String

Effective columns. If this parameter exists, the specified column is used as the metric data result.

Table 8 MetricFormat

Parameter

Type

Description

data

String

Data format

display

String

Display format

display_param

Map<String,String>

Display parameter

data_param

Map<String,String>

Data parameters

Example Requests

Query the alarm severity distribution from June 25 to the current time through the metric API.

https://{endpoint}/v1/{project_id}/workspaces/{workspace_id}/sa/metrics/hits

{
  "metric_ids" : [ "1f0f5e29-5a92-17a5-2c16-5f37c6dc109c" ],
  "params" : [ {
    "start_date" : "2024-06-25T00:00:00.000+08:00"
  } ]
}

Example Responses

Status code: 200

Request successful.

[ {
  "metric_id" : "1f0f5e29-5a92-17a5-2c16-5f37c6dc109c",
  "result" : {
    "labels" : [ "label1" ],
    "datarows" : [ [ { } ] ],
    "effective_column" : "0:1"
  },
  "status" : "SUCCESS"
} ]

SDK Sample Code

The SDK sample code is as follows.

Query the alarm severity distribution from June 25 to the current time through the metric API.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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.v2.region.SecMasterRegion;
import com.huaweicloud.sdk.secmaster.v2.*;
import com.huaweicloud.sdk.secmaster.v2.model.*;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;

public class BatchSearchMetricHitsSolution {

    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();
        BatchSearchMetricHitsRequest request = new BatchSearchMetricHitsRequest();
        request.withWorkspaceId("{workspace_id}");
        BatchSearchMetricHitsRequestBody body = new BatchSearchMetricHitsRequestBody();
        Map<String, String> listParamsParams = new HashMap<>();
        listParamsParams.put("start_date", "2024-06-25T00:00:00.000+08:00");
        List<Map<String, String>> listbodyParams = new ArrayList<>();
        listbodyParams.add(listParamsParams);
        List<String> listbodyMetricIds = new ArrayList<>();
        listbodyMetricIds.add("1f0f5e29-5a92-17a5-2c16-5f37c6dc109c");
        body.withParams(listbodyParams);
        body.withMetricIds(listbodyMetricIds);
        request.withBody(body);
        try {
            BatchSearchMetricHitsResponse response = client.batchSearchMetricHits(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());
        }
    }
}

Query the alarm severity distribution from June 25 to the current time through the metric API.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# coding: utf-8

import os
from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdksecmaster.v2.region.secmaster_region import SecMasterRegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdksecmaster.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 = SecMasterClient.new_builder() \
        .with_credentials(credentials) \
        .with_region(SecMasterRegion.value_of("<YOUR REGION>")) \
        .build()

    try:
        request = BatchSearchMetricHitsRequest()
        request.workspace_id = "{workspace_id}"
        listParamsParams = {
            "start_date": "2024-06-25T00:00:00.000+08:00"
        }
        listParamsbody = [
            listParamsParams
        ]
        listMetricIdsbody = [
            "1f0f5e29-5a92-17a5-2c16-5f37c6dc109c"
        ]
        request.body = BatchSearchMetricHitsRequestBody(
            params=listParamsbody,
            metric_ids=listMetricIdsbody
        )
        response = client.batch_search_metric_hits(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

Query the alarm severity distribution from June 25 to the current time through the metric API.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package main

import (
	"fmt"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
    secmaster "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/secmaster/v2"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/secmaster/v2/model"
    region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/secmaster/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 := basic.NewCredentialsBuilder().
        WithAk(ak).
        WithSk(sk).
        WithProjectId(projectId).
        Build()

    client := secmaster.NewSecMasterClient(
        secmaster.SecMasterClientBuilder().
            WithRegion(region.ValueOf("<YOUR REGION>")).
            WithCredential(auth).
            Build())

    request := &model.BatchSearchMetricHitsRequest{}
	request.WorkspaceId = "{workspace_id}"
	var listParamsParams = map[string]string{
        "start_date": "2024-06-25T00:00:00.000+08:00",
    }
	var listParamsbody = []map[string]string{
        listParamsParams,
    }
	var listMetricIdsbody = []string{
        "1f0f5e29-5a92-17a5-2c16-5f37c6dc109c",
    }
	request.Body = &model.BatchSearchMetricHitsRequestBody{
		Params: &listParamsbody,
		MetricIds: listMetricIdsbody,
	}
	response, err := client.BatchSearchMetricHits(request)
	if err == nil {
        fmt.Printf("%+v\n", response)
    } else {
        fmt.Println(err)
    }
}

For SDK sample code of more programming languages, see the Sample Code tab in API Explorer. SDK sample code can be automatically generated.

Status Codes

Status Code

Description

200

Request successful.

Error Codes

See Error Codes.