文档首页> 应用运维管理 AOM> API参考> API> 监控> 添加或修改服务发现规则
更新时间:2024-02-01 GMT+08:00

添加或修改服务发现规则

功能介绍

该接口用于添加或修改一条或多条服务发现规则。同一projectid下可添加的规则上限为100条。(当前接口未上线墨西哥城二、圣地亚哥、圣保罗一)

调用方法

请参见如何调用API

URI

PUT /v1/{project_id}/inv/servicediscoveryrules

表1 路径参数

参数

是否必选

参数类型

描述

project_id

String

租户从IAM申请到的projectid,一般为32位字符串。

请求参数

表2 请求Header参数

参数

是否必选

参数类型

描述

X-Auth-Token

String

从IAM服务获取的用户Token。

Content-Type

String

指定类型为application/json。

枚举值:

  • application/json

表3 请求Body参数

参数

是否必选

参数类型

描述

appRules

Array of AppRules objects

服务参数。

表4 AppRules

参数

是否必选

参数类型

描述

createTime

String

规则创建时间(创建时不传,修改时传查询返回的createTime)。

缺省值:1599098476654

enable

Boolean

true、false 规则是否启用。

eventName

String

aom_inventory_rules_event规则事件名称,对于服务发现固定为"aom_inventory_rules_event"。

hostid

Array of strings

主机ID(暂不使用,传空即可)。

id

String

创建时填空,修改时填规则ID。

name

String

规则名称。 字符长度为4到63位,以小写字母a-z开头,只能包含0-9/a-z/-,不能以-结尾。

projectid

String

租户从IAM申请到的projectid,一般为32位字符串。

spec

AppRulesSpec object

规则详情。

desc

String

自定义描述信息

表5 AppRulesSpec

参数

是否必选

参数类型

描述

appType

String

服务类型,用于标记服务的分类,仅用于规则分类和界面展示。可以填写任意字段,如按技术栈分类可填写Java,Python。按作用分类可填写collector(采集),database(数据库)等。

attrList

Array of strings

属性列表(暂不使用,可不传)。 cmdLine、env

detectLog

String

是否开启日志采集。 true、false

discoveryRule

Array of DiscoveryRule objects

规则发现部分,数组中有多个对象时表示需要同时满足所有条件的进程才会被匹配到。checkType为cmdLine时checkMode填contain,checkContent格式为["xxx"]表示进程命令行参数中需要包含xxx。checkType为env时checkMode填contain,checkContent格式为 ["k1","v1"]表示进程环境变量中需要包含名为k1值为v1的环境变量。checkType为scope时checkMode填equals,checkContent格式为节点ID数组["hostId1","hostId2"],表示规则仅会在这些节点上生效(如果不指定节点范围,规则将下发到该项目所有的节点)。

isDefaultRule

String

是否为默认规则。 true、false

isDetect

String

是否为规则预探测场景(预探测场景不会保存规则,仅用于规则下发之前验证该规则能否有效发现节点上的进程)。true、false

logFileFix

Array of strings

日志文件的后缀。 log、trace、out

logPathRule

Array of LogPathRule objects

日志路径配置规则。当cmdLineHash为固定字符串时,指定日志路径或者日志文件。否则只采集进程当前打开的以.log和.trace结尾的文件。nameType取值cmdLineHash时,args格式为["00001"],value格式为["/xxx/xx.log"],表示当启动命令是00001时,日志路径为/xxx/xx.log。

nameRule

NameRule object

发现上来的服务、应用的命名规则。

priority

Integer

规则优先级。1~9999的整数字符串,默认取值为9999

dataSource

String

数据源

editable

String

是否支持编辑 true、false

aom_metric_relabel_configs

Object

指标配置

表6 DiscoveryRule

参数

是否必选

参数类型

描述

checkContent

Array of strings

匹配值。

checkMode

String

匹配条件。contain、equals

checkType

String

匹配类型。cmdLine、env、scope

表7 LogPathRule

参数

是否必选

参数类型

描述

