API를 통한 알림 정책 관리

이 문서에서는 Cloud Monitoring API를 사용하여 측정항목 기반의 알림 정책을 프로그래매틱 방식으로 만들고, 수정, 삭제, 나열, 가져오는 방법을 설명합니다. 이 예시에서는 Google Cloud CLI를 사용하고 클라이언트 라이브러리를 사용하는 방법을 보여줍니다. 이 콘텐츠는 로그 기준 알림 정책에 적용되지 않습니다. 로그 기준 알림 정책에 대한 자세한 내용은 로그 모니터링을 참조하세요.

Google Cloud 콘솔을 사용하여 이 태스크를 수행할 수도 있습니다. 자세한 내용은 다음 문서를 참조하세요.

알림 정책 정보

알림 정책은 AlertPolicy 객체로 표현됩니다. 이 객체는 시스템의 비정상 상태를 나타내는 조건 집합을 설명합니다. 알림 정책은 알림 정책이 트리거되었다는 통지를 받을 방법을 지정할 수 있는 알림 채널을 참조합니다.

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

AlertPolicy 리소스는 다음 5개 작업을 지원합니다.

  • 새 정책 만들기
  • 기존 정책 삭제
  • 특정 정책 검색
  • 모든 정책 검색
  • 기존 정책 수정

알림 정책을 JSON 또는 YAML로 표현할 수 있습니다. 이를 통해 파일에 정책을 기록하고 파일을 사용하여 정책을 백업하고 복원할 수 있습니다. Google Cloud CLI를 사용하면 둘 중 어느 형식의 파일에서도 정책을 만들 수 있습니다. REST API를 사용하면 JSON 파일에서 정책을 만들 수 있습니다. JSON 형식의 알림 정책을 선택하려면 샘플 정책을 참조하세요.

다음 예시에서는 gcloud 인터페이스와 API를 사용하여 이러한 기본 사용 사례를 보여줍니다. API를 사용하여 알림 정책을 위한 백업 및 복원 시스템을 구현하는 샘플 프로그램에서 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에서 알림 규칙 및 수신자 마이그레이션을 참조하세요.

다음 샘플에서는 알림 정책 생성을 보여주지만 알림 정책을 설명하는 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 예에는 이러한 필드가 포함되어 있지 않습니다. 그러나 생성 후 이러한 필드에서 생성된 정책이 검색될 경우 필드가 존재하게 됩니다.

알림 정책 나열 및 가져오기

프로젝트의 정책 목록을 검색하려면 alertPolicies.list 메서드를 사용합니다. 이 메서드를 사용하여 정책을 검색하고, 백업 등의 조치를 각 정책에 적용합니다. 또한 이 메서드는 결과를 제한하고 정렬하는 filterorderBy 옵션을 지원합니다. 자세한 내용은 정렬 및 필터링하기를 참조하세요.

특정 정책을 찾고 있는 경우 정책 이름을 알면 alertPolicies.get 메서드를 사용하여 해당 정책만 검색할 수 있습니다. 정책 이름은 displayName이 아닌 AlertPolicy 객체의 name 필드 값 입니다. 정책 이름은 projects/[PROJECT_ID]/alertPolicies/[POLICY_ID] 형식입니다. 예를 들면 다음과 같습니다.

projects/a-gcp-project/alertPolicies/12669073143329903307

gcloud

프로젝트의 모든 알림 정책을 나열하려면 gcloud alpha monitoring policies list 명령어를 사용합니다.

gcloud alpha monitoring policies list

성공하면 list 명령어가 지정된 프로젝트의 전체 정책 목록을 YAML 형식으로 제공합니다. 예를 들어, 프로젝트 a-gcp-project에 있는 표시 이름 'High CPU rate of change'의 정책이 다른 정책과 함께 다음과 같이 나열됩니다.

---
combiner: OR
conditions:
- conditionThreshold:
    aggregations:
    - alignmentPeriod: 900s
      perSeriesAligner: ALIGN_PERCENT_CHANGE
    comparison: COMPARISON_GT
    duration: 180s
    filter: metric.type="compute.googleapis.com/instance/cpu/utilization" AND resource.type="gce_instance"
    thresholdValue: 0.5
    trigger:
      count: 1
  displayName: CPU usage is increasing at a high rate
  name: projects/a-gcp-project/alertPolicies/12669073143329903307/conditions/12669073143329903008
creationRecord:
  mutateTime: '2018-03-26T18:52:39.363601689Z'
  mutatedBy: [USER@DOMAIN]
displayName: High CPU rate of change
enabled: true
mutationRecord:
  mutateTime: '2018-03-26T18:52:39.363601689Z'
  mutatedBy: [USER@DOMAIN]
name: projects/a-gcp-project/alertPolicies/12669073143329903307
---

단일 알림 정책을 나열하려면 대신 gcloud alpha monitoring policies describe를 사용하고 정책 이름을 지정합니다. 예를 들어 이 명령어로는 위의 목록만 반환됩니다.

gcloud alpha monitoring policies describe projects/a-gcp-project/alertPolicies/12669073143329903307

자세한 내용은 gcloud alpha monitoring policies listdescribe 참조를 확인하세요. describe 명령어는 API의 alertPolicies.get 메서드에 해당합니다.

C#

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

static void ListAlertPolicies(string projectId)
{
    var client = AlertPolicyServiceClient.Create();
    var response = client.ListAlertPolicies(new ProjectName(projectId));
    foreach (AlertPolicy policy in response)
    {
        Console.WriteLine(policy.Name);
        if (policy.DisplayName != null)
        {
            Console.WriteLine(policy.DisplayName);
        }
        if (policy.Documentation?.Content != null)
        {
            Console.WriteLine(policy.Documentation.Content);
        }
        Console.WriteLine();
    }
}

Go

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


// listAlertPolicies lists the alert policies in the project.
func listAlertPolicies(w io.Writer, projectID string) error {
	ctx := context.Background()
	client, err := monitoring.NewAlertPolicyClient(ctx)
	if err != nil {
		return err
	}
	defer client.Close()

	req := &monitoringpb.ListAlertPoliciesRequest{
		Name: "projects/" + projectID,
		// Filter:  "", // See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering.
		// OrderBy: "", // See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering.
	}
	it := client.ListAlertPolicies(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			fmt.Fprintln(w, "Done")
			break
		}
		if err != nil {
			return err
		}
		fmt.Fprintf(w, "  Name: %q\n", resp.GetName())
		fmt.Fprintf(w, "  Display Name: %q\n", resp.GetDisplayName())
		fmt.Fprintf(w, "  Documentation Content: %q\n\n", resp.GetDocumentation().GetContent())
	}
	return nil
}

Java

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

