Creare e gestire i canali di notifica tramite API

Questo documento descrive come creare e gestire i canali di notifica utilizzando le librerie client o Google Cloud CLI, entrambi i metodi richiamano l'API Cloud Monitoring. Cloud Monitoring utilizza i canali di notifica per avvisarti o avvisare il tuo team di reperibilità quando viene soddisfatta la condizione di un criterio di avviso. Sono disponibili diversi tipi di canali; ognuno è descritto in un descrittore del canale di notifica. Un canale di notifica di un determinato tipo è un'istanza del descrittore di quel tipo. I tuoi criteri di avviso includono riferimenti ai canali di notifica da utilizzare come percorsi di notifica.

Un canale di notifica deve esistere prima di poter essere utilizzato in un criterio di avviso. I descrittori dei canali di notifica ti vengono forniti, ma devi creare i canali prima di poterli utilizzare.

Per configurare i canali di notifica utilizzando la console Google Cloud , consulta Creare e gestire i canali di notifica.

Gli esempi di codice utilizzati in questo documento sono estratti dall'esempio di API alerting-policy, descritto in Esempio: backup e ripristino.

Informazioni sull'API

La risorsa NotificationChannel supporta le operazioni che ti consentono di gestire i canali di notifica. Supporta anche le operazioni relative alla gestione del campo verificationStatus di un canale:

  • Invio di un codice di verifica
  • Generazione di un codice per copiare lo stato di verifica di un canale verificato in altri canali identici nello stesso progetto o in un nuovo progetto
  • Verifica del canale utilizzando il codice creato dalle due operazioni precedenti

Per ulteriori informazioni, consulta i documenti di riferimento notificationChannels.

Prima di iniziare

  • Per ottenere le autorizzazioni necessarie per visualizzare e configurare i canali di notifica utilizzando l'API Cloud Monitoring, chiedi all'amministratore di concederti il ruolo IAM Monitoring NotificationChannel Editor (roles/monitoring.notificationChannelEditor) nel tuo progetto. Per saperne di più sulla concessione dei ruoli, consulta Gestisci l'accesso a progetti, cartelle e organizzazioni.

    Potresti anche riuscire a ottenere le autorizzazioni richieste tramite i ruoli personalizzati o altri ruoli predefiniti.

    Per saperne di più sui ruoli Cloud Monitoring, consulta Controllare l'accesso con Identity and Access Management.

  • Select the tab for how you plan to use the samples on this page:

    gcloud

      In the Google Cloud console, activate Cloud Shell.

      Activate Cloud Shell

      At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

      C#

      Per utilizzare gli esempi di .NET questa pagina in un ambiente di sviluppo locale, installa e inizializza gcloud CLI, quindi configura le Credenziali predefinite dell'applicazione con le tue credenziali utente.

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      Per saperne di più, consulta Configura ADC per un ambiente di sviluppo locale nella documentazione sull'autenticazione Google Cloud .

      Vai

      Per utilizzare gli esempi di Go questa pagina in un ambiente di sviluppo locale, installa e inizializza gcloud CLI, quindi configura le Credenziali predefinite dell'applicazione con le tue credenziali utente.

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      Per saperne di più, consulta Configura ADC per un ambiente di sviluppo locale nella documentazione sull'autenticazione Google Cloud .

      Java

      Per utilizzare gli esempi di Java questa pagina in un ambiente di sviluppo locale, installa e inizializza gcloud CLI, quindi configura le Credenziali predefinite dell'applicazione con le tue credenziali utente.

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      Per saperne di più, consulta Configura ADC per un ambiente di sviluppo locale nella documentazione sull'autenticazione Google Cloud .

      Node.js

      Per utilizzare gli esempi di Node.js questa pagina in un ambiente di sviluppo locale, installa e inizializza gcloud CLI, quindi configura le Credenziali predefinite dell'applicazione con le tue credenziali utente.

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      Per saperne di più, consulta Configura ADC per un ambiente di sviluppo locale nella documentazione sull'autenticazione Google Cloud .

      PHP

      Per utilizzare gli esempi di PHP questa pagina in un ambiente di sviluppo locale, installa e inizializza gcloud CLI, quindi configura le Credenziali predefinite dell'applicazione con le tue credenziali utente.

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      Per saperne di più, consulta Configura ADC per un ambiente di sviluppo locale nella documentazione sull'autenticazione Google Cloud .

      Python

      Per utilizzare gli esempi di Python questa pagina in un ambiente di sviluppo locale, installa e inizializza gcloud CLI, quindi configura le Credenziali predefinite dell'applicazione con le tue credenziali utente.

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      Per saperne di più, consulta Configura ADC per un ambiente di sviluppo locale nella documentazione sull'autenticazione Google Cloud .

    1. Se prevedi di utilizzare Google Cloud CLI, configura il progetto predefinito:

      gcloud config set project PROJECT_ID
      

      Prima di eseguire il comando precedente, sostituisci quanto segue:

      • PROJECT_ID: l'identificatore del progetto. Per le configurazioni di App Hub, seleziona il progetto host di App Hub o il progetto di gestione della cartella app.

