透過 API 建立及管理通知管道

您可以使用 Cloud Monitoring API 和 Google Cloud CLI,以程式輔助方式建立及管理通知管道。當警告政策觸發時,Cloud Monitoring 會透過這些管道通知您或待命團隊。使用用戶端程式庫或 Google Cloud CLI,從內建通知管道描述元建立通知管道,然後在快訊政策中參照這些管道。

如要在 Google Cloud 控制台中設定通知管道,請參閱「建立及管理通知管道」。本文中的程式碼範例來自「範例:備份及還原」中的警報政策 API 範例。

關於 API

NotificationChannel 資源支援可管理通知管道的作業。此外,這個程式庫也支援與管理頻道 verificationStatus 欄位相關的作業:

  • 傳送驗證碼
  • 產生驗證碼來將已驗證之管道的驗證狀態,複製到同一專案或新專案中的其他相同管道
  • 使用前兩項作業建立的驗證碼來驗證管道

詳情請參閱 notificationChannels 參考文件。

限制

  • 已淘汰的管道類型:campfire 和 hipchat 管道類型已淘汰。請勿建立這類新管道。
  • Pub/Sub 訊息儲存政策:如果您為 Pub/Sub 主題設定訊息儲存政策或資料落地限制,Monitoring 可能就無法發布至該主題。詳情請參閱「FAILED_PRECONDITION 錯誤」。
  • 並行 API 呼叫:設計應用程式時,請務必從單一執行緒呼叫 Cloud Monitoring API,以便在 Google Cloud 專案中建立、修改或刪除通知管道。

事前準備

  • 如要取得透過 Cloud Monitoring API 查看及設定通知管道所需的權限,請要求管理員授予您專案的「Monitoring NotificationChannel Editor」 (roles/monitoring.notificationChannelEditor) IAM 角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

    您或許也能透過自訂角色或其他預先定義的角色,取得必要權限。

    如要進一步瞭解 Cloud Monitoring 角色,請參閱「使用 Identity and Access Management 控制存取權」一文。

  • 選取這個頁面上您打算如何使用���例的分頁:

    gcloud

    在 Google Cloud 控制台中啟用 Cloud Shell。

    啟用 Cloud Shell

    Google Cloud 控制台底部會開啟 Cloud Shell 工作階段,並顯示指令列提示。Cloud Shell 是已安裝 Google Cloud CLI 的殼層環境,並已設定適用於您目前專案的值。工作階段可能要幾秒鐘的時間才能初始化。

    C#

    如要在本機開發環境中使用本頁面的 .NET 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

    1. 安裝 Google Cloud CLI。

    2. 如果您使用外部識別資訊提供者 (IdP),請先 使用聯合身分登入 gcloud CLI。

    3. 如果您使用本機殼層,請為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果您使用 Cloud Shell,則不需要執行這項操作。

      如果系統傳回驗證錯誤,且您使用外部識別資訊提供者 (IdP),請確認您已 使用聯合身分登入 gcloud CLI。

    詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

    Go

    如要在本機開發環境中使用本頁的 Go 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

    1. 安裝 Google Cloud CLI。

    2. 如果您使用外部識別資訊提供者 (IdP),請先 使用聯合身分登入 gcloud CLI。

    3. 如果您使用本機殼層,請為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果您使用 Cloud Shell,則不需要執行這項操作。

      如果系統傳回驗證錯誤,且您使用外部識別資訊提供者 (IdP),請確認您已 使用聯合身分登入 gcloud CLI。

    詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

    Java

    如要在本機開發環境中使用本頁的 Java 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

    1. 安裝 Google Cloud CLI。

    2. 如果您使用外部識別資訊提供者 (IdP),請先 使用聯合身分登入 gcloud CLI。

    3. 如果您使用本機殼層,請為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果您使用 Cloud Shell,則不需要執行這項操作。

      如果系統傳回驗證錯誤,且您使用外部識別資訊提供者 (IdP),請確認您已 使用聯合身分登入 gcloud CLI。

    詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

    Node.js

    如要在本機開發環境中使用本頁的 Node.js 範例,請安裝並初始化 gcloud CLI,然後使用您的使用者憑證設定應用程式預設憑證。

    1. 安裝 Google Cloud CLI。

    2. 如果您使用外部識別資訊提供者 (IdP),請先 使用聯合身分登入 gcloud CLI。

    3. 如果您使用本機殼層,請為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果您使用 Cloud Shell,則不需要執行這項操作。

      如果系統傳回驗證錯誤,且您使用外部識別資訊提供者 (IdP),請確認您已 使用聯合身分登入 gcloud CLI。

    詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

    PHP

    如要在本機開發環境中使用本頁的 PHP 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

    1. 安裝 Google Cloud CLI。

    2. 如果您使用外部識別資訊提供者 (IdP),請先 使用聯合身分登入 gcloud CLI。

    3. 如果您使用本機殼層,請為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果您使用 Cloud Shell,則不需要執行這項操作。

      如果系統傳回驗證錯誤,且您使用外部識別資訊提供者 (IdP),請確認您已 使用聯合身分登入 gcloud CLI。

    詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

    Python

    如要在本機開發環境中使用本頁的 Python 範例,請安裝並初始化 gcloud CLI,然後使用您的使用者憑證設定應用程式預設憑證。

    1. 安裝 Google Cloud CLI。

    2. 如果您使用外部識別資訊提供者 (IdP),請先 使用聯合身分登入 gcloud CLI。

    3. 如果您使用本機殼層,請為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果您使用 Cloud Shell,則不需要執行這項操作。

      如果系統傳回驗證錯誤,且您使用外部識別資訊提供者 (IdP),請確認您已 使用聯合身分登入 gcloud CLI。

    詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

  • 如果您打算使用 Google Cloud CLI,請設定預設專案:

    gcloud config set project PROJECT_ID
    

    執行上一個指令前,請先替換下列項目:

    • PROJECT_ID:專案的 ID。如要進行 App Hub 設定,請選取 App Hub 主專案或管理專案。

