forked from alerta/alerta-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
alerta_pubsub.py
72 lines (53 loc) · 2.42 KB
/
alerta_pubsub.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import os
import logging
from alerta.app import app
from alerta.plugins import PluginBase
from google.cloud import pubsub
from google.oauth2 import service_account
LOG = logging.getLogger('alerta.plugins.pubsub')
DEFAULT_TOPIC_NAME = 'alerta'
TOPIC_NAME = os.environ.get('TOPIC_NAME') or app.config.get('TOPIC_NAME', DEFAULT_TOPIC_NAME)
DEFAULT_SUBSCRIPTION_NAME = 'alerta-notification'
SUBSCRIPTION_NAME = os.environ.get('SUBSCRIPTION_NAME') or app.config.get('SUBSCRIPTION_NAME', DEFAULT_SUBSCRIPTION_NAME)
DEFAULT_SERVICE_ACCOUNT_FILE = None
SERVICE_ACCOUNT_FILE = os.environ.get('SERVICE_ACCOUNT_FILE') or app.config.get('SERVICE_ACCOUNT_FILE', DEFAULT_SERVICE_ACCOUNT_FILE)
PUBSUB_SCOPES = ["https://www.googleapis.com/auth/pubsub"]
class SendToPubsub(PluginBase):
def __init__(self, name=None):
LOG.info('creating pubsub client')
self.client = self.get_client()
# create pubsub topic and subscription if does not exists
try:
LOG.info('checking pubsub topic')
self.topic = self.client.topic(TOPIC_NAME)
if not self.topic.exists():
LOG.info('creating pubsub topic')
self.topic.create()
LOG.info('checking pubsub subscription')
subscription = self.topic.subscription(SUBSCRIPTION_NAME)
if not subscription.exists():
LOG.info('creating pubsub topic subscription')
subscription.create()
except Exception as excp:
LOG.exception(excp)
raise RuntimeError("pubsub exception")
super(SendToPubsub, self).__init__(name)
def get_client(self):
if SERVICE_ACCOUNT_FILE:
LOG.info('using service account file %s', SERVICE_ACCOUNT_FILE)
credential = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE)
scoped_credential = credential.with_scopes(PUBSUB_SCOPES)
return pubsub.Client(credentials=scoped_credential)
LOG.info('default')
return pubsub.Client()
def pre_receive(self, alert):
return alert
def post_receive(self, alert):
try:
message_id = self.topic.publish(alert.__str__())
LOG.info('message %s published', message_id)
except Exception as excp:
LOG.exception(excp)
raise RuntimeError("pubsub exception")
def status_change(self, alert, status, text):
return