private static void listAlertPolicies(String projectId) throws IOException {
  try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) {
    ListAlertPoliciesPagedResponse response = client.listAlertPolicies(ProjectName.of(projectId));

    System.out.println("Alert Policies:");
    for (AlertPolicy policy : response.iterateAll()) {
      System.out.println(
          String.format("\nPolicy %s\nalert-id: %s", policy.getDisplayName(), policy.getName()));
      int channels = policy.getNotificationChannelsCount();
      if (channels > 0) {
        System.out.println("notification-channels:");
        for (int i = 0; i < channels; i++) {
          System.out.println("\t" + policy.getNotificationChannels(i));
        }
      }
      if (policy.hasDocumentation() && policy.getDocumentation().getContent() != null) {
        System.out.println(policy.getDocumentation().getContent());
      }
    }
  }
}

Node.js

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

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

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

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

  const listAlertPoliciesRequest = {
    name: client.projectPath(projectId),
  };
  const [policies] = await client.listAlertPolicies(listAlertPoliciesRequest);
  console.log('Policies:');
  policies.forEach(policy => {
    console.log(`  Display name: ${policy.displayName}`);
    if (policy.documentation && policy.documentation.content) {
      console.log(`     Documentation: ${policy.documentation.content}`);
    }
  });
}
listPolicies();

PHP

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

use Google\Cloud\Monitoring\V3\Client\AlertPolicyServiceClient;
use Google\Cloud\Monitoring\V3\ListAlertPoliciesRequest;

/**
 * Adds a new column to the Albums table in the example database.
 * Example:
 * ```
 * alert_list_policies($projectId);
 * ```
 *
 * @param string $projectId Your project ID
 */
function alert_list_policies($projectId)
{
    $projectName = 'projects/' . $projectId;
    $alertClient = new AlertPolicyServiceClient([
        'projectId' => $projectId,
    ]);
    $listAlertPoliciesRequest = (new ListAlertPoliciesRequest())
        ->setName($projectName);

    $policies = $alertClient->listAlertPolicies($listAlertPoliciesRequest);
    foreach ($policies->iterateAllElements() as $policy) {
        printf('Name: %s (%s)' . PHP_EOL, $policy->getDisplayName(), $policy->getName());
    }
}

Python

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

def list_alert_policies(project_name):
    """List 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>'.
    """

    client = monitoring_v3.AlertPolicyServiceClient()
    policies = client.list_alert_policies(name=project_name)
    print(
        str(
            tabulate.tabulate(
                [(policy.name, policy.display_name) for policy in policies],
                ("name", "display_name"),
            )
        )
    )

알림 정책 삭제

프로젝트에서 정책을 삭제하려면 alertPolicies.delete 메서드를 사용하고 삭제할 알림 정책의 이름을 제공합니다.

gcloud

알림 정책을 삭제하려면 gcloud alpha monitoring policies delete를 사용하고 삭제할 정책의 이름을 지정합니다. 예를 들어, 다음 명령어는 표시 이름 'High CPU rate of change'와 함께 정책을 삭제합니다.

gcloud alpha monitoring policies delete projects/a-gcp-project/alertPolicies/12669073143329903307

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

알림 정책 수정

알림 정책을 수정하려면 alertPolicies.patch 메서드(REST API)를 사용합니다. 다른 API 구현 및 gcloud 인터페이스는 patch 대신 이 update를 호출합니다.

업데이트 작업으로 기존 정책을 완전히 대체하거나 필드 하위 집합을 수정할 수 있습니다. 업데이트 작업은 새로운 AlertPolicy 객체와 필드 마스크(선택사항)를 사용합니다.

필드 마스크가 지정되면 필드 마스크에 나열된 모든 필드가 제공된 정책의 값으로 업데이트됩니다. 제공된 정책의 필드 마스크에 언급된 필드가 없으면 해당 필드는 지워지고 기본값으로 설정됩니다. 마스크에 나열되지 않은 필드는 이전 값을 유지합니다.

필드 마스크가 지정되지 않으면 기존 정책이 제공된 정책으로 대체되지만 이름(projects/[PROJECT_ID]/alertPolicies/[POLICY_ID])은 재사용됩니다. CONDITION_ID를 포함한 name 값을 가진 새 정책의 모든 조건의 이름이 유지됩니다. 그렇지 않으면 새 조건 및 정책 이름이 생성됩니다.

gcloud 명령줄을 사용하여 정책을 업데이트할 때 필드 마스크가 아닌 명령줄 플래그를 사용하여 업데이트할 필드를 지정합니다. 자세한 내용은 gcloud alpha monitoring policies update를 참조하세요.

알림 정책 사용 설정 또는 중지

정책을 사용 설정하거나 중지하려면 AlertPolicy 객체의 부울 enabled 필드 값을 변경합니다. 정책을 사용 설정한 후에도 중지된 동안 수집된 데이터에 의해 정책이 트리거될 수 있음을 유념하세요.

gcloud

알림 정책을 중지하려면 gcloud alpha monitoring policies update 명령어를 사용하고 --no-enabled 플래그를 제공합니다. 다음 명령어는 프로젝트 a-gcp-project에서 'High CPU rate of change' 알림 정책을 사용 중지합니다.

gcloud alpha monitoring policies update projects/a-gcp-project/alertPolicies/12669073143329903307 --no-enabled

정책을 사용 설정하려면 동일한 명령어를 사용하고 --enabled 플래그를 제공합니다. 자세한 내용은 gcloud alpha monitoring policies update 참조를 확인하세요. update 명령어는 alertPolicies.patch 메서드에 해당합니다.

C#

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

static object EnablePolicies(string projectId, string filter, bool enable)
{
    var client = AlertPolicyServiceClient.Create();
    var request = new ListAlertPoliciesRequest()
    {
        ProjectName = new ProjectName(projectId),
        Filter = filter
    };
    var response = client.ListAlertPolicies(request);
    int result = 0;
    foreach (AlertPolicy policy in response)
    {
        try
        {
            if (policy.Enabled == enable)
            {
                Console.WriteLine("Policy {0} is already {1}.",
                    policy.Name, enable ? "enabled" : "disabled");
                continue;
            }
            policy.Enabled = enable;
            var fieldMask = new FieldMask { Paths = { "enabled" } };
            client.UpdateAlertPolicy(fieldMask, policy);
            Console.WriteLine("{0} {1}.", enable ? "Enabled" : "Disabled",
                policy.Name);
        }
        catch (Grpc.Core.RpcException e)
        when (e.Status.StatusCode == StatusCode.InvalidArgument)
        {
            Console.WriteLine(e.Message);
            result -= 1;
        }
    }
    // Return a negative count of how many enable operations failed.
    return result;
}

Go

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