args

Array of strings

命令行。

nameType

String

取值类型。 cmdLineHash

value

Array of strings

日志路径。

表8 NameRule

参数

是否必选

参数类型

描述

appNameRule

Array of AppNameRule objects

服务命名部分,数组中有多个对象时表示将每个对象抽取到的字符串拼接作为服务的名称。nameType取值cmdLine时args格式为["start","end"],表示抽取命令行中start、end之间的字符。nameType取值cmdLine时args格式为["aa"],表示抽取环境变量名为aa对应的环境变量值。nameType取值str时,args格式为["fix"],表示服务名称最后拼接固定文字fix。nameType取值cmdLineHash时,args格式为["0001"],value格式为["ser"],表示当启动命令是0001时,服务名称为ser。

applicationNameRule

Array of ApplicationNameRule objects

应用命名部分。nameType取值cmdLine时args格式为["start","end"],表示抽取命令行中start、end之间的字符。nameType取值cmdLine时args格式为 ["aa"],表示抽取环境变量名为aa对应的环境变量值。nameType取值str时,args格式为["fix"],表示服务名称最后拼接固定文字fix。nameType取值cmdLineHash时,args格式为["0001"],value格式为["ser"],表示当启动命令是0001时,应用名称为ser。

表9 AppNameRule

参数

是否必选

参数类型

描述

nameType

String

取值类型。从cmdLineHash、cmdLine、env、str里面选取。

args

Array of strings

输入值。

value

Array of strings

服务名(仅nameType为cmdLineHash时填写)。

表10 ApplicationNameRule

参数

是否必选

参数类型

描述

nameType

String

取值类型。 从cmdLineHash、cmdLine、env、str里面选取。

args

Array of strings

输入值。

value

Array of strings

服务名(仅nameType为cmdLineHash时填写)。

响应参数

状态码: 200

表11 响应Body参数

参数

参数类型

描述

errorCode

String

响应码。

errorMessage

String

响应信息描述。

responseStatus

Integer

响应状态码(不再使用)。

id

Array of strings

服务发现规则id列表,多AZ配置同步时使用。

results

Array of Map<String,String> objects

服务发现规则详细信息列表。

请求示例

添加名称为“aom_inventory_rules_event”且用户project_id为“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" : "自定义描述/User-defined description"
  } ]
}

响应示例

状态码: 200

OK 请求响应成功。

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

状态码: 400

BadRequest 非法请求。建议直接修改该请求,不要重试该请求。

{
  "errorCode" : "SVCSTG.INV.4000115",
  "errorMessage" : "Request param is invalid",
  "id" : [ ],
  "results" : [ ]
}

SDK代码示例

SDK代码示例如下。

添加名称为“aom_inventory_rules_event”且用户project_id为“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("自定义描述/User-defined 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());
        }
    }
}

添加名称为“aom_inventory_rules_event”且用户project_id为“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
# coding: utf-8

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.getenv("CLOUD_SDK_AK")
    sk = os.getenv("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="自定义描述/User-defined 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)

添加名称为“aom_inventory_rules_event”且用户project_id为“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:= "自定义描述/User-defined 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)
    }
}

更多编程语言的SDK代码示例,请参见API Explorer的代码示例页签,可生成自动对应的SDK代码示例。

状态码

状态码

描述

200

OK 请求响应成功。

400

BadRequest 非法请求。建议直接修改该请求,不要重试该请求。

401

Unauthorized 在客户端提供认证信息后,返回该状态码,表明服务端指出客户端所提供的认证信息不正确或非法。

403

Forbidden 请求被拒绝访问。返回该状态码,表明请求能够到达服务端,且服务端能够理解用户请求,但是拒绝做更多的事情,因为该请求被设置为拒绝访问,建议直接修改该请求,不要重试该请求。

500

InternalServerError 表明服务端能被请求访问到,但是不能理解用户的请求。

503

ServiceUnavailable 被请求的服务无效。建议直接修改该请求,不要重试该请求。

错误码

请参见错误码