列出通知管道類型

Monitoring 提供多種內建通知管道類型。這些型別都會在 NotificationChannelDescriptor 中說明。每個描述元都有 type 欄位,您建立管道執行個體時,該欄位的值會識別管道類型。如要使用 Cloud Monitoring API 或 Google Cloud CLI 擷取可建立的管道類型清單,請輸入下列指令:

$ gcloud beta monitoring channel-descriptors list --format='value(type)'
campfire
email
google_chat
hipchat
pagerduty
pubsub
slack
sms
webhook_basicauth
webhook_tokenauth

如果系統不支援您偏好的通知管道,建議您建立管道,將通知傳送至 Pub/Sub。如需使用 Flask 的 Python 範例,請參閱「使用 Cloud Monitoring 和 Cloud Run 建立自訂通知」。如需其他範例,請參閱 cloud-alerting-notification-forwarding Git 存放區。

列出所有頻道類型

如要擷取 Google Cloud 專案中的所有管道描述元,請使用 gcloud beta monitoring channel-descriptors list 指令或 notificationChannelDescriptors.list API 方法。 擷取的描述元為唯讀。

gcloud beta monitoring channel-descriptors list

成功後,list 指���會列出指定專案中的所有管道描述元。舉例來說,email 管道描述元會顯示在清單中,如下所示:

---
description: A channel that sends notifications via email.
displayName: Email
labels:
- description: An address to send email.
  key: email_address
name: projects/[PROJECT_ID]/notificationChannelDescriptors/email
type: email
---

所有管道描述元都包含下列欄位:

  • name:管道描述元的完整資源名稱。
  • type:名稱中表示管道類型的部分。
  • displayName:type 欄位的說明,用於顯示。
  • description:頻道的簡短說明。
  • labels:一組特定於管道類型的欄位。每種管道類型都有一組專屬標籤。

建立管道時,系統也會提供 enabled 欄位,預設值為 true。

列出特定頻道類型

如要尋找特定描述元並知道其名稱,請使用 gcloud beta monitoring channel-descriptors describe 或 notificationChannelDescriptors.get API 方法。頻道描述元的名稱格式為 projects/[PROJECT_ID]/notificationChannelDescriptors/[CHANNEL_TYPE]。[CHANNEL_TYPE] 必須是先前列出的其中一種類型。例如:

gcloud beta monitoring channel-descriptors describe email

gcloud beta monitoring channel-descriptors describe projects/[PROJECT_ID]/notificationChannelDescriptors/email

詳情請參閱 gcloud beta monitoring channel-descriptors list 和 describe 參考資料。describe 指令與 API 中的 notificationChannelDescriptors.get 方法對應。

建立通知管道

