API를 사용하여 알림 정책 만들기

알림 정책은 Cloud Monitoring API에서 AlertPolicy 객체로 표현됩니다. 이 객체는 시스템의 비정상 상태를 나타내는 조건 집합을 설명합니다.

이 문서에서는 다음을 설명합니다.

  • Monitoring API가 알림 정책을 나타내는 방법
  • Monitoring API가 알림 정책에 제공하는 조건 유형
  • Google Cloud CLI 또는 클라이언트 라이브러리를 사용하여 알림 정책을 만드는 방법

알림 정책 구조

AlertPolicy 구조는 알림 정책의 구성요소를 정의합니다. 정책을 만들 때 다음 AlertPolicy 필드에 대해 값을 지정합니다.

  • displayName: 정책을 설명하는 라벨입니다.
  • documentation: 응답자를 지원하기 위해 제공되는 모든 정보입니다. 이 필드는 선택사항입니다. documentation 객체에는 다음이 포함됩니다.
    • content: 알림 본문에 표시되는 사용자 정의 텍스트입니다.
    • subject: 알림의 제목입니다. 제목은 255자(영문 기준)로 제한됩니다.
  • userLabels: 정책에 연결된 사용자 정의 라벨입니다. 알림과 함께 라벨 사용에 대한 자세한 내용은 라벨로 알림에 주석 추가를 참조하세요.
  • conditions[]: Condition 구조의 배열입니다.
  • combiner: 여러 조건을 처리하는 방법을 결정하는 논리적 연산자입니다.
  • notificationChannels[]: 각각 NotificationChannel을 식별하는 리소스 이름의 배열입니다.
  • alertStrategy: 데이터 수신이 중지될 때 Monitoring이 이슈를 얼마나 빠르게 닫는지를 지정합니다. 이 객체는 또한 측정항목 기반 알림에 대해 반복 알림이 사용 설정되었는지 여부와 이러한 알림 사이의 간격을 지정합니다. 자세한 내용은 반복 알림 전송을 참조하세요.

또한 Cloud Monitoring API 및 Google Cloud 콘솔을 사용할 때 severity 필드를 지정할 수 있습니다. 이 필드를 사용하면 이슈의 심각도 수준을 정의할 수 있습니다. 심각도를 지정하지 않으면 Cloud Monitoring이 알림 정책 심각도를 No Severity로 설정합니다.

만드는 조건에 따라 다른 필드를 사용할 수 있습니다.

알림 정책에 하나의 조건이 포함된 경우 해당 조건이 충족될 때 알림이 전송됩니다. 알림 정책에 여러 조건이 포함된 경우의 알림에 대한 자세한 내용은 여러 조건이 포함된 정책정책당 알림 수를 참조하세요.

알림 정책을 만들거나 수정할 때 Monitoring은 name 필드를 포함한 다른 필드도 설정합니다. name 필드의 값은 정책을 식별하는 알림 정책의 리소스 이름입니다. 리소스 이름은 다음 형식을 갖습니다.

projects/PROJECT_ID/alertPolicies/POLICY_ID

API에서 조건의 유형

Cloud Monitoring API는 Condition 구조에서 다양한 조건 유형을 지원합니다. 측정항목 기준 알림 정책에는 여러 조건 유형이 있고 로그 기준 알림 정책에는 하나의 유형이 있습니다. 다음 섹션에서는 사용 가능한 조건 유형을 설명합니다.

측정항목 기준 알림 정책의 조건

로그 기준 측정항목을 포함하여 측정항목 데이터를 모니터링하는 알림 정책을 만들려면 다음 조건 유형을 사용할 수 있습니다.

필터 기준 측정항목 조건

MetricAbsenceMetricThreshold 조건은 모니터링 필터를 사용하여 모니터링할 시계열 데이터를 선택합니다. 조건 구조의 다른 필드는 데이터 필터링, 그룹화 및 집계 방법을 지정합니다. 이러한 개념들에 대한 자세한 내용은 필터링 및 집계: 시계열 조작을 참조하세요.

MetricAbsence 조건 유형을 사용하는 경우 모든 시계열이 없을 때만 충족되는 조건을 만들 수 있습니다. 이 조건은 aggregations 매개변수를 사용하여 여러 시계열을 단일 시계열로 집계합니다. 자세한 내용은 API 문서의 MetricAbsence 참조를 확인하세요.

