Gestione degli avvisi utilizzando il client Python
Puoi gestire gli avvisi in un'istanza IBM Cloud Monitoring utilizzando il client Monitoring Python.
Per informazioni su come utilizzare il client Python, vedi Utilizzo del client Python.
Crea un avviso (POST)
Il seguente codice mostra la struttura di uno script Python che puoi utilizzare per creare un avviso:
# Reference the Python client
from sdcclient import IbmAuthHelper, SdMonitorClient
# Add the monitoring instance information that is required for authentication
URL = <MONITORING-ENDPOINT>
APIKEY = <IAM_APIKEY>
GUID = <GUID>
ibm_headers = IbmAuthHelper.get_headers(URL, APIKEY, GUID)
# Instantiate the Python client
sdclient = SdMonitorClient(sdc_url=URL, custom_headers=ibm_headers)
# Add the notification channels to send an alert when the alert is triggered
notify_channels = [
{
'type': 'SLACK',
'channel': '<SLACK_CHANNEL_NAME>'
},
{
'type': 'EMAIL',
'emailRecipients': [
'user1@ibm.com', 'user2@ibm.com'
]
}
]
# Get the IDs of the notification channels that you have configured
res = sdclient.get_notification_ids(notify_channels)
if not res[0]:
print("Failed to fetch notification channel ID's")
notification_channel_ids = res
# Create and define the alert details
res = sdclient.create_alert(
name=<ALERT_NAME>,
description=<ALERT_DESCRIPTION>,
severity=<SEVERITY>,
for_atleast_s=<FOR_ATLEAST_S>,
condition=<CONDITION>,
segmentby=<SEGMENTBY>,
segment_condition=<SEGMENT_CONDITION>,
user_filter=<USER_FILTER>,
notify=<NOTIFICATION_CHANNEL_IDS>,
enabled=<ENABLED>,
annotations=<ANNOTATIONS>,
alert_obj=<ALERT_OBJ>
)
if not res[0]:
print("Alert creation failed")
Considera le seguenti informazioni quando crei uno script Python:
-
È necessario includere le seguenti informazioni:
<MONITORING-ENDPOINT>,<IAM_APIKEY>e<GUID>Questi dati sono necessari per autenticare la richiesta con l'istanza di monitoraggio. Per ottenere le informazioni sull'istanza di monitoraggio, consulta Autentica il tuo ID utente o servizio utilizzando IAM. -
È necessario definire i canali di notifica tramite i quali si desidera ricevere una notifica quando viene attivato il messaggio di alert.
I tipi di canale di notifica validi sono
SLACK,PAGER_DUTY,VICTOROPS,WEBHOOKeEMAIL.Quando si definiscono i canali di notifica, i canali devono essere configurati nell'istanza di monitoraggio.
Quando si aggiunge un canale di notifica email, è possibile aggiungere più destinatari. Separare i valori utilizzando una virgola.
Quando definisci un canale Slack, sostituisci
<SLACK_CHANNEL_NAME>con il nome del canale. È necessario includere il simbolo#con il nome del canale, ad esempio#my_monitoring_alert_channel.
Quando configuri l'avviso, completa le seguenti sezioni:
-
[
nameedescription]: è necessario definire un nome univoco per il nome dell'avviso sostituendo<ALERT_NAME>e, facoltativamente, aggiungere una descrizione sostituendo<ALERT_DESCRIPTION>. -
[
severity]: è necessario definire la severità dell'avviso sostituendo<SEVERITY>con un numero. I valori validi sono0,1,2,3,4,5,6e7. -
[
for_atleast_s]: è necessario definire il numero di secondi consecutivi in cui la condizione viene soddisfatta prima che venga attivato l'avviso. Sostituire<FOR_ATLEAST_S>con il numero di secondi. -
[
condition]: devi definire la condizione che definisce quando viene attivato il messaggio di alert. Ad esempio, è possibile impostare questo parametro su['host.mac', 'proc.name']per controllare un avviso CPU per ogni processo su ogni macchina.Per ulteriori informazioni, consultare Avvisi multi - condizione.
-
[
segmentby]: è possibile definire l'ambito di un avviso configurando la sezionesegmentedby. Il valore predefinito èANY. -
[
segment_condition]: quando viene specificato il parametro segmentby, impostare questo campo per determinare quando verrà attivato l'avviso. I valori validi sono ANY e ALL. -
[
user_filter]: è possibile definire un filtro che indica quando viene inviata una notifica. Ad esempio, è possibile definire questa voce se si desidera ricevere una notifica solo se il nome del processo soddisfa la condizione. -
[
notify]: puoi definire il tipo di notifiche che vuoi che l'avviso generi. Impostare questa voce sugli ID notifica dei canali definiti. -
[
enabled]: è possibile configurare lo stato dell'avviso quando viene creato. Per impostazione predefinita, gli avvisi sono abilitati e la voce è impostata sutrue. Impostare sufalsese non si desidera che sia abilitato quando si crea. -
[
annotations]: è possibile aggiungere proprietà personalizzate che è possibile associare all'avviso. -
[
alert_obj]: è possibile collegare un oggetto avviso invece di specificare i parametri individuali.
Aggiornamento di un avviso (PUT)
Per aggiornare un avviso esistente, è necessario l'ID di tale avviso.
Il seguente codice mostra la struttura di uno script Python che puoi utilizzare per aggiornare un avviso:
# Reference the Python client
from sdcclient import IbmAuthHelper, SdMonitorClient
# Add the monitoring instance information that is required for authentication
URL = <MONITORING-ENDPOINT>
APIKEY = <IAM_APIKEY>
GUID = <GUID>
ibm_headers = IbmAuthHelper.get_headers(URL, APIKEY, GUID)
# Instantiate the Python client
sdclient = SdMonitorClient(sdc_url=URL, custom_headers=ibm_headers)
res = sdclient.get_alerts()
if not res[0]:
print("Failed to fetch existing alerts")
alert_found = False
for alert in res['alerts']:
if alert['name'] == alert_name:
alert_found = True
if 'notificationChannelIds' in alert:
alert['notificationChannelIds'] = alert['notificationChannelIds'][0:-1]
update_txt = '(changed by update_alert)'
if alert['description'][-len(update_txt):] != update_txt:
alert['description'] = alert['description'] + update_txt
alert['timespan'] = alert['timespan'] * 2 # Note: Expressed in seconds * 1000000
res_update = sdclient.update_alert(alert)
if not res_update:
print("Alert update failed")
if not alert_found:
print('Alert to be updated not found')
Eliminazione di un avviso (DELETE)
Per eliminare un avviso esistente, è necessario l'ID di tale avviso.
Il seguente codice mostra la struttura di uno script Python che puoi utilizzare per eliminare un avviso:
# Reference the Python client
from sdcclient import IbmAuthHelper, SdMonitorClient
# Add the monitoring instance information that is required for authentication
URL = <MONITORING-ENDPOINT>
APIKEY = <IAM_APIKEY>
GUID = <GUID>
ibm_headers = IbmAuthHelper.get_headers(URL, APIKEY, GUID)
# Instantiate the Python client
sdclient = SdMonitorClient(sdc_url=URL, custom_headers=ibm_headers)
res = sdclient.get_alerts()
if not res[0]:
print("Failed to fetch existing alerts")
for alert in res['alerts']:
if alert['name'] == alert_name:
print("Deleting alert")
res = sdclient.delete_alert(alert)
if not res:
print("Alert deletion failed")
Ottieni tutti gli avvisi utente (GET)
Il codice seguente mostra la struttura di uno script Python che puoi utilizzare per ottenere informazioni su tutti gli avvisi:
# Reference the Python client
from sdcclient import IbmAuthHelper, SdMonitorClient
# Add the monitoring instance information that is required for authentication
URL = <MONITORING-ENDPOINT>
APIKEY = <IAM_APIKEY>
GUID = <GUID>
ibm_headers = IbmAuthHelper.get_headers(URL, APIKEY, GUID)
# Instantiate the Python client
sdclient = SdMonitorClient(sdc_url=URL, custom_headers=ibm_headers)
json_res = sdclient.get_alerts()
print(json_res)