// enablePolicies enables or disables all alert policies in the project.
func enablePolicies(w io.Writer, projectID string, enable bool) error {
	ctx := context.Background()

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

	req := &monitoringpb.ListAlertPoliciesRequest{
		Name: "projects/" + projectID,
		// Filter:  "", // See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering.
		// OrderBy: "", // See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering.
	}
	it := client.ListAlertPolicies(ctx, req)
	for {
		a, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return err
		}
		if a.GetEnabled().GetValue() == enable {
			fmt.Fprintf(w, "Policy %q already has enabled=%v", a.GetDisplayName(), enable)
			continue
		}
		a.Enabled = &wrappers.BoolValue{Value: enable}
		req := &monitoringpb.UpdateAlertPolicyRequest{
			AlertPolicy: a,
			UpdateMask: &fieldmask.FieldMask{
				Paths: []string{"enabled"},
			},
		}
		if _, err := client.UpdateAlertPolicy(ctx, req); err != nil {
			return err
		}
	}
	fmt.Fprintln(w, "Successfully updated alerts.")
	return nil
}

Java

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

private static void enablePolicies(String projectId, String filter, boolean enable)
    throws IOException {
  try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) {
    ListAlertPoliciesPagedResponse response =
        client.listAlertPolicies(
            ListAlertPoliciesRequest.newBuilder()
                .setName(ProjectName.of(projectId).toString())
                .setFilter(filter)
                .build());

    for (AlertPolicy policy : response.iterateAll()) {
      if (policy.getEnabled().getValue() == enable) {
        System.out.println(
            String.format(
                "Policy %s is already %b.", policy.getName(), enable ? "enabled" : "disabled"));
        continue;
      }
      AlertPolicy updatedPolicy =
          AlertPolicy.newBuilder()
              .setName(policy.getName())
              .setEnabled(BoolValue.newBuilder().setValue(enable))
              .build();
      AlertPolicy result =
          client.updateAlertPolicy(
              FieldMask.newBuilder().addPaths("enabled").build(), updatedPolicy);
      System.out.println(
          String.format(
              "%s %s",
              result.getDisplayName(), result.getEnabled().getValue() ? "enabled" : "disabled"));
    }
  }
}

Node.js

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

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

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

async function enablePolicies() {
  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const enabled = true;
  // const filter = 'A filter for selecting policies, e.g. description:"cloud"';

  const listAlertPoliciesRequest = {
    name: client.projectPath(projectId),
    // See https://cloud.google.com/monitoring/alerting/docs/sorting-and-filtering
    filter: filter,
  };

  const [policies] = await client.listAlertPolicies(listAlertPoliciesRequest);
  const responses = [];
  for (const policy of policies) {
    responses.push(
      await client.updateAlertPolicy({
        updateMask: {
          paths: ['enabled'],
        },
        alertPolicy: {
          name: policy.name,
          enabled: {
            value: enabled,
          },
        },
      })
    );
  }
  responses.forEach(response => {
    const alertPolicy = response[0];
    console.log(`${enabled ? 'Enabled' : 'Disabled'} ${alertPolicy.name}.`);
  });
}
enablePolicies();

PHP

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

use Google\Cloud\Monitoring\V3\Client\AlertPolicyServiceClient;
use Google\Cloud\Monitoring\V3\ListAlertPoliciesRequest;
use Google\Cloud\Monitoring\V3\UpdateAlertPolicyRequest;
use Google\Protobuf\FieldMask;

/**
 * Enable or disable alert policies in a project.
 *
 * @param string $projectId Your project ID
 * @param bool $enable Enable or disable the policies.
 * @param string $filter Only enable/disable alert policies that match a filter.
 *        See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering
 */
function alert_enable_policies($projectId, $enable = true, $filter = null)
{
    $alertClient = new AlertPolicyServiceClient([
        'projectId' => $projectId,
    ]);
    $projectName = 'projects/' . $projectId;
    $listAlertPoliciesRequest = (new ListAlertPoliciesRequest())
        ->setName($projectName)
        ->setFilter($filter);

    $policies = $alertClient->listAlertPolicies($listAlertPoliciesRequest);
    foreach ($policies->iterateAllElements() as $policy) {
        $isEnabled = $policy->getEnabled()->getValue();
        if ($enable == $isEnabled) {
            printf('Policy %s is already %s' . PHP_EOL,
                $policy->getName(),
                $isEnabled ? 'enabled' : 'disabled'
            );
        } else {
            $policy->getEnabled()->setValue((bool) $enable);
            $mask = new FieldMask();
            $mask->setPaths(['enabled']);
            $updateAlertPolicyRequest = (new UpdateAlertPolicyRequest())
                ->setAlertPolicy($policy)
                ->setUpdateMask($mask);
            $alertClient->updateAlertPolicy($updateAlertPolicyRequest);
            printf('%s %s' . PHP_EOL,
                $enable ? 'Enabled' : 'Disabled',
                $policy->getName()
            );
        }
    }
}

Python

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

def enable_alert_policies(project_name, enable, filter_=None):
    """Enable or disable 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>'.
        enable (bool): Enable or disable the policies.
        filter_ (str, optional): Only enable/disable alert policies that match
            this filter_.  See
            https://cloud.google.com/monitoring/api/v3/sorting-and-filtering
    """

    client = monitoring_v3.AlertPolicyServiceClient()
    policies = client.list_alert_policies(
        request={"name": project_name, "filter": filter_}
    )

    for policy in policies:
        if bool(enable) == policy.enabled:
            print(
                "Policy",
                policy.name,
                "is already",
                "enabled" if policy.enabled else "disabled",
            )
        else:
            policy.enabled = bool(enable)
            mask = field_mask.FieldMask()
            mask.paths.append("enabled")
            client.update_alert_policy(alert_policy=policy, update_mask=mask)
            print("Enabled" if enable else "Disabled", policy.name)

알림 정책에서 알림 채널 업데이트

알림 정책에서 참조하는 알림 채널을 업데이트할 수도 있습니다. 알림 정책은 알림 채널을 이름으로 참조합니다. 채널을 알림 정책에 사용하려면 먼저 채널이 존재해야 합니다.

NotificationChannelNotificationChannelDescriptors 리소스를 사용하여 알림 채널을 프로그래매틱 방식으로 만들고 관리합니다. 이 섹션의 다음 예에서는 이러한 채널이 이미 존재한다고 가정하며 이러한 API의 사용은 프로그래매틱 샘플에도 나타납니다.

알림 채널 객체에 대한 자세한 내용은 API를 통해 알림 채널 만들기 및 관리를 참조하세요.

gcloud

알림 정책에서 알림 채널을 수정하려면 gcloud alpha monitoring policies update 명령어를 실행합니다. 알림 채널과 관련된 몇 가지 플래그를 사용하여 알림 채널을 삭제하고 바꾸고 새로 추가할 수 있습니다.

예를 들어, 프로젝트 a-gcp-project에 있는 표시 이름 'High CPU rate of change'의 정책은 알림 채널 없이 생성됩니다.

이 정책에 알림 채널을 추가하려면 gcloud alpha monitoring policies update 명령어를 사용하고 --add-notification-channels 플래그로 추가할 채널을 지정합니다.