측정항목 부재 알림 정책을 사용하려면 일부 데이터가 이전에 기록되어 있어야 합니다. 자세한 내용은 측정항목 부재 알림 정책 만들기를 참조하세요.

예측 값을 기준으로 알림을 받으려면 MetricThreshold 조건 유형을 사용하고 forecastOptions 필드를 설정하도록 알림 정책을 구성합니다. 이 필드가 설정되지 않으면 측정된 데이터를 기준점과 비교합니다. 하지만 이 필드가 설정되었으면 예측 데이터를 기준점과 비교합니다. 자세한 내용은 예측된 측정항목 값 알림 정책 만들기를 참조하세요.

MQL 기준 측정항목 조건

MonitoringQueryLanguageCondition 조건은 Monitoring 쿼리 언어(MQL)를 사용하여 모니터링할 시계열 데이터를 선택하고 조작합니다. 값을 기준점과 비교하거나 이 조건 유형의 값 부재를 테스트하는 알림 정책을 만들 수 있습니다. MonitoringQueryLanguageCondition 조건을 사용할 경우 알림 정책에서 유일한 조건이어야 합니다. 자세한 내용은 MQL을 사용한 알림 정책을 참조하세요.

PromQL 기반 측정항목 조건

PrometheusQueryLanguageCondition 조건은 Prometheus 쿼리 언어(PromQL) 쿼리를 사용하여 모니터링할 시계열 데이터를 선택하고 조작합니다. 단순 또는 복잡한 쿼리를 만들고 동적 기준, 비율, 측정항목 비교 등의 쿼리 구조를 사용할 수 있습니다.

PrometheusQueryLanguageCondition 조건을 사용할 경우 알림 정책에서 유일한 조건이어야 합니다. 자세한 내용은 PromQL을 사용한 알림 정책을 참조하세요.

비율 알림 조건

두 가지 측정항목의 비율을 모니터링하도록 측정항목 임곗값 알림 정책을 만들 수 있습니다. MetricThreshold 또는 MonitoringQueryLanguageCondition 조건 유형을 사용하여 이러한 정책을 만들 수 있습니다. 또한 Google Cloud Console에서 직접 MQL을 사용할 수 있습니다. 임곗값 조건을 만들기 위한 그래픽 인터페이스를 사용하여 역할 기준 조건을 만들거나 관리할 수 없습니다.

MQL을 사용하여 비율 기준 알림 정책을 만드는 것이 좋습니다. MQL을 사용하면 MetricTheshold 조건 유형 및 모니터링 필터를 사용하여 빌드할 수 있는 것보다 더 강력하고 더 유연한 쿼리를 빌드할 수 있습니다. 예를 들어 MonitoringQueryLanguageCondition 조건의 경우 델타 측정항목에 대한 게이지 측정항목의 비율을 계산할 수 있습니다. 예시를 보려면 MQL 알림 정책 예시를 참조하세요.

MetricThreshold 조건을 사용하는 경우 해당 비율의 분자 및 분모가 모두 동일한 MetricKind를 가져야 합니다. 측정항목 및 해당 속성의 목록은 측정항목 목록을 참조하세요.

일반적으로 라벨 값을 사용하여 단일 측정항목 유형에 대해 수집된 시계열을 기준으로 비율을 계산하는 것이 가장 좋습니다. 서로 다른 두 측정항목 유형에서 계산되는 비율에는 샘플링 기간 및 정렬 기간의 차이로 인한 문제점이 나타날 수 있습니다.

예를 들어 두 가지 측정항목 유형, RPC 총 개수와 RPC 오류 개수가 있고 총 RPC에 대한 오류 개수 RPC의 비율을 계산한다고 가정해 보겠습니다. 실패한 RPC는 두 측정항목 유형 모두의 시계열에 포함됩니다. 따라서 시계열을 정렬할 때 두 시계열 모두 동일한 정렬 간격으로 실패한 RPC가 표시되지 않을 수 있습니다. 이러한 차이는 다음과 같은 여러 이유로 발생할 수 있습니다.

  • 동일한 이벤트를 기록하는 서로 다른 시계열이 두 개 있으므로 컬렉션을 구현하는 두 가지 기본 카운터 값이 있게 되고 원자적으로 업데이트되지 않습니다.
  • 샘플링 레이트는 다를 수 있습니다. 시계열이 공통 기간으로 정렬되면 단일 이벤트에 대한 이벤트 수가 서로 다른 측정항목의 시계열에 가까운 정렬 간격으로 표시될 수 있습니다.

