Add Rocket.Chat plugin ()

This commit is contained in:
Nick Satterly 2018-08-15 02:42:12 +02:00 committed by GitHub
parent e31c992746
commit 79deb67573
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 215 additions and 0 deletions

View file

@ -49,6 +49,7 @@ Plugins
* [Prometheus](plugins/prometheus)
* [Google Cloud Pub/Sub](plugins/pubsub)
* [Pushover.net](plugins/pushover)
* [Rocket.Chat](plugins/rocketchat)
* [Slack](plugins/slack)
* [Amazon SNS](plugins/sns)
* [Syslog](plugins/syslog)

View file

@ -0,0 +1,102 @@
Rocket.Chat Plugin
==================
Post a [Rocket.Chat](https://rocket.chat) message for new alerts.
![Rocket.Chat Message](./images/alerta-rocketchat-plugin.png)
For help, join [![Gitter chat](https://badges.gitter.im/alerta/chat.png)](https://gitter.im/alerta/chat)
Installation
------------
Clone the GitHub repo and run:
$ python setup.py install
Or, to install remotely from GitHub run:
$ pip install git+https://github.com/alerta/alerta-contrib.git#subdirectory=plugins/rocketchat
Note: If Alerta is installed in a python virtual environment then plugins
need to be installed into the same environment for Alerta to dynamically
discover them.
Configuration
-------------
To configure the Rocket.Chat plugin start by setting up an Incoming Webhook
integration for your Rocket.Chat channel. Login to Rocket.Chat and go to
"Administration" => "Integrations" => "New Integration" => "Incoming WebHook".
Enable the webhook, assign a webhook name, default channel (eg. `#general`)
and username to post messages as (which must already exist).
Note: No integration script is needed so leave the "Script" box blank and disabled.
Save the changes and take a copy of the webhook URL.
Add `rocketchat` to the list of enabled `PLUGINS` in `alertad.conf` server
configuration file and set plugin-specific variables either in the
server configuration file or as environment variables.
```python
PLUGINS = ['rocketchat']
ROCKETCHAT_WEBHOOK_URL = 'https://my.rocket.chat/hooks/TOKEN'
ROCKETCHAT_CHANNEL = '' # if empty then uses channel from incoming webhook configuration
ICON_EMOJI = '' # default :rocket:
ALERTA_USERNAME = '' # default alerta
```
The `DASHBOARD_URL` setting should be configured to link Rocket.Chat messages to
the Alerta console:
```python
DASHBOARD_URL = '' # default="not set"
```
**Example**
```python
PLUGINS = ['reject','rocketchat']
ROCKETCHAT_WEBHOOK_URL = 'https://alerta.rocket.chat/hooks/Ahqyy84yFB4DuWorQ/ZyndPtdbY5PCnaQGsXTJPCXbNC9bDiTL9L2Q7ktLnuHFYNKd'
DASHBOARD_URL = 'http://try.alerta.io'
```
Troubleshooting
---------------
Restart Alerta API and confirm that the plugin has been loaded and enabled.
Set `DEBUG=True` in the `alertad.conf` configuration file and look for log
entries similar to below:
```
2018-08-15 01:49:52,323 - alerta.plugins[36667]: DEBUG - Server plugin 'rocketchat' installed. [in /Users/nsatterl/Projects/alerta/alerta/utils/plugin.py:23]
2018-08-15 01:49:52,332 - alerta.plugins[36667]: INFO - Server plugin 'rocketchat' enabled. [in /Users/nsatterl/Projects/alerta/alerta/utils/plugin.py:31]
2018-08-15 01:49:52,332 - alerta.plugins[36667]: INFO - All server plugins enabled: reject, blackout, rocketchat [in /Users/nsatterl/Projects/alerta/alerta/utils/plugin.py:34]
```
An invalid Webhook URL or Auth Token can result in error messages similar to the following:
```
2018-08-15 01:47:14,751 - alerta.plugins.rocketchat[36569]: DEBUG - Rocket.Chat: {'channel': '', 'text': 'Web service is down', 'alias': 'Alerta', 'emoji': ':rocket:', 'attachments': [{'title': 'ddbfb0d0 Bad - Web service is down', 'title_link': 'http://localhost:8080/#/alert/ddbfb0d0-6c78-4c8e-b37f-2fca7bbc8d80', 'text': 'Web service is down', 'color': '#1E90FF', 'fields': [{'title': 'Status', 'value': 'Open', 'short': True}, {'title': 'Environment', 'value': 'Production', 'short': True}, {'title': 'Resource', 'value': 'web02', 'short': True}, {'title': 'Services', 'value': 'Web', 'short': True}]}]} [in /Users/nsatterl/.virtualenvs/alerta5-py3/lib/python3.6/site-packages/alerta_rocketchat-5.0.0-py3.6.egg/alerta_rocketchat.py:71]
2018-08-15 01:47:14,763 - urllib3.connectionpool[36569]: DEBUG - Starting new HTTPS connection (1): alerta.rocket.chat [in /Users/nsatterl/.virtualenvs/alerta5-py3/lib/python3.6/site-packages/urllib3/connectionpool.py:824]
2018-08-15 01:47:15,563 - urllib3.connectionpool[36569]: DEBUG - https://alerta.rocket.chat:443 "POST /hooks/D2oXe5wZEAKFYKds6/eQJ2dyMq6yPvAbNdx6uLjuiLJvQNSkSoWfQfi8kNwPQ6bsoc HTTP/1.1" 404 86 [in /Users/nsatterl/.virtualenvs/alerta5-py3/lib/python3.6/site-packages/urllib3/connectionpool.py:396]
2018-08-15 01:47:15,567 - alerta.plugins.rocketchat[36569]: DEBUG - Rocket.Chat: 404 - {"success":false,"error":"Invalid integration id or token provided."} [in /Users/nsatterl/.virtualenvs/alerta5-py3/lib/python3.6/site-packages/alerta_rocketchat-5.0.0-py3.6.egg/alerta_rocketchat.py:78]
```
References
----------
* Rocket.Chat Incoming WebHooks: https://rocket.chat/docs/administrator-guides/integrations/index.html#how-to-create-a-new-incoming-webhook
* Slack Message Attachments: https://api.slack.com/docs/message-attachments
License
-------
Copyright (c) 2018 Nick Satterly. Available under the MIT License.

View file

@ -0,0 +1,86 @@
import logging
import os
import requests
try:
from alerta.plugins import app # alerta >= 5.0
except ImportError:
from alerta.app import app # alerta < 5.0
from alerta.plugins import PluginBase
LOG = logging.getLogger('alerta.plugins.rocketchat')
ROCKETCHAT_WEBHOOK_URL = os.environ.get('ROCKETCHAT_WEBHOOK_URL') or app.config['ROCKETCHAT_WEBHOOK_URL']
ROCKETCHAT_CHANNEL = os.environ.get('ROCKETCHAT_CHANNEL') or app.config.get('ROCKETCHAT_CHANNEL', '')
ALERTA_USERNAME = os.environ.get('ALERTA_USERNAME') or app.config.get('ALERTA_USERNAME', 'alerta')
ICON_EMOJI = os.environ.get('ICON_EMOJI') or app.config.get('ICON_EMOJI', ':rocket:')
DASHBOARD_URL = os.environ.get('DASHBOARD_URL') or app.config.get('DASHBOARD_URL', '')
DEFAULT_SEVERITY_MAP = {
'security': '#000000', # black
'critical': '#FF0000', # red
'major': '#FFA500', # orange
'minor': '#FFFF00', # yellow
'warning': '#1E90FF', #blue
'informational': '#808080', #gray
'debug': '#808080', # gray
'trace': '#808080', # gray
'ok': '#00CC00' # green
}
class PostMessage(PluginBase):
def pre_receive(self, alert):
return alert
def post_receive(self, alert):
if alert.repeat:
return
self._post_message(self._prepare_payload(alert))
def status_change(self, alert, status, text):
if status not in ['ack', 'assign']:
return
self._post_message(self._prepare_payload(alert, status, text))
@staticmethod
def _prepare_payload(alert, status=None, text=None):
title = '[{status}] {environment}: {event} on {resource}'.format(
status=(status if status else alert.status).capitalize(),
environment=alert.environment,
severity=alert.severity,
event=alert.event,
resource=alert.resource
)
return {
"channel": ROCKETCHAT_CHANNEL,
"text": text,
"alias": ALERTA_USERNAME,
"emoji": ICON_EMOJI,
"attachments": [{
"title": title,
"title_link": '%s/#/alert/%s' % (DASHBOARD_URL, alert.id),
"text": alert.text,
"color": DEFAULT_SEVERITY_MAP.get(alert.severity, DEFAULT_SEVERITY_MAP['ok']),
"fields": [
{"title": "Status", "value": (status if status else alert.status).capitalize(), "short": True},
{"title": "Environment", "value": alert.environment, "short": True},
{"title": "Resource", "value": alert.resource, "short": True},
{"title": "Services", "value": ", ".join(alert.service), "short": True}
]
}]
}
@staticmethod
def _post_message(payload):
LOG.debug('Rocket.Chat: %s', payload)
try:
r = requests.post(ROCKETCHAT_WEBHOOK_URL, json=payload, timeout=2)
except Exception as e:
raise RuntimeError("Rocket.Chat: ERROR - %s" % e)
LOG.debug('Rocket.Chat: %s - %s', r.status_code, r.text)

Binary file not shown.

After

(image error) Size: 112 KiB

View file

@ -0,0 +1,26 @@
from setuptools import setup, find_packages
version = '5.0.0'
setup(
name="alerta-rocketchat",
version=version,
description='Alerta plugin for Rocket.Chat',
url='https://github.com/alerta/alerta-contrib',
license='MIT',
author='Nick Satterly',
author_email='nick.satterly@gmail.com',
packages=find_packages(),
py_modules=['alerta_rocketchat'],
install_requires=[
'requests'
],
include_package_data=True,
zip_safe=True,
entry_points={
'alerta.plugins': [
'rocketchat = alerta_rocketchat:PostMessage'
]
}
)