gcloud alpha monitoring policies update projects/a-gcp-project/alertPolicies/12669073143329903307 \
--add-notification-channels="projects/a-gcp-project/notificationChannels/1355376463305411567"

자세한 내용은 gcloud alpha monitoring policies update 참조를 확인하세요. update 명령어는 alertPolicies.patch 메서드에 해당합니다.

여기에 추가된 알림 채널이 이미 존재해야 합니다. 자세한 내용은 알림 채널 만들기를 참조하세요.

C#

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

static void ReplaceChannels(string projectId, string alertPolicyId,
    IEnumerable<string> channelIds)
{
    var alertClient = AlertPolicyServiceClient.Create();
    var policy = new AlertPolicy()
    {
        Name = new AlertPolicyName(projectId, alertPolicyId).ToString()
    };
    foreach (string channelId in channelIds)
    {
        policy.NotificationChannels.Add(
            new NotificationChannelName(projectId, channelId)
            .ToString());
    }
    var response = alertClient.UpdateAlertPolicy(
        new FieldMask { Paths = { "notification_channels" } }, policy);
    Console.WriteLine("Updated {0}.", response.Name);
}

Go

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


// replaceChannels replaces the notification channels in the alert policy
// with channelIDs.
func replaceChannels(w io.Writer, projectID, alertPolicyID string, channelIDs []string) error {
	ctx := context.Background()

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

	policy := &monitoringpb.AlertPolicy{
		Name: "projects/" + projectID + "/alertPolicies/" + alertPolicyID,
	}
	for _, c := range channelIDs {
		c = "projects/" + projectID + "/notificationChannels/" + c
		policy.NotificationChannels = append(policy.NotificationChannels, c)
	}
	req := &monitoringpb.UpdateAlertPolicyRequest{
		AlertPolicy: policy,
		UpdateMask: &fieldmask.FieldMask{
			Paths: []string{"notification_channels"},
		},
	}
	if _, err := client.UpdateAlertPolicy(ctx, req); err != nil {
		return fmt.Errorf("UpdateAlertPolicy: %w", err)
	}
	fmt.Fprintf(w, "Successfully replaced channels.")
	return nil
}

Java

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

private static void replaceChannels(String projectId, String alertPolicyId, String[] channelIds)
    throws IOException {
  AlertPolicy.Builder policyBuilder =
      AlertPolicy.newBuilder().setName(AlertPolicyName.of(projectId, alertPolicyId).toString());
  for (String channelId : channelIds) {
    policyBuilder.addNotificationChannels(
        NotificationChannelName.of(projectId, channelId).toString());
  }
  try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) {
    AlertPolicy result =
        client.updateAlertPolicy(
            FieldMask.newBuilder().addPaths("notification_channels").build(),
            policyBuilder.build());
    System.out.println(String.format("Updated %s", result.getName()));
  }
}

Node.js

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


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

// Creates clients
const alertClient = new monitoring.AlertPolicyServiceClient();
const notificationClient = new monitoring.NotificationChannelServiceClient();

async function replaceChannels() {
  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const alertPolicyId = '123456789012314';
  // const channelIds = [
  //   'channel-1',
  //   'channel-2',
  //   'channel-3',
  // ];

  const notificationChannels = channelIds.map(id =>
    notificationClient.projectNotificationChannelPath(projectId, id)
  );

  for (const channel of notificationChannels) {
    const updateChannelRequest = {
      updateMask: {
        paths: ['enabled'],
      },
      notificationChannel: {
        name: channel,
        enabled: {
          value: true,
        },
      },
    };
    try {
      await notificationClient.updateNotificationChannel(
        updateChannelRequest
      );
    } catch (err) {
      const createChannelRequest = {
        notificationChannel: {
          name: channel,
          notificationChannel: {
            type: 'email',
          },
        },
      };
      const newChannel =
        await notificationClient.createNotificationChannel(
          createChannelRequest
        );
      notificationChannels.push(newChannel);
    }
  }

  const updateAlertPolicyRequest = {
    updateMask: {
      paths: ['notification_channels'],
    },
    alertPolicy: {
      name: alertClient.projectAlertPolicyPath(projectId, alertPolicyId),
      notificationChannels: notificationChannels,
    },
  };
  const [alertPolicy] = await alertClient.updateAlertPolicy(
    updateAlertPolicyRequest
  );
  console.log(`Updated ${alertPolicy.name}.`);
}
replaceChannels();

PHP

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

use Google\Cloud\Monitoring\V3\AlertPolicy;
use Google\Cloud\Monitoring\V3\Client\AlertPolicyServiceClient;
use Google\Cloud\Monitoring\V3\Client\NotificationChannelServiceClient;
use Google\Cloud\Monitoring\V3\UpdateAlertPolicyRequest;
use Google\Protobuf\FieldMask;

/**
 * @param string $projectId Your project ID
 * @param string $alertPolicyId Your alert policy id ID
 * @param string[] $channelIds array of channel IDs
 */
function alert_replace_channels(string $projectId, string $alertPolicyId, array $channelIds): void
{
    $alertClient = new AlertPolicyServiceClient([
        'projectId' => $projectId,
    ]);

    $channelClient = new NotificationChannelServiceClient([
        'projectId' => $projectId,
    ]);
    $policy = new AlertPolicy();
    $policy->setName($alertClient->alertPolicyName($projectId, $alertPolicyId));

    $newChannels = [];
    foreach ($channelIds as $channelId) {
        $newChannels[] = $channelClient->notificationChannelName($projectId, $channelId);
    }
    $policy->setNotificationChannels($newChannels);
    $mask = new FieldMask();
    $mask->setPaths(['notification_channels']);
    $updateAlertPolicyRequest = (new UpdateAlertPolicyRequest())
        ->setAlertPolicy($policy)
        ->setUpdateMask($mask);
    $updatedPolicy = $alertClient->updateAlertPolicy($updateAlertPolicyRequest);
    printf('Updated %s' . PHP_EOL, $updatedPolicy->getName());
}

Python

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

def replace_notification_channels(project_name, alert_policy_id, channel_ids):
    """Replace notification channel of an alert.

    Arguments:
        project_name (str): The Google Cloud Project to use. The project name
            must be in the format - 'projects/<PROJECT_NAME>'.
        alert_policy_id (str): The ID of the alert policy whose notification
            channels are to be replaced.
        channel_ids (str): ID of notification channel to be added as channel
            for the given alert policy.
    """

    _, project_id = project_name.split("/")
    alert_client = monitoring_v3.AlertPolicyServiceClient()
    channel_client = monitoring_v3.NotificationChannelServiceClient()
    policy = monitoring_v3.AlertPolicy()
    policy.name = alert_client.alert_policy_path(project_id, alert_policy_id)

    for channel_id in channel_ids:
        policy.notification_channels.append(
            channel_client.notification_channel_path(project_id, channel_id)
        )

    mask = field_mask.FieldMask()
    mask.paths.append("notification_channels")
    updated_policy = alert_client.update_alert_policy(
        alert_policy=policy, update_mask=mask
    )
    print("Updated", updated_policy.name)