해당 정렬 간격의 값 수에 차이가 있으면 1/0 또는 2/1과 같은 무의미한 error/total 비율 값이 발생할 수 있습니다.

비율에 사용되는 숫자가 클수록 무의미한 값이 나올 가능성이 낮습니다. 샘플링 기간보다 긴 정렬 기간을 사용하거나 특정 라벨의 데이터를 그룹화하여 집계하면 더 큰 숫자를 사용할 수 있습니다. 이러한 기법은 특정 간격의 포인트 수에 미치는 작은 차이의 영향을 최소화합니다. 즉, 간격의 예상 포인트 수가 300인 경우보다 3일 경우 2점 차이가 더 중요합니다.

기본 제공 측정항목 유형을 사용하는 경우 필요한 값을 얻기 위해 측정항목 유형 전반에서 비율을 계산해야 할 수도 있습니다.

두 개의 서로 다른 측정항목에서 RPC에서 오류 상태를 반환하는 RPC와 같이 같은 항목을 계산할 수 있는 커스텀 측정항목을 설계하는 경우 각 측정항목이 한 번만 포함된 단일 측정항목을 사용하는 것이 좋습니다. 예를 들어 RPC를 계산 중이고 모든 RPC에 대한 실패한 RPC 비율을 추적한다고 가정해보세요. 이 문제를 해결하려면 RPC를 계산하도록 단일 측정항목 유형을 만들고 라벨을 사용해서 'OK' 상태를 포함해서 호출 상태를 기록합니다. 그런 다음 각 상태 값 오류 또는 'OK'가 해당 사례에 대한 단일 카운터를 업데이트하여 기록됩니다.

로그 기준 알림 정책 조건

필터와 일치하는 메시지가 로그 항목에 표시될 때 알림을 제공하는 로그 기준 알림 정책을 만들려면 LogMatch 조건 유형을 사용합니다. LogMatch 조건을 사용할 경우 알림 정책에서 유일한 조건이어야 합니다.

LogMatch 조건 유형을 로그 기준 측정항목과 함께 사용하지 마세요. 로그 기준 측정항목을 모니터링하는 알림 정책은 측정항목 기준 정책입니다. 로그 기준 측정항목 또는 로그 항목을 모니터링하는 알림 정책 선택에 대한 자세한 내용은 로그 모니터링을 참조하세요.

로그 기준 알림 정책에서도 원칙은 동일하지만, API를 통한 알림 정책 관리 문서의 예시에 사용되는 알림 정책은 측정항목 기준 알림 정책입니다. 로그 기준 알림 정책 관련 정보는 Cloud Logging 문서의 Monitoring API를 사용하여 로그 기준 알림 만들기를 참조하세요.

시작하기 전에