您可以使用 Google Cloud CLI,從 JSON 或 YAML 檔案為 Google Cloud 專案建立通知管道,也可以透過程式輔助方式建立通知管道。

如要建立通知管道,您必須提供描述元內的欄位值。其中大部分 (例如 type) 在所有通知管道描述元中都很常見;請參閱 notificationChannelDescriptors。

每個描述元也包含標籤組合,這個組合會因描述元而不盡相同。如要查看特定描述元的標籤集,請使用「列出通知管道類型」一節所述的 gcloud beta monitoring channel-descriptors describe 指令,擷取描述元。舉例來說,擷取 email 管道描述元會顯示單一標籤:

    labels:
    - description: An address to send email.
      key: email_address

pubsub 管道描述元也包含單一標籤,該標籤會識別 Pub/Sub 主題。不過,頻道可以包含多個標籤。舉例來說,slack 管道描述元有兩個標籤:

    labels:
    - description: A permanent authentication token provided by Slack. This field is obfuscated by returning only a few characters of the key when fetched.
      key: auth_token
    - description: The Slack channel to which to post notifications.
      key: channel_name

擷取 webhook_basicauth 管道描述元會顯示多個標籤:

    labels:
    - description: The password. The field is obfuscated when the channel is fetched.
      key: password
    - description: The public URL to which to publish the webhook.
      key: url
    - description: The username.
      key: username

無論是以程式輔助方式或從指令列建立新管道,規格中的 type 值都必須與對應通知管道描述元的 type 欄位相符。任何必要的標籤鍵也都必須與管道描述元中的標籤鍵相符。

部分標籤對應於向供應商驗證時使用的憑證。 建立頻道時,這些標籤的值必須由供應商提供。取得憑證可能需要使用供應商網站上的 API 金鑰產生頁面,或完成供應商的 OAuth 登入流程。如何取得這類憑證,取決於特定供應商。

頻道預設為啟用。如要建立非使用中的管道,可以加入 enabled 欄位,並將值設為 false。

下列範例說明如何建立通知管道。

範例:使用 gcloud CLI 建立 Pub/Sub 通知管道

如要在 Google Cloud 專案中建立通知管道,請使用 gcloud beta monitoring channels create 指令。如要從檔案載入管道,請使用 --channel-content-from-file 旗標指定檔案。

舉例來說,以下 JSON 顯示新 pubsub 通知管道的規格:

    {
      "type": "pubsub",
      "displayName": "Notifications",
      "description": "Pub/Sub channel for notifications",
      "labels": {
        "topic": "projects/[PROJECT_ID]/topics/notificationTopic"
      },
    }

type 值 (pubsub) 和單一標籤鍵 (topic) 與對應頻道描述元中的 type 和 labels.key 欄位相符。

以下範例會從 pubsub-channel.json 檔案建立新的 Pub/Sub 管道:

gcloud beta monitoring channels create --channel-content-from-file="pubsub-channel.json"

如果成功,這項指令會傳回新頻道的名稱。例如:

Created notification channel [projects/[PROJECT_ID]/notificationChannels/1355376463305411567].

建立pubsub通知管道時,請務必授權通知服務帳戶發布至主題。另請注意,如果主題設有訊息儲存政策或資料駐留限制,監控功能可能無法發布至該主題;請參閱 FAILED_PRECONDITION 錯誤。

範例:使用用戶端程式庫建立通知管道

以下範例說明如何使用用戶端程式庫建立通知管道:

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)
    {
    }
    if (exceptions.Count > 0)
    {
        throw new AggregateException(exceptions);
    }
}

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

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

PHP

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

use Google\Cloud\Monitoring\V3\Client\NotificationChannelServiceClient;
use Google\Cloud\Monitoring\V3\CreateNotificationChannelRequest;
use Google\Cloud\Monitoring\V3\NotificationChannel;

/**
 * @param string $projectId Your project ID
 */
