由 API 管理快訊政策

這個頁面說明如何使用 Stackdriver Monitoring API,以程式化方式建立及管理快訊政策,同時說明如何使用 Cloud SDK 指令列介面管理快訊政策。

這裡的許多工作也可以使用 Stackdriver Monitoring 主控台執行;如需使用 Stackdriver Monitoring 主控台建立及管理快訊政策的說明,請參閱使用快訊政策一文。

事前準備

在針對 API 編寫程式碼之前,您應該先:

  • 擁有一個工作區,監控您想為其建立快訊政策的專案。
  • 熟悉適用於快訊政策的一般概念與術語;詳情請參閱快訊簡介
  • 確保啟用 API 以供使用;詳情請參閱啟用 API
  • 針對您想使用的語言安裝用戶端程式庫;詳情請參閱用戶端程式庫。目前只為 C#、Go、Java、Node.js 與 Python 提供 API 快訊支援。

  • 安裝 Cloud SDK。如此可讓您存取 gcloud 指令列介面,您也可以從這個介面執行這些工作。如果您使用 Cloud Shell,則可以直接使用 Cloud Shell,不用安裝 Cloud SDK。

    這裡還提供了使用 gcloud 介面的範例。請注意,所有 gcloud 範例都假設目前專案已經設定為目標 (gcloud config set project [PROJECT_ID]),因此叫用會省略明確的 --project 標記。範例中目前專案的 ID 為 a-gcp-project

關於快訊政策

快訊政策由 AlertPolicy 物件呈現,說明一組用來指出您系統中可能存在不良健康狀態的條件。快訊政策會參照通知管道,進而讓您指定您想如何收到已觸發快訊政策的通知。

每個快訊政策都屬於個別工作區,且每個工作區都可以包含高達 500 個政策。工作區以其 ID 表示,這個 ID 在參考資源中稱為「專案 ID」。在這些範例中,工作區的 ID 為 a-gcp-project

AlertPolicy 資源支援五項作業:

  • 建立新政策
  • 刪除現有政策
  • 擷取特定政策
  • 擷取所有政策
  • 修改現有政策

快訊政策能夠以 JSON 或 YAML 表示,進而讓您將政策記錄在檔案中,並使用檔案備份及還原政策。使用 Cloud SDK,您可以利用其中任何一種格式的檔案建立政策。使用 REST API,您可以利用 JSON 檔案建立政策。如要選取 JSON 格式的快訊政策,請參閱範例政策一文。

下列範例使用 gcloud 介面與 API 說明這些基本使用案例。API 範例摘自一個範例程式,該程式使用 API 來為快訊政策實作備份與還原系統。如需更完整的範例,請參閱範例:備份與還原一文。

建立政策

如要在專案中建立快訊政策,請使用 alertPolicies.create 方法。

您可以利用 JSON 或 YAML 檔案建立政策,gcloud 指令列介面接受這些檔案做為引數。您可以透過程式讀取 JSON 檔案、將該檔案轉換為 AlertPolicy 物件,並透過 alertPolicies.create 方法來利用這些檔案建立政策。

以下範例說明如何建立快訊政策。

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].

針對顯示名稱為「High CPU rate of change」的政策,rising-cpu-usage.json 檔案中包含 JSON。這個政策在變更頻率政策中有所描述。

詳情請參閱 gcloud alpha monitoring policies create 參考資料。

C#

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

// 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
	}
	channelClient, err := monitoring.NewNotificationChannelClient(ctx)
	if err != nil {
		return err
	}

	// 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

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

const fs = require('fs');

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

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

/**
 * 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;
  }
}

PHP

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

/**
 * @param string $projectId Your project ID
 */
function alert_create_policy($projectId)
{
    $alertClient = new AlertPolicyServiceClient([
        'projectId' => $projectId,
    ]);
    $projectName = $alertClient->projectName($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,
        ])
    ])]);

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

Python