다음은 API를 활용하는 코드 작성 시 사전 요구 사항입니다.

  • 알림 정책에 사용되는 일반적인 개념과 용어를 익혀야 합니다. 자세한 내용은 알림 개요를 참조하세요.
  • Cloud Monitoring API가 사용 설정되었는지 확인합니다. 자세한 내용은 API 사용 설정을 참조하세요.
  • 클라이언트 라이브러리를 사용하려면 사용하려는 언어의 라이브러리를 설치합니다. 자세한 내용은 클라이언트 라이브러리를 참조하세요. 현재 API의 알림 지원은 C#, Go, 자바, Node.js, Python에만 사용할 수 있습니다.
  • Google Cloud CLI를 사용하려면 이를 설치합니다. 하지만 Cloud Shell을 사용하는 경우 Google Cloud CLI가 이미 설치되어 있습니다.

    gcloud 인터페이스의 사용 예도 여기에 나와 있습니다. gcloud 예시에서는 현재 프로젝트가 이미 대상(gcloud config set project [PROJECT_ID])으로 설정되어 있다고 가정하므로 호출 시 명시적 --project 플래그가 생략됩니다. 예시에서 현재 프로젝트의 ID는 a-gcp-project입니다.

  • Cloud Monitoring API를 사용하여 알림 정책을 만들고 수정하는 데 필요한 권한을 얻으려면 관리자에게 프로젝트에 대한 모니터링 경고 정책 편집자(roles/monitoring.alertPolicyEditor) IAM 역할을 부여해 달라고 요청하세요. 역할 부여에 대한 자세한 내용은 액세스 관리를 참조하세요.

    커스텀 역할이나 다른 사전 정의된 역할을 통해 필요한 권한을 얻을 수도 있습니다.

    Monitoring의 IAM 역할에 대한 자세한 내용은 Identity and Access Management로 액세스 제어를 참조하세요.

  • Google Cloud 프로젝트에서 알림 정책 상태를 수정하는 단일 스레드 Cloud Monitoring API 호출로 실행하도록 애플리케이션을 설계합니다. 예를 들어 알림 정책을 만들고, 업데이트, 삭제하는 단일 스레드 API 호출이 있습니다.

알림 정책 만들기

프로젝트에서 알림 정책을 만들려면 alertPolicies.create 메서드를 사용합니다. 이 메서드, 해당 매개변수, 응답 데이터를 호출하는 방법은 참조 페이지 alertPolicies.create를 확인하세요.

JSON 또는 YAML 파일에서 정책을 만들 수 있습니다. Google Cloud CLI는 이러한 파일을 인수로 수락합니다. 사용자는 프로그래매틱 방식으로 JSON 파일을 읽고, AlertPolicy 객체로 변환하고, alertPolicies.create 메서드를 사용해서 이로부터 정책을 만들 수 있습니다. 알림 규칙이 포함된 Prometheus JSON 또는 YAML 구성 파일이 있으면 gcloud CLI가 PromQL 조건을 사용하여 Cloud Monitoring 알림 정책으로 마이그레이션할 수 있습니다. 자세한 내용은 Prometheus에서 알림 규칙 및 수신자 마이그레이션을 참조하세요.

각 알림 정책은 측정항목 범위의 범위 지정 프로젝트에 속합니다. 각 프로젝트는 최대 500개까지 정책을 포함할 수 있습니다. API 호출의 경우 '프로젝트 ID'를 제공하고, 측정항목 범위의 범위 지정 프로젝트의 ID를 값으로 사용해야 합니다. 이 예시에서 측정항목 범위의 범위 지정 프로젝트의 ID는 a-gcp-project입니다.

다음 샘플에서는 알림 정책 생성을 보여주지만 알림 정책을 설명하는 JSON 또는 YAML 파일을 만드는 방법을 설명하지 않습니다. 대신 샘플에서는 JSON 형식의 파일이 있다고 가정하고 API 호출을 실행하는 방법을 보여줍니다. JSON 파일의 예시는 샘플 정책을 참조하세요. 측정항목 비율 모니터링에 대한 일반적인 내용은 측정항목 비율을 참조하세요.

gcloud

프로젝트에서 알림 정책을 만들려면 gcloud alpha monitoring policies create 명령어를 실행합니다. 다음 예시에서는 rising-cpu-usage.json 파일로 a-gcp-project에 알림 정책을 만듭니다.

gcloud alpha monitoring policies create --policy-from-file="rising-cpu-usage.json"

성공할 경우 이 명령어는 다음과 같은 새 정책의 이름을 반환합니다.

Created alert policy [projects/a-gcp-project/alertPolicies/12669073143329903307].

rising-cpu-usage.json 파일에는 표시 이름이 'High CPU rate of change'인 정책의 JSON이 들어 있습니다. 이 정책에 대한 자세한 내용은 변경률 정책을 참조하세요.

자세한 내용은 gcloud alpha monitoring policies create 참조를 확인하세요.

C#

Monitoring에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