function alert_create_channel(string $projectId): void
{
    $channelClient = new NotificationChannelServiceClient([
        'projectId' => $projectId,
    ]);
    $projectName = 'projects/' . $projectId;

    $channel = new NotificationChannel();
    $channel->setDisplayName('Test Notification Channel');
    $channel->setType('email');
    $channel->setLabels(['email_address' => 'fake@example.com']);
    $createNotificationChannelRequest = (new CreateNotificationChannelRequest())
        ->setName($projectName)
        ->setNotificationChannel($channel);

    $channel = $channelClient->createNotificationChannel($createNotificationChannelRequest);
    printf('Created notification channel %s' . PHP_EOL, $channel->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)

範例:建立 Slack 通知管道

如要為 Slack 應用程式設定通知管道,請按照下列步驟操作:

  1. 設定 Slack 應用程式:

    1. 如果還沒有 Slack 應用程式,請按照 Slack 參考文件建立應用程式,並安裝至工作區。
    2. 為 Slack 應用程式設定 OAuth 範圍,包�� chat:write 和 chat:write.public。
    3. 複製應用程式的 Bot 使用者 OAuth 權杖。
  2. 建立定義通知管道設定的檔案。 加入標籤,其中 auth_token 鍵的值為 Slack 應用程式的機器人使用者 OAuth 權杖。例如:

    {
      "description": "A Slack notification channel",
      "displayName": "Slack",
      "type": "slack",
      "enabled": true,
      "labels": {
        "auth_token": "OAUTH_TOKEN_VALUE",
        "channel_name": "SLACK_CHANNEL_NAME"
      }
    }
    
  3. 執行下列指令來建立通知管道:

    gcloud beta monitoring channels create --channel-content-from-file="FILE_NAME"
    

列出專案中的通知管道

如要擷取 Google Cloud 專案中的所有通知管道,請使用 notificationChannels.list 方法。這個方法也支援以 filter 和 orderBy 選項來限制及排序結果;詳情請參閱「排序與篩選」。

如要尋找特定頻道,且知道該頻道的名稱,可以使用 notificationChannels.get 方法只擷取該頻道。頻道名稱的格式為 projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID],例如:

    projects/[PROJECT_ID]/notificationChannels/1355376463305411567

當您擷取管道時,像驗證憑證與 API 金鑰這一類敏感值可能會基於安全理由��模糊處理。 如果您要透過複製現有管道的方式來建立新管道,任何模糊處理的值都需要修正。

gcloud

如要列出 Google Cloud 專案中的所有通知管道,請使用 gcloud beta monitoring channels list 指令:

gcloud beta monitoring channels list

如果成功,list 指令會列出指定專案中的所有管道。舉例來說,上述指令可能會傳回包含下列項目的清單:

    ---
    description: E-mail channel created by gcloud as a test
    displayName: test e-mail channel
    enabled: false
    labels:
      email_address: user@example.com
    name: projects/[PROJECT_ID]/notificationChannels/1355376463305411567
    type: email
    ---
    description: Pub/Sub channel for notifications
    displayName: Notifications
    enabled: true
    labels:
      topic: projects/[PROJECT_ID]/topics/notificationTopic
    name: projects/[PROJECT_ID]/notificationChannels/1355376463305411567
    type: pubsub

如要改為列出單一頻道,請使用 gcloud beta monitoring channels describe 並指定頻道名稱。舉例來說,這個指令會傳回前一個清單中顯示的 Pub/Sub 管道:

gcloud beta monitoring channels describe projects/[PROJECT_ID]/notificationChannels/1355376463305411567

詳情請參閱 gcloud beta monitoring channels list 和 describe 參考資料。describe 指令與 API 中的 notificationChannels.get 方法對應。

C#

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

static void ListNotificationChannels(string projectId)
{
    var client = NotificationChannelServiceClient.Create();
    var response = client.ListNotificationChannels(new ProjectName(projectId));
    foreach (NotificationChannel channel in response)
    {
        Console.WriteLine(channel.Name);
        if (channel.DisplayName != null)
        {
            Console.WriteLine(channel.DisplayName);
        }
        Console.WriteLine();
    }
}

Node.js

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


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

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

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

  const request = {
    name: client.projectPath(projectId),
    filter,
  };
  const channels = await client.listNotificationChannels(request);
  console.log(channels);
  for (const channel of channels[0]) {
    console.log(`Deleting channel ${channel.displayName}`);
    try {
      await client.deleteNotificationChannel({
        name: channel.name,
      });
    } catch (err) {
      // ignore error
    }
  }
}
deleteChannels();

Go

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

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

Java

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

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

PHP

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

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

/**
 * @param string $projectId Your project ID
 */
