Help Center/ Application Operations Management/ API Reference/ APIs/ Monitoring/ Adding or Modifying One or More Service Discovery Rules
Updated on 2024-06-28 GMT+08:00

Adding or Modifying One or More Service Discovery Rules

Function

This API is used to add or modify one or more service discovery rules. A maximum of 100 rules can be added to a project.

Calling Method

For details, see Calling APIs.

URI

PUT /v1/{project_id}/inv/servicediscoveryrules

Table 1 Path Parameters

Parameter

Mandatory

Type

Description

project_id

Yes

String

Project ID obtained from IAM. Generally, a project ID contains 32 characters.

Request Parameters

Table 2 Request header parameters

Parameter

Mandatory

Type

Description

X-Auth-Token

Yes

String

User token obtained from IAM.

Content-Type

Yes

String

Content type, which is application/json.

Enumeration values:

  • application/json

Table 3 Request body parameters

Parameter

Mandatory

Type

Description

appRules

No

Array of AppRules objects

Service parameters.

Table 4 AppRules

Parameter

Mandatory

Type

Description

createTime

No

String

Creation time. When creating a service discovery rule, leave this parameter blank. When modifying a service discovery rule, enter the returned createTime.

Default: 1599098476654

enable

Yes

Boolean

Whether a rule is enabled. Values: true and false.

eventName

Yes

String

aom_inventory_rules_event Rule event name. For service discovery, the fixed value is aom_inventory_rules_event.

hostid

No

Array of strings

Host ID. Currently, this parameter is not used and can be left blank.

id

Yes

String

Rule ID. When creating a service discovery rule, leave this parameter blank. When modifying a service discovery rule, enter a rule ID.

name

Yes

String

Rule name, which contains a maximum of 64 characters. It must start with a lowercase letter but cannot end with a hyphen (-). Only digits, lowercase letters, and hyphens are allowed.

projectid

Yes

String

Project ID obtained from IAM. Generally, a project ID contains 32 characters.

spec

Yes

AppRulesSpec object

Rule details.

desc

No

String

Custom description

Table 5 AppRulesSpec

Parameter

Mandatory

Type

Description

appType

Yes

String

Service type, which is used only for rule classification and UI display. You can enter any field. For example, enter Java or Python by technology stack, or enter collector or database by function.

attrList

No

Array of strings

Attribute list. Currently, this parameter is not used and can be left blank. Values: cmdLine and env.

detectLog

Yes

String

Whether to enable log collection. Values: true and false.

discoveryRule

Yes

Array of DiscoveryRule objects

Discovery rule. If the array contains multiple conditions, only the processes that meet all the conditions will be matched. If the value of checkType is cmdLine, set the value of checkMode to contain. checkContent is in the format of ["xxx"], indicating that the process must contain the xxx parameter. If the value of checkType is env, set the value of checkMode to contain. checkContent is in the format of ["k1","v1"], indicating that the process must contain the environment variable whose name is k1 and value is v1. If the value of checkType is scope, set the value of checkMode to equals. checkContent is in the format of ["hostId1","hostId2"], indicating that the rule takes effect only on specified nodes. If no nodes are specified, the rule applies to all nodes of the project.

isDefaultRule

Yes

String

Whether the rule is the default one. Values: true and false.

isDetect

Yes

String

Whether the scenario is a pre-check scenario. No rules will be saved in the pre-check scenario. This scenario is designed only to check whether a rule can detect node processes before it is delivered. Values: true and false.

logFileFix

Yes

Array of strings

Log file suffix. Values: log, trace, and out.

logPathRule

No

Array of LogPathRule objects

Log path configuration rule. If cmdLineHash is a fixed string, logs in the specified log path or log file are collected. Otherwise, only the files whose names end with .log or .trace are collected. If the value of nameType is cmdLineHash, args is in the format of ["00001"] and value is in the format of ["/xxx/xx.log"], indicating that the log path is /xxx/xx.log when the startup command is 00001.