static void RestorePolicies(string projectId, string filePath)
{
    var policyClient = AlertPolicyServiceClient.Create();
    var channelClient = NotificationChannelServiceClient.Create();
    List<Exception> exceptions = new List<Exception>();
    var backup = JsonConvert.DeserializeObject<BackupRecord>(
        File.ReadAllText(filePath), new ProtoMessageConverter());
    var projectName = new ProjectName(projectId);
    bool isSameProject = projectId == backup.ProjectId;
    // When a channel is recreated, rather than updated, it will get
    // a new name.  We have to update the AlertPolicy with the new
    // name.  Track the names in this map.
    var channelNameMap = new Dictionary<string, string>();
    foreach (NotificationChannel channel in backup.Channels)
    {
    }
    foreach (AlertPolicy policy in backup.Policies)
    {
        string policyName = policy.Name;
        // These two fields cannot be set directly, so clear them.
        policy.CreationRecord = null;
        policy.MutationRecord = null;
        // Update channel names if the channel was recreated with
        // another name.
        for (int i = 0; i < policy.NotificationChannels.Count; ++i)
        {
            if (channelNameMap.ContainsKey(policy.NotificationChannels[i]))
            {
                policy.NotificationChannels[i] =
                    channelNameMap[policy.NotificationChannels[i]];
            }
        }
        try
        {
            Console.WriteLine("Updating policy.\n{0}",
                policy.DisplayName);
            bool updated = false;
            if (isSameProject)
                try
                {
                    policyClient.UpdateAlertPolicy(null, policy);
                    updated = true;
                }
                catch (Grpc.Core.RpcException e)
                when (e.Status.StatusCode == StatusCode.NotFound)
                { }
            if (!updated)
            {
                // The policy no longer exists.  Recreate it.
                policy.Name = null;
                foreach (var condition in policy.Conditions)
                {
                    condition.Name = null;
                }
                policyClient.CreateAlertPolicy(projectName, policy);
            }
            Console.WriteLine("Restored {0}.", policyName);
        }
        catch (Exception e)
        {
            // If one failed, continue trying to update the others.
            exceptions.Add(e);
        }
    }
    if (exceptions.Count > 0)
    {
        throw new AggregateException(exceptions);
    }
}

Go

Monitoring에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


// restorePolicies updates the project with the alert policies and
// notification channels in r.
func restorePolicies(w io.Writer, projectID string, r io.Reader) error {
	b := backup{}
	if err := json.NewDecoder(r).Decode(&b); err != nil {
		return err
	}
	sameProject := projectID == b.ProjectID

	ctx := context.Background()

	alertClient, err := monitoring.NewAlertPolicyClient(ctx)
	if err != nil {
		return err
	}
	defer alertClient.Close()
	channelClient, err := monitoring.NewNotificationChannelClient(ctx)
	if err != nil {
		return err
	}
	defer channelClient.Close()

	// When a channel is recreated, rather than updated, it will get
	// a new name.  We have to update the AlertPolicy with the new
	// name.  channelNames keeps track of the new names.
	channelNames := make(map[string]string)
	for _, c := range b.Channels {
		fmt.Fprintf(w, "Updating channel %q\n", c.GetDisplayName())
		c.VerificationStatus = monitoringpb.NotificationChannel_VERIFICATION_STATUS_UNSPECIFIED
		updated := false
		if sameProject {
			req := &monitoringpb.UpdateNotificationChannelRequest{
				NotificationChannel: c.NotificationChannel,
			}
			_, err := channelClient.UpdateNotificationChannel(ctx, req)
			if err == nil {
				updated = true
			}
		}
		if !updated {
			req := &monitoringpb.CreateNotificationChannelRequest{
				Name:                "projects/" + projectID,
				NotificationChannel: c.NotificationChannel,
			}
			oldName := c.GetName()
			c.Name = ""
			newC, err := channelClient.CreateNotificationChannel(ctx, req)
			if err != nil {
				return err
			}
			channelNames[oldName] = newC.GetName()
		}
	}

	for _, policy := range b.AlertPolicies {
		fmt.Fprintf(w, "Updating alert %q\n", policy.GetDisplayName())
		policy.CreationRecord = nil
		policy.MutationRecord = nil
		for i, aChannel := range policy.GetNotificationChannels() {
			if c, ok := channelNames[aChannel]; ok {
				policy.NotificationChannels[i] = c
			}
		}
		updated := false
		if sameProject {
			req := &monitoringpb.UpdateAlertPolicyRequest{
				AlertPolicy: policy.AlertPolicy,
			}
			_, err := alertClient.UpdateAlertPolicy(ctx, req)
			if err == nil {
				updated = true
			}
		}
		if !updated {
			req := &monitoringpb.CreateAlertPolicyRequest{
				Name:        "projects/" + projectID,
				AlertPolicy: policy.AlertPolicy,
			}
			if _, err = alertClient.CreateAlertPolicy(ctx, req); err != nil {
				log.Fatal(err)
			}
		}
	}
	fmt.Fprintf(w, "Successfully restored alerts.")
	return nil
}

