alerta-contrib/plugins/geoip/alerta_geoip.py

49 lines
1.5 KiB
Python
Raw Permalink Normal View History

2015-01-30 15:22:43 +00:00
2017-09-17 15:56:55 +01:00
import logging
import os
2015-01-30 15:22:43 +00:00
import requests
2017-09-17 15:56:55 +01:00
try:
from alerta.plugins import app # alerta >= 5.0
except ImportError:
from alerta.app import app # alerta < 5.0
2015-01-30 15:22:43 +00:00
from alerta.plugins import PluginBase
2016-09-15 10:16:11 +01:00
LOG = logging.getLogger('alerta.plugins.geoip')
2015-01-30 15:22:43 +00:00
2018-11-16 20:45:45 +01:00
GEOIP_URL = os.environ.get('GEOIP_URL') or app.config.get('GEOIP_URL', 'http://api.ipstack.com')
GEOIP_ACCESS_KEY = os.environ.get('GEOIP_ACCESS_KEY') or app.config.get('GEOIP_ACCESS_KEY', None)
2015-01-30 15:22:43 +00:00
class GeoLocation(PluginBase):
def pre_receive(self, alert):
2016-11-20 21:59:18 +00:00
ip_addr = alert.attributes['ip'].split(', ')[0]
LOG.debug("GeoIP lookup for IP: %s", ip_addr)
2015-01-30 15:52:19 +00:00
if 'ip' in alert.attributes:
2018-11-16 20:45:45 +01:00
url = '%s/%s?access_key=%s' % (GEOIP_URL, ip_addr, GEOIP_ACCESS_KEY)
2015-01-30 15:52:19 +00:00
else:
2016-09-15 10:16:11 +01:00
LOG.warning("IP address must be included as an alert attribute.")
2015-01-30 15:52:19 +00:00
raise RuntimeWarning("IP address must be included as an alert attribute.")
2015-01-30 15:22:43 +00:00
r = requests.get(url, headers={'Content-type': 'application/json'}, timeout=2)
try:
2018-11-16 20:45:45 +01:00
geoip_lookup = r.json()
alert.attributes = {
'geoip': geoip_lookup,
'country': geoip_lookup['location'].get('country_flag_emoji')
}
2015-01-30 15:22:43 +00:00
except Exception as e:
2016-09-15 10:16:11 +01:00
LOG.error("GeoIP lookup failed: %s" % str(e))
2015-01-30 15:22:43 +00:00
raise RuntimeError("GeoIP lookup failed: %s" % str(e))
return alert
def post_receive(self, alert):
return
2015-01-30 15:22:43 +00:00
def status_change(self, alert, status, text):
return