알림 정책에서 문서 수정

정책과 관련된 이슈 및 알림과 함께 포함되는 문서가 정책에 있을 수 있습니다. 이 필드를 사용하여 응답자가 알림 정책이 나타내는 문제를 이해하고 처리하는 데 도움이 되는 정보를 포함합니다. 문서는 이를 허용하는 이메일 알림 및 알림 유형에 포함됩니다. 다른 채널 유형에서는 이를 생략할 수 있습니다.

gcloud

정책에 문서를 추가하거나 기존 문서를 바꾸려면 gcloud alpha monitoring policies update 명령어를 사용하고 --documentation-format="text/markdown" 플래그(지원되는 유일한 형식), --documentation 플래그(명령줄에서 값 입력용) 또는 --documentation-from-file 플래그(파일에서 값 읽기용)를 제공합니다.

예를 들어, 프로젝트 a-gcp-project에 있는 표시 이름 'High CPU rate of change'의 정책이 문서 없이 생성됩니다.

다음 명령어는 지정된 정책의 documentation 필드를 cpu-usage-doc.md 파일의 내용으로 설정합니다.

gcloud alpha monitoring policies update projects/a-gcp-project/alertPolicies/12669073143329903307 \
--documentation-format="text/markdown" \
--documentation-from-file="cpu-usage-doc.md"

자세한 내용은 gcloud alpha monitoring policies update 참조를 확인하세요. update 명령어는 alertPolicies.patch 메서드에 해당합니다.

대시보드에 알림 정책 추가

커스텀 대시보드에서 단일 조건 알림 정책의 요약을 표시하려면 AlertChart 위젯을 대시보드에 추가합니다. 새 대시보드에 dashboards.create 메서드를 사용하고 기존 대시보드에는 dashboards.patch 메서드를 사용합니다.

다중 조건 알림 정책을 지정하면 알림 차트에 데이터가 표시되지 않습니다.

이러한 API 메서드 사용에 대한 자세한 내용은 API를 통해 대시보드 만들기 및 관리를 참조하세요.

예시: 백업 및 복원

표시된 모든 API 예는 프로젝트의 알림 정책을 파일로 백업할 수 있는 더 큰 애플리케이션에서 가져온 것이므로 정책을 다른 프로젝트로 복원할 수 있습니다. 백업 및 복원에 사용된 프로젝트가 다른 경우 애플리케이션은 한 프로젝트에서 다른 프로젝트로 정책을 효과적으로 내보내고 가져옵니다.

이 섹션에서는 특정 상황에만 해당하는 소수의 인용문이 아니라 상황별 백업 및 복원용 코드를 보여줍니다.

정책 백업하기

백업 작업은 간단합니다. 각 프로젝트의 알림 정책 집합과 알림 채널 집합이 수집되어 JSON의 외부 저장소에 저장됩니다.

C#

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

        static void BackupPolicies(string projectId, string filePath)
        {
            var policyClient = AlertPolicyServiceClient.Create();
            var channelClient = NotificationChannelServiceClient.Create();
            var projectName = new ProjectName(projectId);
            File.WriteAllText(filePath, JsonConvert.SerializeObject(
                new BackupRecord()
                {
                    ProjectId = projectId,
                    Policies = policyClient.ListAlertPolicies(projectName),
                    Channels = channelClient.ListNotificationChannels(projectName)
                }, new ProtoMessageConverter()));
        }
        class BackupRecord
        {
            public string ProjectId { get; set; }
            public IEnumerable<AlertPolicy> Policies { get; set; }
            public IEnumerable<NotificationChannel> Channels { get; set; }
        }

        /// <summary>
        /// Lets Newtonsoft.Json and Protobuf's json converters play nicely
        /// together.  The default Netwtonsoft.Json Deserialize method will
        /// not correctly deserialize proto messages.
        /// </summary>
        class ProtoMessageConverter : JsonConverter
        {
            public override bool CanConvert(System.Type objectType)
            {
                return typeof(Google.Protobuf.IMessage)
                    .IsAssignableFrom(objectType);
            }

            public override object ReadJson(JsonReader reader,
                System.Type objectType, object existingValue,
                JsonSerializer serializer)
            {
                // Read an entire object from the reader.
                var converter = new ExpandoObjectConverter();
                object o = converter.ReadJson(reader, objectType, existingValue,
                    serializer);
                // Convert it back to json text.
                string text = JsonConvert.SerializeObject(o);
                // And let protobuf's parser parse the text.
                IMessage message = (IMessage)Activator
                    .CreateInstance(objectType);
                return Google.Protobuf.JsonParser.Default.Parse(text,
                    message.Descriptor);
            }

            public override void WriteJson(JsonWriter writer, object value,
                JsonSerializer serializer)
            {
                writer.WriteRawValue(Google.Protobuf.JsonFormatter.Default
                    .Format((IMessage)value));
            }
        }

Go

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


// backupPolicies writes a JSON representation of the project's alert
// policies and notification channels.
func backupPolicies(w io.Writer, projectID string) error {
	b := backup{ProjectID: projectID}
	ctx := context.Background()

	alertClient, err := monitoring.NewAlertPolicyClient(ctx)
	if err != nil {
		return err
	}
	defer alertClient.Close()
	alertReq := &monitoringpb.ListAlertPoliciesRequest{
		Name: "projects/" + projectID,
		// Filter:  "", // See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering.
		// OrderBy: "", // See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering.
	}
	alertIt := alertClient.ListAlertPolicies(ctx, alertReq)
	for {
		resp, err := alertIt.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return err
		}
		b.AlertPolicies = append(b.AlertPolicies, &alertPolicy{resp})
	}

	channelClient, err := monitoring.NewNotificationChannelClient(ctx)
	if err != nil {
		return err
	}
	defer channelClient.Close()
	channelReq := &monitoringpb.ListNotificationChannelsRequest{
		Name: "projects/" + projectID,
		// Filter:  "", // See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering.
		// OrderBy: "", // See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering.
	}
	channelIt := channelClient.ListNotificationChannels(ctx, channelReq)
	for {
		resp, err := channelIt.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return err
		}
		b.Channels = append(b.Channels, &channel{resp})
	}
	bs, err := json.MarshalIndent(b, "", "  ")
	if err != nil {
		return err
	}
	if _, err := w.Write(bs); err != nil {
		return err
	}
	return nil
}

// alertPolicy is a wrapper around the AlertPolicy proto to
// ensure JSON marshaling/unmarshaling works correctly.
type alertPolicy struct {
	*monitoringpb.AlertPolicy
}

// channel is a wrapper around the NotificationChannel proto to
// ensure JSON marshaling/unmarshaling works correctly.
type channel struct {
	*monitoringpb.NotificationChannel
}

// backup is used to backup and restore a project's policies.
type backup struct {
	ProjectID     string
	AlertPolicies []*alertPolicy
	Channels      []*channel
}