Java

Monitoring에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

private static void restoreRevisedPolicies(
    String projectId, boolean isSameProject, List<AlertPolicy> policies) throws IOException {
  try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) {
    for (AlertPolicy policy : policies) {
      if (!isSameProject) {
        policy = client.createAlertPolicy(ProjectName.of(projectId), policy);
      } else {
        try {
          client.updateAlertPolicy(null, policy);
        } catch (Exception e) {
          policy =
              client.createAlertPolicy(
                  ProjectName.of(projectId), policy.toBuilder().clearName().build());
        }
      }
      System.out.println(String.format("Restored %s", policy.getName()));
    }
  }
}

Node.js

Monitoring에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

const fs = require('fs');

// Imports the Google Cloud client library
const monitoring = require('@google-cloud/monitoring');

// Creates a client
const client = new monitoring.AlertPolicyServiceClient();

async function restorePolicies() {
  // Note: The policies are restored one at a time due to limitations in
  // the API. Otherwise, you may receive a 'service unavailable'  error
  // while trying to create multiple alerts simultaneously.

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';

  console.log('Loading policies from ./policies_backup.json');
  const fileContent = fs.readFileSync('./policies_backup.json', 'utf-8');
  const policies = JSON.parse(fileContent);

  for (const index in policies) {
    // Restore each policy one at a time
    let policy = policies[index];
    if (await doesAlertPolicyExist(policy.name)) {
      policy = await client.updateAlertPolicy({
        alertPolicy: policy,
      });
    } else {
      // Clear away output-only fields
      delete policy.name;
      delete policy.creationRecord;
      delete policy.mutationRecord;
      policy.conditions.forEach(condition => delete condition.name);

      policy = await client.createAlertPolicy({
        name: client.projectPath(projectId),
        alertPolicy: policy,
      });
    }

    console.log(`Restored ${policy[0].name}.`);
  }
  async function doesAlertPolicyExist(name) {
    try {
      const [policy] = await client.getAlertPolicy({
        name,
      });
      return policy ? true : false;
    } catch (err) {
      if (err && err.code === 5) {
        // Error code 5 comes from the google.rpc.code.NOT_FOUND protobuf
        return false;
      }
      throw err;
    }
  }
}
restorePolicies();

PHP

Monitoring에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

use Google\Cloud\Monitoring\V3\AlertPolicy;
use Google\Cloud\Monitoring\V3\AlertPolicy\Condition;
use Google\Cloud\Monitoring\V3\AlertPolicy\Condition\MetricThreshold;
use Google\Cloud\Monitoring\V3\AlertPolicy\ConditionCombinerType;
use Google\Cloud\Monitoring\V3\Client\AlertPolicyServiceClient;
use Google\Cloud\Monitoring\V3\ComparisonType;
use Google\Cloud\Monitoring\V3\CreateAlertPolicyRequest;
use Google\Protobuf\Duration;

/**
 * @param string $projectId Your project ID
 */
function alert_create_policy($projectId)
{
    $alertClient = new AlertPolicyServiceClient([
        'projectId' => $projectId,
    ]);
    $projectName = 'projects/' . $projectId;

    $policy = new AlertPolicy();
    $policy->setDisplayName('Test Alert Policy');
    $policy->setCombiner(ConditionCombinerType::PBOR);
    /** @see https://cloud.google.com/monitoring/api/resources for a list of resource.type */
    /** @see https://cloud.google.com/monitoring/api/metrics_gcp for a list of metric.type */
    $policy->setConditions([new Condition([
        'display_name' => 'condition-1',
        'condition_threshold' => new MetricThreshold([
            'filter' => 'resource.type = "gce_instance" AND metric.type = "compute.googleapis.com/instance/cpu/utilization"',
            'duration' => new Duration(['seconds' => '60']),
            'comparison' => ComparisonType::COMPARISON_LT,
        ])
    ])]);
    $createAlertPolicyRequest = (new CreateAlertPolicyRequest())
        ->setName($projectName)
        ->setAlertPolicy($policy);

    $policy = $alertClient->createAlertPolicy($createAlertPolicyRequest);
    printf('Created alert policy %s' . PHP_EOL, $policy->getName());
}