def restore(project_name):
    print('Loading alert policies and notification channels from backup.json.')
    record = json.load(open('backup.json', 'rt'))
    is_same_project = project_name == record['project_name']
    # Convert dicts to AlertPolicies.
    policies_json = [json.dumps(policy) for policy in record['policies']]
    policies = [google.protobuf.json_format.Parse(
        policy_json, monitoring_v3.types.alert_pb2.AlertPolicy())
        for policy_json in policies_json]
    # Convert dicts to NotificationChannels
    channels_json = [json.dumps(channel) for channel in record['channels']]
    channels = [google.protobuf.json_format.Parse(
        channel_json, monitoring_v3.types.notification_pb2.
        NotificationChannel()) 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.enums.NotificationChannel.\
            VerificationStatus.VERIFICATION_STATUS_UNSPECIFIED

        if is_same_project:
            try:
                channel_client.update_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
            channel.ClearField("name")
            new_channel = channel_client.create_notification_channel(
                project_name, 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.
        policy.ClearField('creation_record')
        policy.ClearField('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(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
            policy.ClearField("name")
            for condition in policy.conditions:
                condition.ClearField("name")
            policy = alert_client.create_alert_policy(project_name, policy)
        print('Updated', policy.name)

建立的 AlertPolicy 物件將擁有其他欄位。政策本身將擁有 namecreationRecordmutationRecord 欄位。此外,系統會為政策中的每個條件提供 name。這些欄位無法從外部修改,因此不必在建立政策時設定這些欄位。用於建立政策的所有 JSON 範例都不包含這些欄位,但如果在利用這些欄位建立政策之後擷取政策,這些欄位會顯示出來。

擷取政策

如要在專案中擷取政策的清單,請使用 alertPolicies.list 方法。使用這個方法可以擷取政策並將某項動作套用至其中的每個政策,例如備份政策。這個方法也支援以 filterorderBy 選項來限制及排序結果;詳情請參閱排序與篩選

如果您要尋找特定政策且知道政策名稱,則可以使用 alertPolicies.get 方法只擷取這個政策。在 AlertPolicy 物件中,政策名稱是 name 欄位的值,而不是 displayName 的值。政策名稱的格式為 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」(高 CPU 變更頻率) 的政策會以下列方式列出:

---
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#

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

// 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
	}

	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

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

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

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

/**
 * 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}`);
  }
});

PHP

use Google\Cloud\Monitoring\V3\AlertPolicyServiceClient;

/**
 * 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)
{
    $alertClient = new AlertPolicyServiceClient([
        'projectId' => $projectId,
    ]);

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

Python

def list_alert_policies(project_name):
    client = monitoring_v3.AlertPolicyServiceClient()
    policies = client.list_alert_policies(project_name)
    print(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 介面將此方法稱為 update,而不是 patch

更新作業可以完全取代現有政策,也可以修改欄位子集。更新作業會採用新的 AlertPolicy 物件與選用的欄位遮罩

如果指定欄位遮罩,則列在欄位遮罩中的任何欄位,都會更新為所提供政策中的值。如果提供的政策不包含欄位遮罩中提及的欄位,則會清除該欄位並將其設定為預設值。未列在遮罩中的任何欄位會保留之前的值。

如果未指定欄位遮罩,則會將現有政策取代為提供的政策,但會重複使用名稱 (projects/[PROJECT_ID]/alertPolicies/[POLICY_ID])。新政策中的 name 值包含 CONDITION_ID 的任何條件都會保留這些名稱。若非如此,則會建立新條件與政策名稱。

使用 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 指令與 REST API 中的 alertPolicies.patch 方法對應。

C#

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

// 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
	}

	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

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

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

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

/**
 * 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 tasks = await Promise.all(
  policies
    .map(policy => {
      return {
        updateMask: {paths: ['disabled']},
        alertPolicy: {
          name: policy.name,
          disabled: enabled ? false : true,
        },
      };
    })
    .map(updateAlertPolicyRequest =>
      client.updateAlertPolicy(updateAlertPolicyRequest)
    )
);
tasks.forEach(response => {
  const alertPolicy = response[0];
  console.log(`${enabled ? 'Enabled' : 'Disabled'} ${alertPolicy.name}.`);
});

PHP

use Google\Cloud\Monitoring\V3\AlertPolicyServiceClient;
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 = $alertClient->projectName($projectId);

    $policies = $alertClient->listAlertPolicies($projectName, [
        'filter' => $filter
    ]);
    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']);
            $alertClient->updateAlertPolicy($policy, [
                'updateMask' => $mask
            ]);
            printf('%s %s' . PHP_EOL,
                $enable ? 'Enabled' : 'Disabled',
                $policy->getName()
            );
        }
    }
}

Python

def enable_alert_policies(project_name, enable, filter_=None):
    """Enable or disable alert policies in a project.

    Arguments:
        project_name (str)
        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(project_name, filter_=filter_)

    for policy in policies:
        if bool(enable) == policy.enabled.value:
            print('Policy', policy.name, 'is already',
                  'enabled' if policy.enabled.value else 'disabled')
        else:
            policy.enabled.value = bool(enable)
            mask = monitoring_v3.types.field_mask_pb2.FieldMask()
            mask.paths.append('enabled')
            client.update_alert_policy(policy, 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 指令與 REST API 中的 alertPolicies.patch 方法對應。

在此處新增的通知管道必須已經存在;詳情請參閱建立管道一文。

C#

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

// 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
	}

	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: %v", err)
	}
	fmt.Fprintf(w, "Successfully replaced channels.")
	return nil
}

Java

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

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

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

/**
 * 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.notificationChannelPath(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.alertPolicyPath(projectId, alertPolicyId),
    notificationChannels: notificationChannels,
  },
};
const [alertPolicy] = await alertClient.updateAlertPolicy(
  updateAlertPolicyRequest
);
console.log(`Updated ${alertPolicy.name}.`);

PHP

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

/**
 * @param string $projectId Your project ID
 * @param string $alertPolicyId Your alert policy id ID
 * @param array $channelIds array of channel IDs
 */
function alert_replace_channels($projectId, $alertPolicyId, array $channelIds)
{
    $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']);
    $updatedPolicy = $alertClient->updateAlertPolicy($policy, [
        'updateMask' => $mask,
    ]);
    printf('Updated %s' . PHP_EOL, $updatedPolicy->getName());
}

Python

def replace_notification_channels(project_name, alert_policy_id, channel_ids):
    _, project_id = project_name.split('/')
    alert_client = monitoring_v3.AlertPolicyServiceClient()
    channel_client = monitoring_v3.NotificationChannelServiceClient()
    policy = monitoring_v3.types.alert_pb2.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 = monitoring_v3.types.field_mask_pb2.FieldMask()
    mask.paths.append('notification_channels')
    updated_policy = alert_client.update_alert_policy(policy, 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」(高 CPU 變更頻率) 的政策建立時並沒有說明文件。

下列指令會將指定政策中的 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 指令與 REST API 中的 alertPolicies.patch 方法對應。

範例:備份與還原

顯示的所有 API 範例均提取自較大的應用程式,進而可將專案中的快訊政策備份到檔案中,並在可能的情況下,將政策還原至其他專案。如果用於備份與還原的專案不同,應用程式可在專案之間有效匯出及匯入政策。

本節會將適用於備份與還原的程式碼顯示在背景資訊中,而不是顯示為一組小型的獨立摘錄。

備份政策

備份作業非常簡單。每個專案中的快訊政策集與通知管道集都會以 JSON 格式收集並儲存至外部儲存空間。

C#

        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

// 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
	}
	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
	}
	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

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

const fs = require('fs');

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

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

/**
 * 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

use Google\Cloud\Monitoring\V3\AlertPolicyServiceClient;
use Google\Cloud\Monitoring\V3\NotificationChannelServiceClient;

/**
 * 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 = $alertClient->projectName($projectId);

    $record = [
        'project_name' => $projectName,
        'policies' => [],
        'channels' => [],
    ];
    $policies = $alertClient->listAlertPolicies($projectName);
    foreach ($policies->iterateAllElements() as $policy) {
        $record['policies'][] = json_decode($policy->serializeToJsonString());
    }
    $channels = $channelClient->listNotificationChannels($projectName);
    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

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

class ProtoEncoder(json.JSONEncoder):
    """Uses google.protobuf.json_format to encode protobufs as json."""
    def default(self, obj):
        if type(obj) in (monitoring_v3.types.alert_pb2.AlertPolicy,
                         monitoring_v3.types.notification_pb2.
                         NotificationChannel):
            text = google.protobuf.json_format.MessageToJson(obj)
            return json.loads(text)
        return super(ProtoEncoder, self).default(obj)

還原備份政策

還原程序比原始備份更複雜。您可以還原至最初備份的專案,也可以還原至其他專案,進而有效提供快訊政策的匯入內容。

如果您還原至相同專案,任何現有管道或政策都會更新 (若其仍然存在)。如果不存在,則會重新建立。還原程序會在重新建立政策與通知之前,先清除備份政策中的唯讀欄位 (例如建立和異動記錄)。

您可以利用儲存在某個專案中的政策,在另一個專案中建立全新或類似的政策。但是,您必須在儲存政策的副本中先進行下列變更:

  • 從任何通知管道移除下列欄位:
    • name
    • verificationStatus
  • 建立通知管道,然後在快訊政策中參照這些通知管道 (您需要新的管道 ID)。
  • 從任何重新建立的快訊政策中移除下列欄位:
    • name
    • condition.name
    • creationRecord
    • mutationRecord

此外,如果要在新專案中重新建立政策,備份政策中任何條件的名稱也要與建立和異動記錄一併清除。

另外,在不同專案中重新建立通知管道時,會取得不同名稱,因此還原程序必須將所備份快訊政策中管道的名稱對應至其新名稱,並將舊名稱取代為新名稱。

除了通知管道的名稱以外,建立或更新管道時也無法設定 verificationStatus 欄位的值,所以會使用特殊值 unspecified。在將管道還原至新專案之後,必須對其明確驗證。

C#

        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

// 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
	}
	channelClient, err := monitoring.NewNotificationChannelClient(ctx)
	if err != nil {
		return err
	}

	// 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

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

const fs = require('fs');

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

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

/**
 * 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;
  }
}

PHP

use Google\Cloud\Monitoring\V3\AlertPolicyServiceClient;
use Google\Cloud\Monitoring\V3\NotificationChannelServiceClient;
use Google\Cloud\Monitoring\V3\AlertPolicy;
use Google\Cloud\Monitoring\V3\NotificationChannel;
use Google\Cloud\Monitoring\V3\NotificationChannel\VerificationStatus;
use Google\ApiCore\ApiException;

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

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

    print('Loading alert policies and notification channels from backup.json.' . PHP_EOL);
    $projectName = $alertClient->projectName($projectId);
    $record = json_decode(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(json_encode($policyArray));
        $policies[] = $policy;
    }

    # Convert dicts to NotificationChannels
    $channels = [];
    foreach (array_filter($record['channels']) as $channelArray) {
        $channel = new NotificationChannel();
        $channel->mergeFromJsonString(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 {
                $channelClient->updateNotificationChannel($channel);
                $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('');
            $newChannel = $channelClient->createNotificationChannel(
                $projectName,
                $channel
            );
            $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->setCreationRecord(null);
        $policy->setMutationRecord(null);

        $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 {
                $alertClient->updateAlertPolicy($policy);
                $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('');
            }
            $policy = $alertClient->createAlertPolicy($projectName, $policy);
        }
        printf('Updated %s' . PHP_EOL, $policy->getName());
    }
    print('Restored alert policies and notification channels from backup.json.');
}

Python

def restore(project_name):
    print('Loading alert policies and notification channels from backup.json.')
    record = json.load(open('backup.json', 'rt'))
    is_same_project = project_name == record['project_name']
    # Convert dicts to AlertPolicies.
    policies_json = [json.dumps(policy) for policy in record['policies']]
    policies = [google.protobuf.json_format.Parse(
        policy_json, monitoring_v3.types.alert_pb2.AlertPolicy())
        for policy_json in policies_json]
    # Convert dicts to NotificationChannels
    channels_json = [json.dumps(channel) for channel in record['channels']]
    channels = [google.protobuf.json_format.Parse(
        channel_json, monitoring_v3.types.notification_pb2.
        NotificationChannel()) 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.enums.NotificationChannel.\
            VerificationStatus.VERIFICATION_STATUS_UNSPECIFIED

        if is_same_project:
            try:
                channel_client.update_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
            channel.ClearField("name")
            new_channel = channel_client.create_notification_channel(
                project_name, 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.
        policy.ClearField('creation_record')
        policy.ClearField('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(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
            policy.ClearField("name")
            for condition in policy.conditions:
                condition.ClearField("name")
            policy = alert_client.create_alert_policy(project_name, policy)
        print('Updated', policy.name)

快訊與 Cloud SDK

在 Cloud SDK 中,管理快訊政策與通知管道的指令群組是 monitoring,這是 Alpha 版。monitoring 群組可在 alpha 元件中找到。也就是說,所有這些指令的開頭都是:

gcloud alpha monitoring

如要查看您是否已安裝 alpha 元件,請執行下列指令:

gcloud components list

如果您未安裝 alpha 元件,請執行下列指令來安裝:

gcloud components install alpha

如果您擁有 alpha 元件,請執行下列指令以查看 monitoring 群組:

gcloud alpha monitoring --help

如果未包含 monitoring 群組,Cloud SDK 會提示您新增:

You do not currently have this command group installed.
[...]
Do you want to continue (Y/n)?  y
本頁內容對您是否有任何幫助?請提供意見:

傳送您對下列選項的寶貴意見...

這個網頁
Stackdriver Monitoring
需要協助嗎?請前往我們的支援網頁