func (a *alertPolicy) MarshalJSON() ([]byte, error) {
	m := &jsonpb.Marshaler{EmitDefaults: true}
	b := new(bytes.Buffer)
	m.Marshal(b, a.AlertPolicy)
	return b.Bytes(), nil
}

func (a *alertPolicy) UnmarshalJSON(b []byte) error {
	u := &jsonpb.Unmarshaler{}
	a.AlertPolicy = new(monitoringpb.AlertPolicy)
	return u.Unmarshal(bytes.NewReader(b), a.AlertPolicy)
}

func (c *channel) MarshalJSON() ([]byte, error) {
	m := &jsonpb.Marshaler{}
	b := new(bytes.Buffer)
	m.Marshal(b, c.NotificationChannel)
	return b.Bytes(), nil
}

func (c *channel) UnmarshalJSON(b []byte) error {
	u := &jsonpb.Unmarshaler{}
	c.NotificationChannel = new(monitoringpb.NotificationChannel)
	return u.Unmarshal(bytes.NewReader(b), c.NotificationChannel)
}

Java

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

private static void backupPolicies(String projectId, String filePath) throws IOException {
  List<AlertPolicy> alertPolicies = getAlertPolicies(projectId);
  List<NotificationChannel> notificationChannels = getNotificationChannels(projectId);
  writePoliciesBackupFile(projectId, filePath, alertPolicies, notificationChannels);
  System.out.println(String.format("Saved policies to %s", filePath));
}

private static List<AlertPolicy> getAlertPolicies(String projectId) throws IOException {
  List<AlertPolicy> alertPolicies = Lists.newArrayList();
  try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) {
    ListAlertPoliciesPagedResponse response = client.listAlertPolicies(ProjectName.of(projectId));

    for (AlertPolicy policy : response.iterateAll()) {
      alertPolicies.add(policy);
    }
  }
  return alertPolicies;
}

private static List<NotificationChannel> getNotificationChannels(String projectId)
    throws IOException {
  List<NotificationChannel> notificationChannels = Lists.newArrayList();
  try (NotificationChannelServiceClient client = NotificationChannelServiceClient.create()) {
    ListNotificationChannelsPagedResponse listNotificationChannelsResponse =
        client.listNotificationChannels(ProjectName.of(projectId));
    for (NotificationChannel channel : listNotificationChannelsResponse.iterateAll()) {
      notificationChannels.add(channel);
    }
  }
  return notificationChannels;
}

