This topic provides some sample scripts to show you how to call and test an alert API.
Call an OCP alert API
The following script shows how to call the API that pushes alerts o OCP, so that OCP can process the alerts.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
import requests
import json
data = {
"alarmType": "your_alarm_type",
"labels": {"key":"value"},
"target":"alarm_target",
}
base64userpass = base64.b64encode('{0}:{1}'.format('username', 'password'))
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
"Authorization": "Basic %s" % base64userpass,
}
resp = requests.post(url='http://xxx.xxx.xxx.xxx:8080/api/v2/alarm/alarms', headers=headers, data=json.dumps(data))
jresp = json.loads(resp.text)
print(jresp)
Send an alert from OCP
After an alert is generated in OCP, the alert message is sent through a specified alert channel. You can use a shell script or a Python scrip to configure an alert channel. The following example shows how to send an alert message through an alert channel. The send_alarm function retrieves the values of alert-related environment variables from the os.environ object. For a list of supported environment variables, see OCP alert template variables.
Python script example:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Note: The first line of the script must use a shebang to specify the program to use. Only Python and bash are supported.
import os
import sys
def send_alarm():
message = os.environ['message']
print("Alert message: {}".format(message))
with open("./alarm_output.txt", "a") as file_object:
file_object.write("{}\n".format(message))
def main():
"""
Return 0 if succeeded.
Return a non-zero value if failed. The error is printed to stderr.
"""
try:
send_alarm()
print("send alarm success")
return 0
except Exception as e:
sys.stderr.write(str(e))
return 1
if __name__ == "__main__":
sys.exit(main())
Test an alert
To test if an alert can be pushed to a third-party platform, take one of the following approaches.
You can trigger an alert in OCP by performing the following steps:
Suspend OCP Agent to trigger an agent-unavailable alert, for example, the
no_enough_exporteralert.Check if the third-party platform receives the alert.
The Alert Channel Configuration module of OCP provides a testing feature. You can start a test by clicking Send Test Message . For more information, see Create an alert channel.
You can call the API that pushes alerts to OCP, and then use an alert channel script to send the alert to a third-party platform.