nameRule

Yes

NameRule object

Naming rules for discovered services and applications.

priority

Yes

Integer

Rule priority. Value range: 1 to 9999. Default value: 9999.

dataSource

No

String

Data source.

editable

No

String

Whether to support editing. Options: true and false.

aom_metric_relabel_configs

No

Object

Metric configuration.

Table 6 DiscoveryRule

Parameter

Mandatory

Type

Description

checkContent

Yes

Array of strings

Matched value.

checkMode

Yes

String

Match condition. Values: contain and equals.

checkType

Yes

String

Match type. Values: cmdLine, env, and scope.

Table 7 LogPathRule

Parameter

Mandatory

Type

Description

args

Yes

Array of strings

Command.

nameType

Yes

String

Value type, which can be cmdLineHash.

value

Yes

Array of strings

Log path.

Table 8 NameRule

Parameter

Mandatory

Type

Description

appNameRule

Yes

Array of AppNameRule objects

Service name rule. If there are multiple objects in the array, the character strings extracted from these objects constitute the service name. If the value of nameType is cmdLine, args is in the format of ["start", "end"], indicating that the characters between start and end in the command are extracted.If the value of nameType is cmdLine, args is in the format of ["aa"], indicating that the environment variable named aa is extracted.If the value of nameType is str, args is in the format of ["fix"], indicating that the service name is suffixed with fix.If the value of nameType is cmdLineHash, args is in the format of ["0001"] and value is in the format of ["ser"], indicating that the service name is ser when the startup command is 0001.

applicationNameRule

Yes

Array of ApplicationNameRule objects

Application name rule.If the value of nameType is cmdLine, args is in the format of ["start", "end"], indicating that the characters between start and end in the command are extracted.If the value of nameType is cmdLine, args is in the format of ["aa"], indicating that the environment variable named aa is extracted.If the value of nameType is str, args is in the format of ["fix"], indicating that the service name is suffixed with fix.If the value of nameType is cmdLineHash, args is in the format of ["0001"] and value is in the format of ["ser"], indicating that the application name is ser when the startup command is 0001.

Table 9 AppNameRule

Parameter

Mandatory

Type

Description

nameType

Yes

String

Value type. Values: cmdLineHash, cmdLine, env, and str.

args

Yes

Array of strings

Input value.

value

No

Array of strings

Service name, which is mandatory only when the value of nameType is cmdLineHash.

Table 10 ApplicationNameRule

Parameter

Mandatory

Type

Description

nameType

Yes

String

Value type. Values: cmdLineHash, cmdLine, env, and str.

args

Yes

Array of strings

Input value.

value

No

Array of strings

Service name, which is mandatory only when the value of nameType is cmdLineHash.

Response Parameters

Status code: 200

Table 11 Response body parameters

Parameter

Type

Description

errorCode

String

Response code.

errorMessage

String

Response message.

responseStatus

Integer

Response status code (no longer used).

id

Array of strings

Service discovery rule ID list. This parameter is used during cross-AZ configuration synchronization.

results

Array of Map<String,String> objects

Details about service discovery rules.

Example Requests

Add an application discovery rule whose name is aom_inventory_rules_event and project ID is 684fc87a79d7xxxx22e62a7da95b.

https://{endpoint}/v1/{project_id}/inv/servicediscoveryrules