private static void writePoliciesBackupFile(
    String projectId,
    String filePath,
    List<AlertPolicy> alertPolicies,
    List<NotificationChannel> notificationChannels)
    throws IOException {
  JsonObject backupContents = new JsonObject();
  backupContents.add("project_id", new JsonPrimitive(projectId));
  JsonArray policiesJson = new JsonArray();
  for (AlertPolicy policy : alertPolicies) {
    policiesJson.add(gson.toJsonTree(policy));
  }
  backupContents.add("policies", policiesJson);

  JsonArray notificationsJson = new JsonArray();
  for (NotificationChannel channel : notificationChannels) {
    notificationsJson.add(gson.toJsonTree(channel));
  }
  backupContents.add("notification_channels", notificationsJson);

  FileWriter writer = new FileWriter(filePath);
  writer.write(backupContents.toString());
  writer.close();
}

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 backupPolicies() {
  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';

  const listAlertPoliciesRequest = {
    name: client.projectPath(projectId),
  };

  let [policies] = await client.listAlertPolicies(listAlertPoliciesRequest);

  // filter out any policies created by tests for this sample
  policies = policies.filter(policy => {
    return !policy.displayName.startsWith('gcloud-tests-');
  });

  fs.writeFileSync(
    './policies_backup.json',
    JSON.stringify(policies, null, 2),
    'utf-8'
  );

  console.log('Saved policies to ./policies_backup.json');

PHP

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

use Google\Cloud\Monitoring\V3\Client\AlertPolicyServiceClient;
use Google\Cloud\Monitoring\V3\Client\NotificationChannelServiceClient;
use Google\Cloud\Monitoring\V3\ListAlertPoliciesRequest;
use Google\Cloud\Monitoring\V3\ListNotificationChannelsRequest;

/**
 * Back up alert policies.
 *
 * @param string $projectId Your project ID
 */
function alert_backup_policies($projectId)
{
    $alertClient = new AlertPolicyServiceClient([
        'projectId' => $projectId,
    ]);
    $channelClient = new NotificationChannelServiceClient([
        'projectId' => $projectId,
    ]);
    $projectName = 'projects/' . $projectId;

    $record = [
        'project_name' => $projectName,
        'policies' => [],
        'channels' => [],
    ];
    $listAlertPoliciesRequest = (new ListAlertPoliciesRequest())
        ->setName($projectName);
    $policies = $alertClient->listAlertPolicies($listAlertPoliciesRequest);
    foreach ($policies->iterateAllElements() as $policy) {
        $record['policies'][] = json_decode($policy->serializeToJsonString());
    }
    $listNotificationChannelsRequest = (new ListNotificationChannelsRequest())
        ->setName($projectName);
    $channels = $channelClient->listNotificationChannels($listNotificationChannelsRequest);
    foreach ($channels->iterateAllElements() as $channel) {
        $record['channels'][] = json_decode($channel->serializeToJsonString());
    }
    file_put_contents('backup.json', json_encode($record, JSON_PRETTY_PRINT));
    print('Backed up alert policies and notification channels to backup.json.');
}

Python

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

def backup(project_name, backup_filename):
    """Backup alert policies from a project to a local file.

    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) to which
            the alert policies will be written as backup.
    """

    alert_client = monitoring_v3.AlertPolicyServiceClient()
    channel_client = monitoring_v3.NotificationChannelServiceClient()
    record = {
        "project_name": project_name,
        "policies": list(alert_client.list_alert_policies(name=project_name)),
        "channels": list(channel_client.list_notification_channels(name=project_name)),
    }
    json.dump(record, open(backup_filename, "wt"), cls=ProtoEncoder, indent=2)
    print(
        "Backed up alert policies and notification channels to {}.".format(
            backup_filename
        )
    )

class ProtoEncoder(json.JSONEncoder):
    """Encode protobufs as json."""

    def default(self, obj):
        if type(obj) in (monitoring_v3.AlertPolicy, monitoring_v3.NotificationChannel):
            text = proto.Message.to_json(obj)
            return json.loads(text)
        return super(ProtoEncoder, self).default(obj)

백업한 정책 복원하기

복원 프로세스는 원래 백업보다 더 복잡합니다. 원래 백업한 프로젝트로 복원할 수 있습니다. 또한 다른 프로젝트로 복원하여 효과적으로 알림 정책을 가져올 수 있습니다.

동일한 프로젝트로 복원하는 경우 기존 채널이나 정책이 여전히 존재하면 업데이트되고, 그렇지 않으면 다시 만들어집니다. 백업된 정책의 생성 및 변경 레코드와 같은 읽기 전용 필드는 복원 프로세스에서 정책 및 알림이 다시 만들어지기 전에 지워집니다.

한 프로젝트에 저장된 정책을 사용하여 다른 프로젝트에 새 정책이나 비슷한 정책을 만들 수 있습니다. 하지만 저장된 정책 사본을 다음과 같이 먼저 변경해야 합니다.

  • 알림 채널에서 다음 필드를 삭제합니다.
    • name
    • verificationStatus
  • 알림 채널을 만든 다음 알림 정책에서 채널을 참조합니다. 새 채널 식별자가 있어야 합니다.
  • 다시 만드는 모든 알림 정책에서 다음 필드를 삭제합니다.
    • name
    • condition.name
    • creationRecord
    • mutationRecord

새 프로젝트에서 정책을 다시 만드는 경우 백업된 정책의 조건 이름은 생성 및 변경 레코드와 함께 지워집니다.

또한 다른 프로젝트에 알림 채널을 다시 만들면 다른 이름을 사용하므로 복원 프로세스에서 백업된 알림 정책의 채널 이름을 새 이름으로 매핑하고 이전 이름을 새 이름으로 바꿔야 합니다.

알림 채널의 이름 외에도 채널이 만들어지거나 업데이트될 때 verificationStatus 필드의 값을 설정할 수 없으므로 센티널 값 unspecified가 사용됩니다. 채널이 새 프로젝트로 복원된 후에는 채널을 명시적으로 확인해야 합니다.

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)
            {
                try
                {
                    bool updated = false;
                    Console.WriteLine("Updating channel.\n{0}",
                        channel.DisplayName);
                    // This field is immutable and it is illegal to specify a
                    // non-default value (UNVERIFIED or VERIFIED) in the
                    // Create() or Update() operations.
                    channel.VerificationStatus = NotificationChannel.Types
                        .VerificationStatus.Unspecified;
                    if (isSameProject)
                        try
                        {
                            channelClient.UpdateNotificationChannel(
                                null, channel);
                            updated = true;
                        }
                        catch (Grpc.Core.RpcException e)
                        when (e.Status.StatusCode == StatusCode.NotFound)
                        { }
                    if (!updated)
                    {
                        // The channel no longer exists.  Recreate it.
                        string oldName = channel.Name;
                        channel.Name = null;
                        var response = channelClient.CreateNotificationChannel(
                            projectName, channel);
                        channelNameMap.Add(oldName, response.Name);
                    }
                }
                catch (Exception e)
                {
                    // If one failed, continue trying to update the others.
                    exceptions.Add(e);
                }
            }
            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);
            }
        }

        class BackupRecord
        {
            public string ProjectId { get; set; }
            public IEnumerable<AlertPolicy> Policies { get; set; }
            public IEnumerable<NotificationChannel> Channels { get; set; }
        }

        /// <summary>
        /// Lets Newtonsoft.Json and Protobuf's json converters play nicely
        /// together.  The default Netwtonsoft.Json Deserialize method will
        /// not correctly deserialize proto messages.
        /// </summary>
        class ProtoMessageConverter : JsonConverter
        {
            public override bool CanConvert(System.Type objectType)
            {
                return typeof(Google.Protobuf.IMessage)
                    .IsAssignableFrom(objectType);
            }

            public override object ReadJson(JsonReader reader,
                System.Type objectType, object existingValue,
                JsonSerializer serializer)
            {
                // Read an entire object from the reader.
                var converter = new ExpandoObjectConverter();
                object o = converter.ReadJson(reader, objectType, existingValue,
                    serializer);
                // Convert it back to json text.
                string text = JsonConvert.SerializeObject(o);
                // And let protobuf's parser parse the text.
                IMessage message = (IMessage)Activator
                    .CreateInstance(objectType);
                return Google.Protobuf.JsonParser.Default.Parse(text,
                    message.Descriptor);
            }

            public override void WriteJson(JsonWriter writer, object value,
                JsonSerializer serializer)
            {
                writer.WriteRawValue(Google.Protobuf.JsonFormatter.Default
                    .Format((IMessage)value));
            }
        }

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 restorePolicies(String projectId, String filePath) throws IOException {
  FileReader reader = new FileReader(filePath);
  BufferedReader bufferedReader = new BufferedReader(reader);

  JsonObject backupContent = getPolicyJsonContents(filePath, bufferedReader);
  String backupProjectId = backupContent.get("project_id").getAsString();
  boolean isSameProject = projectId.equals(backupProjectId);

  AlertPolicy[] policies = gson.fromJson(backupContent.get("policies"), AlertPolicy[].class);
  List<NotificationChannel> notificationChannels = readNotificationChannelsJson(backupContent);
  Map<String, String> restoredChannelIds =
      restoreNotificationChannels(projectId, notificationChannels, isSameProject);
  List<AlertPolicy> policiesToRestore =
      reviseRestoredPolicies(policies, isSameProject, restoredChannelIds);

  restoreRevisedPolicies(projectId, isSameProject, policiesToRestore);
}

private static List<AlertPolicy> reviseRestoredPolicies(
    AlertPolicy[] policies, boolean isSameProject, Map<String, String> restoredChannelIds) {
  List<AlertPolicy> newPolicies = Lists.newArrayListWithCapacity(policies.length);
  for (AlertPolicy policy : policies) {
    AlertPolicy.Builder policyBuilder =
        policy
            .toBuilder()
            .clearNotificationChannels()
            .clearMutationRecord()
            .clearCreationRecord();
    // Update restored notification channel names.
    for (String channelName : policy.getNotificationChannelsList()) {
      String newChannelName = restoredChannelIds.get(channelName);
      if (!Strings.isNullOrEmpty(newChannelName)) {
        policyBuilder.addNotificationChannels(newChannelName);
      }
    }
    if (!isSameProject) {
      policyBuilder.clearName();
      policyBuilder.clearConditions();
      for (AlertPolicy.Condition condition : policy.getConditionsList()) {
        policyBuilder.addConditions(condition.toBuilder().clearName());
      }
    }
    newPolicies.add(policyBuilder.build());
  }
  return newPolicies;
}

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()));
    }
  }
}

private static List<NotificationChannel> readNotificationChannelsJson(JsonObject backupContent) {
  if (backupContent.has("notification_channels")) {
    NotificationChannel[] channels =
        gson.fromJson(backupContent.get("notification_channels"), NotificationChannel[].class);
    return Lists.newArrayList(channels);
  }
  return Lists.newArrayList();
}