function alert_list_channels($projectId)
{
    $projectName = 'projects/' . $projectId;
    $channelClient = new NotificationChannelServiceClient([
        'projectId' => $projectId,
    ]);
    $listNotificationChannelsRequest = (new ListNotificationChannelsRequest())
        ->setName($projectName);

    $channels = $channelClient->listNotificationChannels($listNotificationChannelsRequest);
    foreach ($channels->iterateAllElements() as $channel) {
        printf('Name: %s (%s)' . PHP_EOL, $channel->getDisplayName(), $channel->getName());
    }
}

Python

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

def list_notification_channels(project_name):
    """List alert notification channels 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.NotificationChannelServiceClient()
    channels = client.list_notification_channels(name=project_name)
    print(
        tabulate.tabulate(
            [(channel.name, channel.display_name) for channel in channels],
            ("name", "display_name"),
        )
    )

從專案中刪除通知管道

如要從 Google Cloud 專案中刪除通知管道,請使用 notificationChannels.delete 方法,並提供要刪除的通知管道名稱。頻道的名稱是 NotificationChannel 例項中的 name 欄位值,而非 displayName。頻道名稱的格式為 projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID],例如:

    projects/[PROJECT_ID]/notificationChannels/1355376463305411567

根據預設,如果您嘗試刪除警告政策參照的管道,系統不會刪除該管道。如要強制從警告政策中移除參照並刪除管道,請將 force 選項設為 true。這個選項會自動從所有參照政策中移除管道。

gcloud

如要刪除通知管道,請使用 gcloud beta monitoring channels delete 並指定要刪除的管道名稱。舉例來說,下列指令會刪除在另一個範例中建立的 email 管道:

gcloud beta monitoring channels delete projects/[PROJECT_ID]/notificationChannels/1355376463305411567

詳情請參閱gcloud beta monitoring channels delete參考資料。

C#

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


using Google.Cloud.Monitoring.V3;
using System;

partial class AlertSnippets
{
    public void DeleteNotificationChannel(
        string channelName = "projects/your-project-id/notificationChannels/123")
    {
        var client = NotificationChannelServiceClient.Create();
        client.DeleteNotificationChannel(
            name: NotificationChannelName.Parse(channelName),
            force: true);
        Console.WriteLine("Deleted {0}.", channelName);
    }
}

Go

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


import (
	"context"
	"fmt"
	"io"

	monitoring "cloud.google.com/go/monitoring/apiv3"
	"cloud.google.com/go/monitoring/apiv3/v2/monitoringpb"
)

// deleteChannel deletes the given channel. channelName should be of the form
// "projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]".
func deleteChannel(w io.Writer, channelName string) error {
	ctx := context.Background()

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

	req := &monitoringpb.DeleteNotificationChannelRequest{
		Name: channelName,
	}

	if err := client.DeleteNotificationChannel(ctx, req); err != nil {
		return fmt.Errorf("DeleteNotificationChannel: %w", err)
	}

	fmt.Fprintf(w, "Deleted channel %q", channelName)
	return nil
}

Java

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

static void deleteNotificationChannel(String channelName) throws IOException {
  String projectId = System.getProperty("projectId");
  try (NotificationChannelServiceClient client = NotificationChannelServiceClient.create()) {
    NotificationChannelName name = NotificationChannelName.of(projectId, channelName);
    client.deleteNotificationChannel(channelName, false);
    System.out.println("Deleted notification channel " + channelName);
  }
}

PHP

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

use Google\Cloud\Monitoring\V3\Client\NotificationChannelServiceClient;
use Google\Cloud\Monitoring\V3\DeleteNotificationChannelRequest;

/**
 * @param string $projectId Your project ID
 * @param string $channelId
 */
function alert_delete_channel(string $projectId, string $channelId): void
{
    $channelClient = new NotificationChannelServiceClient([
        'projectId' => $projectId,
    ]);
    $channelName = $channelClient->notificationChannelName($projectId, $channelId);
    $deleteNotificationChannelRequest = (new DeleteNotificationChannelRequest())
        ->setName($channelName);

    $channelClient->deleteNotificationChannel($deleteNotificationChannelRequest);
    printf('Deleted notification channel %s' . PHP_EOL, $channelName);
}

Node.js

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


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

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

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

  const request = {
    name: client.projectPath(projectId),
    filter,
  };
  const channels = await client.listNotificationChannels(request);
  console.log(channels);
  for (const channel of channels[0]) {
    console.log(`Deleting channel ${channel.displayName}`);
    try {
      await client.deleteNotificationChannel({
        name: channel.name,
      });
    } catch (err) {
      // ignore error
    }
  }
}
deleteChannels();

Python

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

def delete_notification_channels(project_name, channel_ids, force=None):
    """Delete alert notification channels.

    Arguments:
        project_name (str): The Google Cloud Project to use. The project name
            must be in the format - 'projects/<PROJECT_NAME>'.
        channel_ids list(str): List of IDs of notification channels to delete.
        force (bool): If true, the notification channels are deleted regardless
            of its in use by alert policies. If false, channels that are still
            referenced by an existing alerting policy will fail to be deleted.
    """

    channel_client = monitoring_v3.NotificationChannelServiceClient()
    for channel_id in channel_ids:
        channel_name = "{}/notificationChannels/{}".format(project_name, channel_id)
        try:
            channel_client.delete_notification_channel(name=channel_name, force=force)
            print("Channel {} deleted".format(channel_name))
        except ValueError:
            print("The parameters are invalid")
        except Exception as e:
            print("API call failed: {}".format(e))

修改通知管道

如要修改通知管道,請使用 notificationChannels.patch 方法 (在 REST API 中)。其他 API 實作項目和 Google Cloud CLI 會呼叫 update,而不是 patch。

更新作業可以完全取代現有管道,也可以修改欄位子集。例如,您可以啟用及停用頻道。 停用管道後,系統就不會再透過該管道傳送通知。 如果變更只是暫時性的,停用管道通常會比從參照該管道的警告政策中移除管道更方便。

gcloud

如要啟用已停用的通知管道,請使用 gcloud beta monitoring channels update 指令並提供 --enabled 旗標。下列指令會啟用先前範例中建立的 email 通知管道 (處於停用狀態):

gcloud beta monitoring channels update projects/[PROJECT_ID]/notificationChannels/1355376463305411567 --enabled

如要停用通知管道,請使用相同指令並提供 --no-enabled 旗標。詳情請參閱 gcloud beta monitoring channels update 參考資料。update 指令與 REST API 中的 notificationChannels.patch 方法對應。

C#

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


using Google.Cloud.Monitoring.V3;
using Google.Protobuf.WellKnownTypes;
using System;

partial class AlertSnippets
{
    public NotificationChannel EnableNotificationChannel(
        string channelName = "projects/your-project-id/notificationChannels/123")
    {
        var client = NotificationChannelServiceClient.Create();
        NotificationChannel channel = new NotificationChannel();
        channel.Enabled = true;
        channel.Name = channelName;
        var fieldMask = new FieldMask { Paths = { "enabled" } };
        channel = client.UpdateNotificationChannel(
            updateMask: fieldMask,
            notificationChannel: channel);
        Console.WriteLine("Enabled {0}.", channel.Name);
        return channel;
    }
}

Go

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


import (
	"context"
	"fmt"
	"io"

	monitoring "cloud.google.com/go/monitoring/apiv3"
	"cloud.google.com/go/monitoring/apiv3/v2/monitoringpb"
	"github.com/golang/protobuf/ptypes/wrappers"
	"google.golang.org/genproto/protobuf/field_mask"
)

// enableChannel enables the given channel. channelName should be of the form
// "projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]".
func enableChannel(w io.Writer, channelName string) error {
	ctx := context.Background()

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

	req := &monitoringpb.UpdateNotificationChannelRequest{
		UpdateMask: &field_mask.FieldMask{Paths: []string{"enabled"}},
		NotificationChannel: &monitoringpb.NotificationChannel{
			Name:    channelName,
			Enabled: &wrappers.BoolValue{Value: true},
		},
	}

	if _, err := client.UpdateNotificationChannel(ctx, req); err != nil {
		return fmt.Errorf("EnableNotificationChannel: %w", err)
	}

	fmt.Fprintf(w, "Enabled channel %q", channelName)
	return nil
}

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

Java

如要向 Monitoring 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

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

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)

查看通知管道記錄

您可以使用 Logs Explorer 查看通知管道錯誤:

  1. 前往 Google Cloud 控制台的 「Logs Explorer」頁面:

    前往「Logs Explorer」(記錄檔探索工具)

    如果您是使用搜尋列尋找這個頁面,請選取子標題為「Logging」的結果。

  2. 輸入並執行查詢。如要查詢通知管道錯誤相關資訊,請參閱「Cloud Monitoring 查詢」。