{
  "appRules" : [ {
    "createTime" : "1694705766730",
    "enable" : true,
    "name" : "ica**nt",
    "eventName" : "aom_inventory_rules_event",
    "hostid" : [ ],
    "id" : "b53a5152-****-****-****-302367e04c0b",
    "projectid" : "684fc87a79d7xxxx22e62a7da95b",
    "spec" : {
      "detectLog" : "true",
      "editable" : null,
      "logPathRule" : [ ],
      "priority" : 9999,
      "attrList" : [ "cmdLine" ],
      "nameRule" : {
        "appNameRule" : [ {
          "args" : [ "/opt/********* -DNFW=ica**nt" ],
          "nameType" : "cmdLineHash",
          "value" : [ "aicagentserver" ]
        } ],
        "applicationNameRule" : [ {
          "args" : [ "/opt/*********** -DNFW=ica**nt" ],
          "nameType" : "cmdLineHash",
          "value" : [ "aica**nt" ]
        } ]
      },
      "appType" : "",
      "aom_metric_relabel_configs" : null,
      "logFileFix" : [ "log", "trace", "out" ],
      "isDetect" : "false",
      "isDefaultRule" : null,
      "dataSource" : null,
      "discoveryRule" : [ {
        "checkType" : "cmdLine",
        "checkContent" : [ "-DNFW=ica**nt" ],
        "checkMode" : "contain"
      } ]
    },
    "desc" : "Custom description"
  } ]
}

Example Responses

Status code: 200

OK: The request is successful.

{
  "errorCode" : "SVCSTG.INV.2000000",
  "errorMessage" : null,
  "id" : [ ],
  "results" : [ {
    "name" : "aom_inventory_rules_event",
    "id" : "b53a5152-****-****-****-302367e04c0b"
  } ]
}

Status code: 400

Bad Request: The request is invalid. The client should not repeat the request without modifications.

{
  "errorCode" : "SVCSTG.INV.4000115",
  "errorMessage" : "apprule name has existed",
  "id" : [ ],
  "results" : [ ]
}

SDK Sample Code

The SDK sample code is as follows.

Java