Elenca i tipi di canali di notifica

Monitoring fornisce diversi tipi di canali di notifica integrati. Ciascuno di questi tipi è descritto in un NotificationChannelDescriptor. Questi descrittori hanno un campo type e il valore di questo campo funge da identificatore quando vengono create istanze di quel tipo di canale. Per recuperare un elenco dei tipi di canali che puoi creare con l'API Cloud Monitoring o Google Cloud CLI, inserisci il seguente comando:

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

Per saperne di più sui canali di notifica, vedi Creare e gestire i canali di notifica.

Se il tuo canale di notifica preferito non è supportato, valuta la possibilità di creare una pipeline che si basa sull'invio delle notifiche a Pub/Sub. Per un esempio Python che utilizza Flask, consulta Creazione di notifiche personalizzate con Cloud Monitoring e Cloud Run. Per altri esempi, consulta il repository Git cloud-alerting-notification-forwarding.

Per recuperare tutti i descrittori di canale in un progetto Google Cloud , utilizza il metodo notificationChannelDescriptors.list. I descrittori recuperati sono di sola lettura.

Se stai cercando un descrittore specifico e ne conosci il nome, puoi utilizzare il metodo notificationChannelDescriptors.get per recuperare solo quel descrittore del canale. Il nome di un descrittore di canale ha il formato projects/[PROJECT_ID]/notificationChannelDescriptors/[CHANNEL_TYPE] [CHANNEL_TYPE] deve essere uno dei tipi elencati in precedenza. Ad esempio:

projects/[PROJECT_ID]/notificationChannelDescriptors/email

gcloud

Per elencare tutti i descrittori dei canali di notifica in un progetto, utilizza il comando gcloud beta monitoring channel-descriptors list: Google Cloud

gcloud beta monitoring channel-descriptors list

Se l'operazione ha esito positivo, il comando list fornisce un elenco di tutti i descrittori di canale nel progetto specificato. Ad esempio, il descrittore del canale email viene visualizzato nell'elenco nel seguente modo:

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

Tutti i descrittori dei canali includono questi campi:

  • name: Il nome della risorsa completo del descrittore del canale
  • type: La parte del nome che indica il tipo di canale
  • displayName: una descrizione del campo type, a scopo di visualizzazione
  • description: Una breve descrizione del canale
  • labels: Un insieme di campi specifici per un tipo di canale. Ogni tipo di canale ha il proprio insieme di etichette.

Quando viene creato un canale, viene aggiunto anche un campo enabled, con il valore true per impostazione predefinita.

Per elencare un singolo descrittore di canale, utilizza gcloud beta monitoring channel-descriptors describe e specifica il nome del descrittore di canale. Non è necessario specificare il nome completo. Ad esempio, entrambi questi comandi restituiscono l'elenco precedente:

gcloud beta monitoring channel-descriptors describe email

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

Per saperne di più, consulta i riferimenti gcloud beta monitoring channel-descriptors list e describe. Il comando describe corrisponde al metodo notificationChannelDescriptors.get nell'API.

Creazione di un canale di notifica

Puoi creare canali di notifica per i tuoi progetti Google Cloud da file JSON o YAML utilizzando Google Cloud CLI e puoi crearli in modo programmatico.

Per creare un canale di notifica, devi fornire i valori per i campi nel relativo descrittore. La maggior parte di questi, come type, sono comuni a tutti i descrittori dei canali di notifica. Vedi notificationChannelDescriptors.

Ogni descrittore ha anche un insieme di etichette e questo insieme varia a seconda dei descrittori. Per visualizzare l'insieme di etichette per un determinato descrittore, recupera il descrittore utilizzando il comando gcloud beta monitoring channel-descriptors describe descritto in Elencare i tipi di canali di notifica. Ad esempio, il recupero del descrittore del canale email mostra una singola etichetta:

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