Python

Monitoring에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

def restore(project_name, backup_filename):
    """Restore alert policies in a project.

    Arguments:
        project_name (str): The Google Cloud Project to use. The project name
            must be in the format - 'projects/<PROJECT_NAME>'.
        backup_filename (str): Name of the file (along with its path) from
            which the alert policies will be restored.
    """
    print(
        "Loading alert policies and notification channels from {}.".format(
            backup_filename
        )
    )
    record = json.load(open(backup_filename, "rt"))
    is_same_project = project_name == record["project_name"]
    # Convert dicts to AlertPolicies.
    policies_json = [json.dumps(policy) for policy in record["policies"]]
    policies = [
        monitoring_v3.AlertPolicy.from_json(policy_json)
        for policy_json in policies_json
    ]
    # Convert dicts to NotificationChannels
    channels_json = [json.dumps(channel) for channel in record["channels"]]
    channels = [
        monitoring_v3.NotificationChannel.from_json(channel_json)
        for channel_json in channels_json
    ]

    # Restore the channels.
    channel_client = monitoring_v3.NotificationChannelServiceClient()
    channel_name_map = {}

    for channel in channels:
        updated = False
        print("Updating channel", channel.display_name)
        # This field is immutable and it is illegal to specify a
        # non-default value (UNVERIFIED or VERIFIED) in the
        # Create() or Update() operations.
        channel.verification_status = (
            monitoring_v3.NotificationChannel.VerificationStatus.VERIFICATION_STATUS_UNSPECIFIED
        )

        if is_same_project:
            try:
                channel_client.update_notification_channel(notification_channel=channel)
                updated = True
            except google.api_core.exceptions.NotFound:
                pass  # The channel was deleted.  Create it below.

        if not updated:
            # The channel no longer exists.  Recreate it.
            old_name = channel.name
            del channel.name
            new_channel = channel_client.create_notification_channel(
                name=project_name, notification_channel=channel
            )
            channel_name_map[old_name] = new_channel.name

    # Restore the alerts
    alert_client = monitoring_v3.AlertPolicyServiceClient()

    for policy in policies:
        print("Updating policy", policy.display_name)
        # These two fields cannot be set directly, so clear them.
        del policy.creation_record
        del policy.mutation_record

        # Update old channel names with new channel names.
        for i, channel in enumerate(policy.notification_channels):
            new_channel = channel_name_map.get(channel)
            if new_channel:
                policy.notification_channels[i] = new_channel

        updated = False

        if is_same_project:
            try:
                alert_client.update_alert_policy(alert_policy=policy)
                updated = True
            except google.api_core.exceptions.NotFound:
                pass  # The policy was deleted.  Create it below.
            except google.api_core.exceptions.InvalidArgument:
                # Annoying that API throws InvalidArgument when the policy
                # does not exist.  Seems like it should throw NotFound.
                pass  # The policy was deleted.  Create it below.

        if not updated:
            # The policy no longer exists.  Recreate it.
            old_name = policy.name
            del policy.name
            for condition in policy.conditions:
                del condition.name
            policy = alert_client.create_alert_policy(
                name=project_name, alert_policy=policy
            )
        print("Updated", policy.name)

생성된 AlertPolicy 객체에는 추가 필드가 있습니다. 정책 자체에는 name, creationRecord, mutationRecord 필드가 포함됩니다. 또한 정책의 각 조건에도 name이 제공됩니다. 이러한 필드는 외부에서 수정할 수 없으므로 정책을 만들 때 필드를 설정할 필요가 없습니다. 정책 만들기에 사용되는 JSON 예에는 이러한 필드가 포함되어 있지 않습니다. 그러나 생성 후 이러한 필드에서 생성된 정책이 검색될 경우 필드가 존재하게 됩니다.

다음 단계