private static Map<String, String> restoreNotificationChannels(
    String projectId, List<NotificationChannel> channels, boolean isSameProject)
    throws IOException {
  Map<String, String> newChannelNames = Maps.newHashMap();
  try (NotificationChannelServiceClient client = NotificationChannelServiceClient.create()) {
    for (NotificationChannel channel : channels) {
      // Update channel name if project ID is different.
      boolean channelUpdated = false;
      if (isSameProject) {
        try {
          NotificationChannel updatedChannel =
              client.updateNotificationChannel(NOTIFICATION_CHANNEL_UPDATE_MASK, channel);
          newChannelNames.put(channel.getName(), updatedChannel.getName());
          channelUpdated = true;
        } catch (Exception e) {
          channelUpdated = false;
        }
      }
      if (!channelUpdated) {
        NotificationChannel newChannel =
            client.createNotificationChannel(
                ProjectName.of(projectId),
                channel.toBuilder().clearName().clearVerificationStatus().build());
        newChannelNames.put(channel.getName(), newChannel.getName());
      }
    }
  }
  return newChannelNames;
}

private static JsonObject getPolicyJsonContents(String filePath, BufferedReader content) {
  try {
    return gson.fromJson(content, JsonObject.class);
  } catch (JsonSyntaxException jse) {
    throw new RuntimeException(String.format("Could not parse policies file %s", filePath), jse);
  }
}

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\ApiCore\ApiException;
use Google\Cloud\Monitoring\V3\AlertPolicy;
use Google\Cloud\Monitoring\V3\Client\AlertPolicyServiceClient;
use Google\Cloud\Monitoring\V3\Client\NotificationChannelServiceClient;
use Google\Cloud\Monitoring\V3\CreateAlertPolicyRequest;
use Google\Cloud\Monitoring\V3\CreateNotificationChannelRequest;
use Google\Cloud\Monitoring\V3\NotificationChannel;
use Google\Cloud\Monitoring\V3\NotificationChannel\VerificationStatus;
use Google\Cloud\Monitoring\V3\UpdateAlertPolicyRequest;
use Google\Cloud\Monitoring\V3\UpdateNotificationChannelRequest;

/**
 * @param string $projectId Your project ID
 */
function alert_restore_policies(string $projectId): void
{
    $alertClient = new AlertPolicyServiceClient([
        'projectId' => $projectId,
    ]);

    $channelClient = new NotificationChannelServiceClient([
        'projectId' => $projectId,
    ]);

    print('Loading alert policies and notification channels from backup.json.' . PHP_EOL);
    $projectName = 'projects/' . $projectId;
    $record = json_decode((string) file_get_contents('backup.json'), true);
    $isSameProject = $projectName == $record['project_name'];

    # Convert dicts to AlertPolicies.
    $policies = [];
    foreach ($record['policies'] as $policyArray) {
        $policy = new AlertPolicy();
        $policy->mergeFromJsonString((string) json_encode($policyArray));
        $policies[] = $policy;
    }

    # Convert dicts to NotificationChannels
    $channels = [];
    foreach (array_filter($record['channels']) as $channelArray) {
        $channel = new NotificationChannel();
        $channel->mergeFromJsonString((string) json_encode($channelArray));
        $channels[] = $channel;
    }

    # Restore the channels.
    $channelNameMap = [];
    foreach ($channels as $channel) {
        $updated = false;
        printf('Updating channel %s' . PHP_EOL, $channel->getDisplayName());

        # This field is immutable and it is illegal to specify a
        # non-default value (UNVERIFIED or VERIFIED) in the
        # Create() or Update() operations.
        $channel->setVerificationStatus(
            VerificationStatus::VERIFICATION_STATUS_UNSPECIFIED
        );

        if ($isSameProject) {
            try {
                $updateNotificationChannelRequest = (new UpdateNotificationChannelRequest())
                    ->setNotificationChannel($channel);
                $channelClient->updateNotificationChannel($updateNotificationChannelRequest);
                $updated = true;
            } catch (ApiException $e) {
                # The channel was deleted.  Create it below.
                if ($e->getStatus() !== 'NOT_FOUND') {
                    throw $e;
                }
            }
        }

        if (!$updated) {
            # The channel no longer exists.  Recreate it.
            $oldName = $channel->getName();
            $channel->setName('');
            $createNotificationChannelRequest = (new CreateNotificationChannelRequest())
                ->setName($projectName)
                ->setNotificationChannel($channel);
            $newChannel = $channelClient->createNotificationChannel($createNotificationChannelRequest);
            $channelNameMap[$oldName] = $newChannel->getName();
        }
    }

    # Restore the alerts
    foreach ($policies as $policy) {
        printf('Updating policy %s' . PHP_EOL, $policy->getDisplayName());
        # These two fields cannot be set directly, so clear them.
        $policy->clearCreationRecord();
        $policy->clearMutationRecord();

        $notificationChannels = $policy->getNotificationChannels();

        # Update old channel names with new channel names.
        foreach ($notificationChannels as $i => $channel) {
            if (isset($channelNameMap[$channel])) {
                $notificationChannels[$i] = $channelNameMap[$channel];
            }
        }

        $updated = false;
        if ($isSameProject) {
            try {
                $updateAlertPolicyRequest = (new UpdateAlertPolicyRequest())
                    ->setAlertPolicy($policy);
                $alertClient->updateAlertPolicy($updateAlertPolicyRequest);
                $updated = true;
            } catch (ApiException $e) {
                # The policy was deleted.  Create it below.
                if ($e->getStatus() !== 'NOT_FOUND') {
                    throw $e;
                }
            }
        }

        if (!$updated) {
            # The policy no longer exists.  Recreate it.
            $oldName = $policy->getName();
            $policy->setName('');
            foreach ($policy->getConditions() as $condition) {
                $condition->setName('');
            }
            $createAlertPolicyRequest = (new CreateAlertPolicyRequest())
                ->setName($projectName)
                ->setAlertPolicy($policy);
            $policy = $alertClient->createAlertPolicy($createAlertPolicyRequest);
        }
        printf('Updated %s' . PHP_EOL, $policy->getName());
    }
    print('Restored alert policies and notification channels from backup.json.');
}

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)

알림 및 Google Cloud CLI

Google Cloud CLI에서 알림 정책과 알림 채널을 관리하는 명령어 그룹은 알파 출시 버전인 monitoring입니다. monitoring 그룹은 alpha 구성요소에서 사용할 수 있습니다. 즉, 이들 명령어는 모두 다음으로 시작합니다.

gcloud alpha monitoring

alpha 구성요소가 설치되어 있는지 확인하려면 다음 명령어를 실행합니다.

gcloud components list

alpha 구성요소가 설치되어 있지 않으면 다음 명령어를 실행하여 설치하세요.

gcloud components install alpha

alpha 구성요소가 있으면 다음 명령어를 실행하여 monitoring 그룹을 확인합니다.

gcloud alpha monitoring --help

monitoring 그룹이 포함되어 있지 않으면 Google Cloud CLI에서 해당 그룹을 추가하라는 메시지를 표시합니다.

You do not currently have this command group installed.
[...]
Do you want to continue (Y/n)?  y