Il descrittore del canale pubsub contiene anche una singola etichetta, che identifica l'argomento Pub/Sub. Tuttavia, i canali possono contenere più etichette. Ad esempio, il descrittore del canale slack ha due etichette:

    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

Il recupero del descrittore del canale webhook_basicauth mostra diverse etichette:

    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

Indipendentemente dal fatto che tu crei un nuovo canale a livello di programmazione o dalla riga di comando, il valore di type nella specifica deve corrispondere al campo type nel descrittore del canale di notifica corrispondente. Anche le chiavi delle etichette obbligatorie devono corrispondere a quelle nel descrittore del canale.

Alcune etichette corrispondono alle credenziali utilizzate per l'autenticazione con il fornitore. Quando crei un canale, i valori di queste etichette devono essere ottenuti dal fornitore. L'ottenimento di una credenziale potrebbe comportare l'utilizzo di una pagina di generazione della chiave API sul sito web del fornitore o il completamento di un flusso di accesso OAuth con il fornitore. I dettagli su come ottenere una credenziale di questo tipo dipendono dal fornitore specifico.

Ad esempio, di seguito viene mostrata la specifica di un nuovo canale di notifica pubsub in JSON:

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

Il valore type (pubsub) e la singola chiave di etichetta (topic) corrispondono ai campi type e labels.key nel descrittore del canale corrispondente.

I canali sono abilitati per impostazione predefinita. Se vuoi creare un canale inattivo, puoi includere il campo enabled con il valore false.

Gli esempi seguenti illustrano la creazione di canali di notifica.

gcloud

Per creare un canale di notifica in un progetto Google Cloud , utilizza il comando gcloud beta monitoring channels create. Per caricare il canale da un file, utilizza il flag --channel-content-from-file per specificare il file.

Il seguente esempio crea un nuovo canale Pub/Sub dal file pubsub-channel.json:

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

In caso di esito positivo, questo comando restituisce il nome del nuovo canale, ad esempio:

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

Per saperne di più, consulta il riferimento gcloud beta monitoring channels create.

C#

Per eseguire l'autenticazione in Monitoring, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

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

Per eseguire l'autenticazione in Monitoring, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.


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

Per eseguire l'autenticazione in Monitoring, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.


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

Per eseguire l'autenticazione in Monitoring, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

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

Per eseguire l'autenticazione in Monitoring, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

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

Per eseguire l'autenticazione in Monitoring, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

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)

Esempio: creare un canale di notifica Slack

Per configurare un canale di notifica per un'app Slack:

  1. Configura l'app Slack:

    1. Se non hai ancora un'app Slack, segui la documentazione di riferimento di Slack per crearne una e installarla nel tuo spazio di lavoro.
    2. Configura la tua app Slack con gli ambiti OAuth per chat:write e chat:write.public.
    3. Copia il token OAuth dell'utente bot dell'app.
  2. Crea un file che definisca la configurazione del canale di notifica. Includi un'etichetta in cui la chiave auth_token ha il valore del token OAuth dell'utente bot della tua app Slack. Ad esempio:

    {
      "description": "A Slack notification channel",
      "displayName": "Slack",
      "type": "slack",
      "enabled": true,
      "labels": {
        "auth_token": "OAUTH_TOKEN_VALUE",
        "channel_name": "SLACK_CHANNEL_NAME"
      }
    }
    
  3. Esegui questo comando per creare il canale di notifica:

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

Elenca i canali di notifica in un progetto

Per recuperare tutti i canali di notifica in un progetto Google Cloud , utilizza il metodo notificationChannels.list. Questo metodo supporta anche le opzioni filter e orderBy per limitare e ordinare i risultati; vedi Ordinamento e filtro.

Se stai cercando un canale specifico e ne conosci il nome, puoi utilizzare il metodo notificationChannels.get per recuperare solo quel canale. Il nome di un canale ha il formato projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID], ad esempio:

    projects/[PROJECT_ID]/notificationChannels/1355376463305411567

Quando recuperi un canale, i valori sensibili come i token di autenticazione e le chiavi API potrebbero essere offuscati per motivi di sicurezza. Se stai creando un nuovo canale copiandone uno esistente, tutti i valori offuscati devono essere corretti.

gcloud

Per elencare tutti i canali di notifica in un progetto Google Cloud , utilizza il comando gcloud beta monitoring channels list:

gcloud beta monitoring channels list

In caso di esito positivo, il comando list fornisce un elenco di tutti i canali nel progetto specificato. Ad esempio, il comando precedente potrebbe restituire un elenco che include le seguenti voci:

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

Per elencare un singolo canale, utilizza invece gcloud beta monitoring channels describe e specifica il nome del canale. Ad esempio, questo comando restituisce il canale Pub/Sub mostrato nell'elenco precedente:

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

Per saperne di più, consulta i riferimenti gcloud beta monitoring channels list e describe. Il comando describe corrisponde al metodo notificationChannels.get nell'API.

C#

Per eseguire l'autenticazione in Monitoring, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

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

Per eseguire l'autenticazione in Monitoring, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.


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

Per eseguire l'autenticazione in Monitoring, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

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

Per eseguire l'autenticazione in Monitoring, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

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

Per eseguire l'autenticazione in Monitoring, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

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

Per eseguire l'autenticazione in Monitoring, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

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"),
        )
    )

Eliminare un canale di notifica da un progetto

Per eliminare un canale di notifica da un progetto Google Cloud , utilizza il metodo notificationChannels.delete e fornisci il nome del canale di notifica da eliminare. Il nome di un canale è il valore del campo name, non di displayName, nell'istanza NotificationChannel. Il nome di un canale ha il formato projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID], ad esempio:

    projects/[PROJECT_ID]/notificationChannels/1355376463305411567

Per impostazione predefinita, se tenti di eliminare un canale a cui fa riferimento una criterio di avvisoo, il canale non verrà eliminato. Per forzare la rimozione dei riferimenti dalle policy di avviso ed eliminare il canale, imposta l'opzione force su true. Questa opzione rimuove automaticamente il canale da tutte le norme di riferimento.

gcloud

Per eliminare un canale di notifica, utilizza gcloud beta monitoring channels delete e specifica il nome del canale da eliminare. Ad esempio, il comando seguente elimina il canale email creato in un altro esempio:

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

Per saperne di più, consulta il riferimento gcloud beta monitoring channels delete.

C#

Per eseguire l'autenticazione in Monitoring, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.


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

Per eseguire l'autenticazione in Monitoring, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.


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

Per eseguire l'autenticazione in Monitoring, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

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

Per eseguire l'autenticazione in Monitoring, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

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

Per eseguire l'autenticazione in Monitoring, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.


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

Per eseguire l'autenticazione in Monitoring, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

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

Modificare un canale di notifica

Per modificare un canale di notifica, utilizza il metodo notificationChannels.patch (nell'API REST). Altre implementazioni dell'API e Google Cloud CLI chiamano questo update anziché patch.

Un'operazione di aggiornamento può sostituire completamente il canale esistente o modificare un sottoinsieme di campi. Ad esempio, puoi attivare e disattivare il canale. Se disattivi un canale, le notifiche non verranno recapitate. La disattivazione di un canale è in genere più comoda rispetto alla rimozione del canale dalle policy di avviso che lo riguardano, se la modifica è temporanea.

gcloud

Per attivare un canale di notifica disattivato, utilizza il comando gcloud beta monitoring channels update e fornisci il flag --enabled. Il seguente comando attiva il canale di notifica email creato, nello stato disattivato, in un esempio precedente:

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

Per disattivare una norma, utilizza lo stesso comando e fornisci il flag --no-enabled. Per saperne di più, consulta il riferimento gcloud beta monitoring channels update. Il comando update corrisponde al metodo notificationChannels.patch nell'API REST.

C#

Per eseguire l'autenticazione in Monitoring, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.


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

Per eseguire l'autenticazione in Monitoring, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.


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

Per eseguire l'autenticazione in Monitoring, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.


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

Per eseguire l'autenticazione in Monitoring, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

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

Per eseguire l'autenticazione in Monitoring, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

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

Per eseguire l'autenticazione in Monitoring, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

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)

Visualizza i log dei canali di notifica

Puoi utilizzare Esplora log per visualizzare gli errori del canale di notifica:

  1. Nella Google Cloud console, vai alla pagina Esplora log:

    Vai a Esplora log

    Se utilizzi la barra di ricerca per trovare questa pagina, seleziona il risultato con il sottotitolo Logging.

  2. Inserisci ed esegui la query. Per le query specifiche per gli errori del canale di notifica, consulta Query di Cloud Monitoring.