Add an application discovery rule whose name is aom_inventory_rules_event and project ID is 684fc87a79d7xxxx22e62a7da95b.

  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
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
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 AddOrUpdateServiceDiscoveryRulesSolution {

    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");

        ICredential auth = new BasicCredentials()
                .withAk(ak)
                .withSk(sk);

        AomClient client = AomClient.newBuilder()
                .withCredential(auth)
                .withRegion(AomRegion.valueOf("<YOUR REGION>"))
                .build();
        AddOrUpdateServiceDiscoveryRulesRequest request = new AddOrUpdateServiceDiscoveryRulesRequest();
        AppRulesBody body = new AppRulesBody();
        List<String> listApplicationNameRuleValue = new ArrayList<>();
        listApplicationNameRuleValue.add("aica**nt");
        List<String> listApplicationNameRuleArgs = new ArrayList<>();
        listApplicationNameRuleArgs.add("/opt/*********** -DNFW=ica**nt");
        List<ApplicationNameRule> listNameRuleApplicationNameRule = new ArrayList<>();
        listNameRuleApplicationNameRule.add(
            new ApplicationNameRule()
                .withNameType("cmdLineHash")
                .withArgs(listApplicationNameRuleArgs)
                .withValue(listApplicationNameRuleValue)
        );
        List<String> listAppNameRuleValue = new ArrayList<>();
        listAppNameRuleValue.add("aicagentserver");
        List<String> listAppNameRuleArgs = new ArrayList<>();
        listAppNameRuleArgs.add("/opt/********* -DNFW=ica**nt");
        List<AppNameRule> listNameRuleAppNameRule = new ArrayList<>();
        listNameRuleAppNameRule.add(
            new AppNameRule()
                .withNameType("cmdLineHash")
                .withArgs(listAppNameRuleArgs)
                .withValue(listAppNameRuleValue)
        );
        NameRule nameRuleSpec = new NameRule();
        nameRuleSpec.withAppNameRule(listNameRuleAppNameRule)
            .withApplicationNameRule(listNameRuleApplicationNameRule);
        List<String> listSpecLogFileFix = new ArrayList<>();
        listSpecLogFileFix.add("log");
        listSpecLogFileFix.add("trace");
        listSpecLogFileFix.add("out");
        List<String> listDiscoveryRuleCheckContent = new ArrayList<>();
        listDiscoveryRuleCheckContent.add("-DNFW=ica**nt");
        List<DiscoveryRule> listSpecDiscoveryRule = new ArrayList<>();
        listSpecDiscoveryRule.add(
            new DiscoveryRule()
                .withCheckContent(listDiscoveryRuleCheckContent)
                .withCheckMode("contain")
                .withCheckType("cmdLine")
        );
        List<String> listSpecAttrList = new ArrayList<>();
        listSpecAttrList.add("cmdLine");
        AppRulesSpec specAppRules = new AppRulesSpec();
        specAppRules.withAppType("")
            .withAttrList(listSpecAttrList)
            .withDetectLog("true")
            .withDiscoveryRule(listSpecDiscoveryRule)
            .withIsDetect("false")
            .withLogFileFix(listSpecLogFileFix)
            .withNameRule(nameRuleSpec)
            .withPriority(9999);
        List<AppRules> listbodyAppRules = new ArrayList<>();
        listbodyAppRules.add(
            new AppRules()
                .withCreateTime("1694705766730")
                .withEnable(true)
                .withEventName("aom_inventory_rules_event")
                .withHostid()
                .withId("b53a5152-****-****-****-302367e04c0b")
                .withName("ica**nt")
                .withProjectid("684fc87a79d7xxxx22e62a7da95b")
                .withSpec(specAppRules)
                .withDesc("Custom description")
        );
        body.withAppRules(listbodyAppRules);
        request.withBody(body);
        try {
            AddOrUpdateServiceDiscoveryRulesResponse response = client.addOrUpdateServiceDiscoveryRules(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

Add an application discovery rule whose name is aom_inventory_rules_event and project ID is 684fc87a79d7xxxx22e62a7da95b.

  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
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
# 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"]

    credentials = BasicCredentials(ak, sk)

    client = AomClient.new_builder() \
        .with_credentials(credentials) \
        .with_region(AomRegion.value_of("<YOUR REGION>")) \
        .build()

    try:
        request = AddOrUpdateServiceDiscoveryRulesRequest()
        listValueApplicationNameRule = [
            "aica**nt"
        ]
        listArgsApplicationNameRule = [
            "/opt/*********** -DNFW=ica**nt"
        ]
        listApplicationNameRuleNameRule = [
            ApplicationNameRule(
                name_type="cmdLineHash",
                args=listArgsApplicationNameRule,
                value=listValueApplicationNameRule
            )
        ]
        listValueAppNameRule = [
            "aicagentserver"
        ]
        listArgsAppNameRule = [
            "/opt/********* -DNFW=ica**nt"
        ]
        listAppNameRuleNameRule = [
            AppNameRule(
                name_type="cmdLineHash",
                args=listArgsAppNameRule,
                value=listValueAppNameRule
            )
        ]
        nameRuleSpec = NameRule(
            app_name_rule=listAppNameRuleNameRule,
            application_name_rule=listApplicationNameRuleNameRule
        )
        listLogFileFixSpec = [
            "log",
            "trace",
            "out"
        ]
        listCheckContentDiscoveryRule = [
            "-DNFW=ica**nt"
        ]
        listDiscoveryRuleSpec = [
            DiscoveryRule(
                check_content=listCheckContentDiscoveryRule,
                check_mode="contain",
                check_type="cmdLine"
            )
        ]
        listAttrListSpec = [
            "cmdLine"
        ]
        specAppRules = AppRulesSpec(
            app_type="",
            attr_list=listAttrListSpec,
            detect_log="true",
            discovery_rule=listDiscoveryRuleSpec,
            is_detect="false",
            log_file_fix=listLogFileFixSpec,
            name_rule=nameRuleSpec,
            priority=9999
        )
        listAppRulesbody = [
            AppRules(
                create_time="1694705766730",
                enable=True,
                event_name="aom_inventory_rules_event",
                id="b53a5152-****-****-****-302367e04c0b",
                name="ica**nt",
                projectid="684fc87a79d7xxxx22e62a7da95b",
                spec=specAppRules,
                desc="Custom description"
            )
        ]
        request.body = AppRulesBody(
            app_rules=listAppRulesbody
        )
        response = client.add_or_update_service_discovery_rules(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

Add an application discovery rule whose name is aom_inventory_rules_event and project ID is 684fc87a79d7xxxx22e62a7da95b.

  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
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
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")

    auth := basic.NewCredentialsBuilder().
        WithAk(ak).
        WithSk(sk).
        Build()

    client := aom.NewAomClient(
        aom.AomClientBuilder().
            WithRegion(region.ValueOf("<YOUR REGION>")).
            WithCredential(auth).
            Build())

    request := &model.AddOrUpdateServiceDiscoveryRulesRequest{}
	var listValueApplicationNameRule = []string{
        "aica**nt",
    }
	var listArgsApplicationNameRule = []string{
        "/opt/*********** -DNFW=ica**nt",
    }
	var listApplicationNameRuleNameRule = []model.ApplicationNameRule{
        {
            NameType: "cmdLineHash",
            Args: listArgsApplicationNameRule,
            Value: &listValueApplicationNameRule,
        },
    }
	var listValueAppNameRule = []string{
        "aicagentserver",
    }
	var listArgsAppNameRule = []string{
        "/opt/********* -DNFW=ica**nt",
    }
	var listAppNameRuleNameRule = []model.AppNameRule{
        {
            NameType: "cmdLineHash",
            Args: listArgsAppNameRule,
            Value: &listValueAppNameRule,
        },
    }
	nameRuleSpec := &model.NameRule{
		AppNameRule: listAppNameRuleNameRule,
		ApplicationNameRule: listApplicationNameRuleNameRule,
	}
	var listLogFileFixSpec = []string{
        "log",
	    "trace",
	    "out",
    }
	var listCheckContentDiscoveryRule = []string{
        "-DNFW=ica**nt",
    }
	var listDiscoveryRuleSpec = []model.DiscoveryRule{
        {
            CheckContent: listCheckContentDiscoveryRule,
            CheckMode: "contain",
            CheckType: "cmdLine",
        },
    }
	var listAttrListSpec = []string{
        "cmdLine",
    }
	specAppRules := &model.AppRulesSpec{
		AppType: "",
		AttrList: &listAttrListSpec,
		DetectLog: "true",
		DiscoveryRule: listDiscoveryRuleSpec,
		IsDetect: "false",
		LogFileFix: listLogFileFixSpec,
		NameRule: nameRuleSpec,
		Priority: int32(9999),
	}
	createTimeAppRules:= "1694705766730"
	descAppRules:= "Custom description"
	var listAppRulesbody = []model.AppRules{
        {
            CreateTime: &createTimeAppRules,
            Enable: true,
            EventName: "aom_inventory_rules_event",
            Id: "b53a5152-****-****-****-302367e04c0b",
            Name: "ica**nt",
            Projectid: "684fc87a79d7xxxx22e62a7da95b",
            Spec: specAppRules,
            Desc: &descAppRules,
        },
    }
	request.Body = &model.AppRulesBody{
		AppRules: &listAppRulesbody,
	}
	response, err := client.AddOrUpdateServiceDiscoveryRules(request)
	if err == nil {
        fmt.Printf("%+v\n", response)
    } else {
        fmt.Println(err)
    }
}

More

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

OK: The request is successful.

400

Bad Request: The request is invalid. The client should not repeat the request without modifications.

401

Unauthorized: The authentication information is incorrect or invalid.

403

Forbidden: The request is rejected. The server has received the request and understood it, but the server refuses to respond to it. The client should not repeat the request without modifications.

500

Internal Server Error: The server is able to receive the request but unable to understand the request.

503

Service Unavailable: The requested service is invalid. The client should not repeat the request without modifications.

Error Codes

See Error Codes.