Beispiel #1
0
    def test_env_vars(self):

        config = Config(config_file=None)
        self.assertEqual(config.options['config_file'], '~/.alerta.conf')

        with mod_env(ALERTA_CONF_FILE='~/.alerta.test.conf',
                     ALERTA_DEFAULT_PROFILE='test-profile',
                     ALERTA_ENDPOINT='http://foo/bar/baz',
                     ALERTA_API_KEY='test-key',
                     REQUESTS_CA_BUNDLE='',
                     CLICOLOR='',
                     DEBUG='1'):

            # conf file
            config = Config(config_file=None)
            self.assertEqual(config.options['config_file'],
                             '~/.alerta.test.conf', os.environ)
            config = Config(config_file='/dev/null')
            self.assertEqual(config.options['config_file'], '/dev/null')

            # profile
            config = Config(config_file=None)
            config.get_config_for_profle()
            self.assertEqual(config.options['profile'], 'test-profile',
                             os.environ)

            # endpoint
            self.client = Client()
            self.assertEqual(self.client.endpoint, 'http://foo/bar/baz')

            # api key
            self.assertEqual(config.options['key'], 'test-key')
Beispiel #2
0
    def __init__(self):

        self.api = Client()

        LOG.info('Starting UDP listener...')
        # Set up syslog UDP listener
        try:
            self.udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.udp.bind(('', SYSLOG_UDP_PORT))
        except socket.error as e:
            LOG.error('Syslog UDP error: %s', e)
            sys.exit(2)
        LOG.info('Listening on syslog port %s/udp' % SYSLOG_UDP_PORT)

        LOG.info('Starting TCP listener...')
        # Set up syslog TCP listener
        try:
            self.tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.tcp.bind(('', SYSLOG_TCP_PORT))
            self.tcp.listen(5)
        except socket.error as e:
            LOG.error('Syslog TCP error: %s', e)
            sys.exit(2)
        LOG.info('Listening on syslog port %s/tcp' % SYSLOG_TCP_PORT)

        self.shuttingdown = False
    def setUp(self):
        self.client = Client()

        alarm_model = {
            'name': 'Alerta 8.0.1',
            'severity': {
                'security': 0,
                'critical': 1,
                'major': 2,
                'minor': 3,
                'warning': 4,
                'indeterminate': 5,
                'informational': 6,
                'normal': 7,
                'ok': 7,
                'cleared': 7,
                'debug': 8,
                'trace': 9,
                'unknown': 10
            },
            'defaults': {
                'normal_severity': 'normal'
            }
        }

        config = Config(config_file=None,
                        config_override={'alarm_model': alarm_model})
        self.obj = config.options
        self.obj['client'] = self.client

        self.runner = CliRunner(echo_stdin=True)
    def senddata(self, content):
        config_file = os.environ.get('ALERTA_CONF_FILE') or OPTIONS['config_file']
        config = configparser.RawConfigParser(defaults=OPTIONS)
        try:
            config.read(os.path.expanduser(config_file))
        except Exception:
            sys.exit("Problem reading configuration file %s - is this an ini file?" % config_file)

        want_profile = os.environ.get('ALERTA_DEFAULT_PROFILE') or config.defaults().get('profile')
        if want_profile and config.has_section('profile %s' % want_profile):
            for opt in OPTIONS:
                try:
                    OPTIONS[opt] = config.getboolean('profile %s' % want_profile, opt)
                except (ValueError, AttributeError):
                    OPTIONS[opt] = config.get('profile %s' % want_profile, opt)
        else:
            for opt in OPTIONS:
                try:
                    OPTIONS[opt] = config.getboolean('DEFAULT', opt)
                except (ValueError, AttributeError):
                    OPTIONS[opt] = config.get('DEFAULT', opt)
        try:
            LOG.debug("[alerta] sendto=%s ", OPTIONS.get("endpoint"))
            api = Client(endpoint=OPTIONS.get("endpoint"), key=OPTIONS.get("key"), ssl_verify=OPTIONS.get("sslverify"))
            api.send_alert(**content)
        except RequestException as e:
            raise EAException("send message has error: %s" % e)

        elastalert_logger.info("send msg success" )
Beispiel #5
0
def cli(ctx, config_file, profile, endpoint_url, output, color, debug):
    """
    Alerta client unified command-line tool.
    """
    config = Config(config_file)
    config.get_config_for_profle(profile)
    config.get_remote_config(endpoint_url)

    ctx.obj = config.options

    # override current options with command-line options or environment variables
    ctx.obj['output'] = output or config.options['output']
    ctx.obj['color'] = color or os.environ.get('CLICOLOR',
                                               None) or config.options['color']
    endpoint = endpoint_url or config.options['endpoint']

    ctx.obj['client'] = Client(endpoint=endpoint,
                               key=config.options['key'],
                               token=get_token(endpoint),
                               username=config.options.get('username', None),
                               password=config.options.get('password', None),
                               timeout=float(config.options['timeout']),
                               ssl_verify=config.options['sslverify'],
                               debug=debug or os.environ.get('DEBUG', None)
                               or config.options['debug'])
Beispiel #6
0
    def run(self):
        """Run the App main logic.

        This method should contain the core logic of the App.
        """
        alerta_api_key = self.tcex.playbook.read(self.args.alerta_api_key)
        alerta_api_endpoint = self.tcex.playbook.read(self.args.alerta_api_endpoint)
        alert_id = self.tcex.playbook.read(self.args.alert_id)
        query = self.tcex.playbook.read(self.args.query, True)

        # initialize alerta client
        client = Client(endpoint=alerta_api_endpoint, key=alerta_api_key)

        if not alert_id and not query:
            self.tcex.log.info('Retrieving all alerts from {}'.format(alerta_api_endpoint))
            alerts = client.get_alerts()
        elif alert_id:
            self.tcex.log.info('Retrieving alert with id "{}"'.format(alert_id))
            alerts = [client.get_alert(alert_id)]
        elif query:
            raise NotImplementedError('The ability to search for a query is not implemented yet. If you need it, create an issue here: https://github.com/ThreatConnect-Inc/threatconnect-playbooks/issues')
            # TODO: the difficulty here is that the query should be a tuple (I think) and I'm not sure how to (elegantly) convert the incoming string to a tuple
            # self.tcex.log.info('Retrieving alerts matching the query: {}'.format(query))
            # alerts = client.search(query)

        alerts_json = self.convert_to_json(alerts)

        self.tcex.playbook.create_output('alerta.alerts', alerts_json, 'StringArray')
        self.tcex.playbook.create_output('alerta.alerts.0', alerts_json[0], 'String')
        self.tcex.playbook.create_output('alerta.alertCount', len(alerts_json), 'String')
Beispiel #7
0
    def run(self):

        api = Client(endpoint=OPTIONS['endpoint'], key=OPTIONS['key'])
        keep_alive = 0

        while not self.should_stop:
            for alertid in on_hold.keys():
                try:
                    (alert, hold_time) = on_hold[alertid]
                except KeyError:
                    continue
                if time.time() > hold_time:
                    self.send_email(alert)
                    try:
                        del on_hold[alertid]
                    except KeyError:
                        continue

            if keep_alive >= 10:
                tag = OPTIONS['smtp_host'] or 'alerta-mailer'
                try:
                    api.heartbeat(tags=[tag])
                except Exception as e:
                    time.sleep(5)
                    continue
                keep_alive = 0
            keep_alive += 1
            time.sleep(2)
Beispiel #8
0
    def run(self):

        endpoint = os.environ.get('ALERTA_ENDPOINT', 'http://localhost:8080')
        key = os.environ.get('ALERTA_API_KEY', None)

        self.api = Client(endpoint=endpoint, key=key)

        data = sys.stdin.read()
        LOG.info('snmptrapd -> %r', data)
        data = unicode(data, 'utf-8', errors='ignore')
        LOG.debug('unicoded -> %s', data)

        snmptrapAlert = SnmpTrapHandler.parse_snmptrap(data)

        if snmptrapAlert:
            try:
                self.api.send(snmptrapAlert)
            except Exception as e:
                LOG.warning('Failed to send alert: %s', e)

        LOG.debug('Send heartbeat...')
        try:
            origin = '{}/{}'.format('snmptrap', platform.uname()[1])
            self.api.heartbeat(origin, tags=[__version__])
        except Exception as e:
            LOG.warning('Failed to send heartbeat: %s', e)
Beispiel #9
0
def cli(ctx, config_file, profile, endpoint_url, output, color, debug):
    """
    Alerta client unified command-line tool.
    """
    config = Config(config_file)
    config.get_config_for_profle(profile)

    ctx.obj = dict()
    ctx.obj['timezone'] = config.options['timezone']
    ctx.obj['output'] = output or config.options['output']
    ctx.obj['color'] = color or os.environ.get('CLICOLOR', None) or config.options['color']
    endpoint = endpoint_url or config.options['endpoint']
    ctx.obj['provider'] = config.options['provider']
    ctx.obj['client_id'] = config.options['client_id']
    ctx.obj['github_url'] = config.options['github_url']
    ctx.obj['gitlab_url'] = config.options['gitlab_url']

    ctx.obj['client'] = Client(
        endpoint=endpoint,
        key=config.options['key'],
        token=get_token(endpoint),
        timeout=float(config.options['timeout']),
        ssl_verify=config.options['sslverify'],
        debug=debug or os.environ.get('DEBUG', None) or config.options['debug']
    )
Beispiel #10
0
    def run(self):

        api = Client(endpoint=OPTIONS['endpoint'], key=OPTIONS['key'])
        keep_alive = 0

        while not self.should_stop:
            for alertid in list(on_hold.keys()):
                try:
                    (alert, hold_time) = on_hold[alertid]
                except KeyError:
                    continue

                if time.time() > hold_time:
                    self.diagnose(alert)
                    try:
                        del on_hold[alertid]
                    except KeyError:
                        continue

            if keep_alive >= 10:
                try:
                    origin = '{}'.format('alerta-trigger')
                    api.heartbeat(origin, tags=[__version__])
                except Exception as e:
                    time.sleep(5)
                    continue
                keep_alive = 0
            keep_alive += 1
            time.sleep(2)
Beispiel #11
0
    def setUp(self):
        self.client = Client()

        config = Config(config_file=None)
        self.obj = config.options
        self.obj['client'] = self.client

        self.runner = CliRunner(echo_stdin=True)
Beispiel #12
0
 def alerta(self):
     """Return alerta instance, create new if missing"""
     if self._alerta is None:
         LOGGER.warning('No alerta exist. Create client.')
         self._alerta = Client(endpoint=self.alerta_config.alerta_endpoint,
                               debug=self.alerta_config.alerta_debug,
                               timeout=self.alerta_config.alerta_timeout,
                               key=self.alerta_api_key)
     return self._alerta
Beispiel #13
0
    def __init__(self):
        default_url = "http://localhost:8080/api"

        self.endpoint = os.environ.get("ALERTA_ENDPOINT", default_url)
        self.key = os.environ.get("ALERTA_KEY", "")
        self.ssl_verify = os.environ.get("ALERTA_SSL_VERIFY", False)

        self.client = Client(endpoint=self.endpoint,
                             key=self.key,
                             ssl_verify=self.ssl_verify)
Beispiel #14
0
    def post_receive(self, alert):
        client = Client(endpoint=FORWARD_URL)
        fw_count = alert.attributes.get('fw_count') or 0
        fw_count = fw_count + 1
        if fw_count >= FORWARD_MAX_LENGTH:
            LOG.debug('alert discarded by cycle overflow')
            return

        alert.attributes['fw_count'] = fw_count
        client.send_alert(**alert.serialize)
        return
Beispiel #15
0
    def run(self):

        self.running = True

        # Create internal queue
        self.queue = Queue.Queue()

        self.api = Client()

        # Initialiase ping targets
        ping_list = init_targets()

        # Start worker threads
        LOG.debug('Starting %s worker threads...', SERVER_THREAD_COUNT)
        for i in range(SERVER_THREAD_COUNT):
            w = WorkerThread(self.api, self.queue)
            try:
                w.start()
            except Exception as e:
                LOG.error('Worker thread #%s did not start: %s', i, e)
                continue
            LOG.info('Started worker thread: %s', w.getName())

        while not self.shuttingdown:
            try:
                for p in ping_list:
                    if 'targets' in p and p['targets']:
                        for target in p['targets']:
                            environment = p['environment']
                            service = p['service']
                            retries = p.get('retries', PING_MAX_RETRIES)
                            self.queue.put(
                                (environment, service, target, retries,
                                 time.time()))

                LOG.debug('Send heartbeat...')
                try:
                    origin = '{}/{}'.format('pinger', platform.uname()[1])
                    self.api.heartbeat(origin, tags=[__version__])
                except Exception as e:
                    LOG.warning('Failed to send heartbeat: %s', e)

                time.sleep(LOOP_EVERY)
                LOG.info('Ping queue length is %d', self.queue.qsize())

            except (KeyboardInterrupt, SystemExit):
                self.shuttingdown = True

        LOG.info('Shutdown request received...')
        self.running = False

        for i in range(SERVER_THREAD_COUNT):
            self.queue.put(None)
        w.join()
Beispiel #16
0
def main():

    api = Client()
    listener = Listener()

    while True:
        listener.send_cmd('READY\n')
        headers, body = listener.wait()
        event = headers['eventname']

        if event.startswith('TICK'):
            try:
                origin = '{}/{}'.format('supervisord', platform.uname()[1])
                api.heartbeat(origin, tags=[headers['ver'], event])
            except Exception as e:
                listener.log_stderr(e)
                listener.send_cmd('RESULT 4\nFAIL')
            else:
                listener.send_cmd('RESULT 2\nOK')
        else:
            if event.endswith('FATAL'):
                severity = 'critical'
            elif event.endswith('BACKOFF'):
                severity = 'warning'
            elif event.endswith('EXITED'):
                severity = 'minor'
            else:
                severity = 'normal'
            try:
                api.send_alert(
                    resource='%s:%s' %
                    (platform.uname()[1], body['processname']),
                    environment='Production',
                    service=['supervisord'],
                    event=event,
                    correlate=[
                        'PROCESS_STATE_STARTING', 'PROCESS_STATE_RUNNING',
                        'PROCESS_STATE_BACKOFF', 'PROCESS_STATE_STOPPING',
                        'PROCESS_STATE_EXITED', 'PROCESS_STATE_STOPPED',
                        'PROCESS_STATE_FATAL', 'PROCESS_STATE_UNKNOWN'
                    ],
                    value='serial=%s' % headers['serial'],
                    severity=severity,
                    origin=headers['server'],
                    text='State changed from %s to %s.' %
                    (body['from_state'], event),
                    raw_data='%s\n\n%s' %
                    (json.dumps(headers), json.dumps(body)))
            except Exception as e:
                listener.log_stderr(e)
                listener.send_cmd('RESULT 4\nFAIL')
            else:
                listener.send_cmd('RESULT 2\nOK')
Beispiel #17
0
    def post_receive(self, alert):
        if not FORWARD_URL or not FORWARD_API_KEY:
            return
        client = Client(endpoint=FORWARD_URL, key=FORWARD_API_KEY)
        fw_count = alert.attributes.get('fw_count') or 0
        fw_count = fw_count+1
        if fw_count >= FORWARD_MAX_LENGTH:
            LOG.debug('alert discarded by cycle overflow')
            return

        alert.get('attributes')['fw_count'] = fw_count
        client.send_alert(
            **alert
        )
        return
Beispiel #18
0
    def run(self):

        endpoint = os.environ.get('ALERTA_ENDPOINT', 'http://localhost:8080')
        key = os.environ.get('ALERTA_API_KEY', None)

        self.api = Client(endpoint=endpoint, key=key)

        data = sys.stdin.read()
        LOG.info('snmptrapd -> %r', data)
        try:
            data = unicode(data, 'utf-8', errors='ignore')  # python 2
        except NameError:
            pass
        LOG.debug('unicoded -> %s', data)

        try:
            resource, event, correlate, trap_version, trapvars = self.parse_snmptrap(data)
            if resource and event:
                self.api.send_alert(
                    resource=resource,
                    event=event,
                    correlate=correlate,
                    group='SNMP',
                    value=trapvars['$w'],
                    severity='indeterminate',
                    environment='Production',
                    service=['Network'],
                    text=trapvars['$W'],
                    event_type='snmptrapAlert',
                    attributes={'trapvars': {k.replace('$', '_'): v for k, v in trapvars.items()}},
                    tags=[trap_version],
                    create_time=datetime.datetime.strptime('%sT%s.000Z' % (trapvars['$x'], trapvars['$X']), '%Y-%m-%dT%H:%M:%S.%fZ'),
                    raw_data=data
                )
        except Exception as e:
            LOG.warning('Failed to send alert: %s', e)

        LOG.debug('Send heartbeat...')
        try:
            origin = '{}/{}'.format('snmptrap', platform.uname()[1])
            self.api.heartbeat(origin, tags=[__version__])
        except Exception as e:
            LOG.warning('Failed to send heartbeat: %s', e)
Beispiel #19
0
    def run(self):

        self.running = True

        self.queue = Queue.Queue()
        self.api = Client(endpoint=settings.ENDPOINT, key=settings.API_KEY)

        # Start worker threads
        LOG.debug('Starting %s worker threads...', SERVER_THREADS)
        for i in range(SERVER_THREADS):
            w = WorkerThread(self.queue, self.api)
            try:
                w.start()
            except Exception as e:
                LOG.error('Worker thread #%s did not start: %s', i, e)
                continue
            LOG.info('Started worker thread: %s', w.getName())

        while not self.shuttingdown:
            try:
                for check in settings.checks:
                    self.queue.put((check, time.time()))

                LOG.debug('Send heartbeat...')
                try:
                    origin = '{}/{}'.format('urlmon', platform.uname()[1])
                    self.api.heartbeat(origin, tags=[__version__])
                except Exception as e:
                    LOG.warning('Failed to send heartbeat: %s', e)

                time.sleep(LOOP_EVERY)
                LOG.info('URL check queue length is %d', self.queue.qsize())

            except (KeyboardInterrupt, SystemExit):
                self.shuttingdown = True

        LOG.info('Shutdown request received...')
        self.running = False

        for i in range(SERVER_THREADS):
            self.queue.put(None)
        w.join()
Beispiel #20
0
    def run(self):
        """Run the App main logic.

        This method should contain the core logic of the App.
        """
        alerta_api_key = self.tcex.playbook.read(self.args.alerta_api_key)
        alerta_api_endpoint = self.tcex.playbook.read(
            self.args.alerta_api_endpoint)
        resource = self.tcex.playbook.read(self.args.resource_under_alarm)
        event = self.tcex.playbook.read(self.args.event_name)
        severity = self.tcex.playbook.read(self.args.severity)
        service = self.tcex.playbook.read(self.args.services, True)
        environment = self.tcex.playbook.read(self.args.environment)

        # initialize alerta client
        client = Client(endpoint=alerta_api_endpoint, key=alerta_api_key)

        new_alert = client.send_alert(resource,
                                      event,
                                      severity=severity,
                                      environment=environment,
                                      service=service)[1]
        self.tcex.playbook.create_output('alerta.alertId', new_alert.id)
Beispiel #21
0
 def setUp(self):
     self.client = Client(endpoint='http://api:8080', key='demo-key')
Beispiel #22
0
    def run(self):

        while True:
            LOG.debug('Waiting on input queue...')
            try:
                check, queue_time = self.queue.get()
            except TypeError:
                LOG.info('%s is shutting down.', self.getName())
                break

            if time.time() - queue_time > LOOP_EVERY:
                LOG.warning(
                    'URL request for %s to %s expired after %d seconds.',
                    check['resource'], check['url'],
                    int(time.time() - queue_time))
                self.queue.task_done()
                continue

            resource = check['resource']
            LOG.info('%s polling %s...', self.getName(), resource)
            status, reason, body, rtt = self.urlmon(check)

            status_regex = check.get('status_regex', None)
            search_string = check.get('search', None)
            rule = check.get('rule', None)
            warn_thold = check.get('warning', SLOW_WARNING_THRESHOLD)
            crit_thold = check.get('critical', SLOW_CRITICAL_THRESHOLD)
            checker_api = check.get('api_endpoint', None)
            checker_apikey = check.get('api_key', None)
            if (checker_api and checker_apikey):
                local_api = Client(endpoint=checker_api, key=checker_apikey)
            else:
                local_api = self.api

            try:
                description = HTTP_RESPONSES[status]
            except KeyError:
                description = 'undefined'

            if not status:
                event = 'HttpConnectionError'
                severity = 'major'
                value = reason
                text = 'Error during connection or data transfer (timeout=%d).' % MAX_TIMEOUT

            elif status_regex:
                if re.search(status_regex, str(status)):
                    event = 'HttpResponseRegexOK'
                    severity = 'normal'
                    value = '%s (%d)' % (description, status)
                    text = 'HTTP server responded with status code %d that matched "%s" in %dms' % (
                        status, status_regex, rtt)
                else:
                    event = 'HttpResponseRegexError'
                    severity = 'major'
                    value = '%s (%d)' % (description, status)
                    text = 'HTTP server responded with status code %d that failed to match "%s"' % (
                        status, status_regex)

            elif 100 <= status <= 199:
                event = 'HttpInformational'
                severity = 'normal'
                value = '%s (%d)' % (description, status)
                text = 'HTTP server responded with status code %d in %dms' % (
                    status, rtt)

            elif 200 <= status <= 299:
                event = 'HttpResponseOK'
                severity = 'normal'
                value = '%s (%d)' % (description, status)
                text = 'HTTP server responded with status code %d in %dms' % (
                    status, rtt)

            elif 300 <= status <= 399:
                event = 'HttpRedirection'
                severity = 'minor'
                value = '%s (%d)' % (description, status)
                text = 'HTTP server responded with status code %d in %dms' % (
                    status, rtt)

            elif 400 <= status <= 499:
                event = 'HttpClientError'
                severity = 'minor'
                value = '%s (%d)' % (description, status)
                text = 'HTTP server responded with status code %d in %dms' % (
                    status, rtt)

            elif 500 <= status <= 599:
                event = 'HttpServerError'
                severity = 'major'
                value = '%s (%d)' % (description, status)
                text = 'HTTP server responded with status code %d in %dms' % (
                    status, rtt)

            else:
                event = 'HttpUnknownError'
                severity = 'warning'
                value = 'UNKNOWN'
                text = 'HTTP request resulted in an unhandled error.'

            if event in ['HttpResponseOK', 'HttpResponseRegexOK']:
                if rtt > crit_thold:
                    event = 'HttpResponseSlow'
                    severity = 'critical'
                    value = '%dms' % rtt
                    text = 'Website available but exceeding critical RT thresholds of %dms' % crit_thold
                elif rtt > warn_thold:
                    event = 'HttpResponseSlow'
                    severity = 'warning'
                    value = '%dms' % rtt
                    text = 'Website available but exceeding warning RT thresholds of %dms' % warn_thold
                if search_string and body:
                    LOG.debug('Searching for %s', search_string)
                    found = False
                    for line in body.split('\n'):
                        m = re.search(search_string, line)
                        if m:
                            found = True
                            LOG.debug("Regex: Found %s in %s", search_string,
                                      line)
                            break
                    if not found:
                        event = 'HttpContentError'
                        severity = 'minor'
                        value = 'Search failed'
                        text = 'Website available but pattern "%s" not found' % search_string
                elif rule and body:
                    LOG.debug('Evaluating rule %s', rule)
                    headers = check.get('headers', {})
                    if 'Content-type' in headers and headers[
                            'Content-type'] == 'application/json':
                        try:
                            body = json.loads(body)
                        except ValueError as e:
                            LOG.error('Could not evaluate rule %s: %s', rule,
                                      e)
                    try:
                        eval(
                            rule
                        )  # NOTE: assumes request body in variable called 'body'
                    except (SyntaxError, NameError, ZeroDivisionError) as e:
                        LOG.error('Could not evaluate rule %s: %s', rule, e)
                    except Exception as e:
                        LOG.error('Could not evaluate rule %s: %s', rule, e)
                    else:
                        if not eval(rule):
                            event = 'HttpContentError'
                            severity = 'minor'
                            value = 'Rule failed'
                            text = 'Website available but rule evaluation failed (%s)' % rule

            LOG.debug("URL: %s, Status: %s (%s), Round-Trip Time: %dms -> %s",
                      check['url'], description, status, rtt, event)

            resource = check['resource']
            correlate = _HTTP_ALERTS
            group = 'Web'
            environment = check['environment']
            service = check['service']
            text = text
            tags = check.get('tags', list())
            threshold_info = "%s : RT > %d RT > %d x %s" % (
                check['url'], warn_thold, crit_thold, check.get('count', 1))

            try:
                local_api.send_alert(
                    resource=resource,
                    event=event,
                    correlate=correlate,
                    group=group,
                    value=value,
                    severity=severity,
                    environment=environment,
                    service=service,
                    text=text,
                    event_type='serviceAlert',
                    tags=tags,
                    attributes={'thresholdInfo': threshold_info})
            except Exception as e:
                LOG.warning('Failed to send alert: %s', e)

            self.queue.task_done()
            LOG.info('%s check complete.', self.getName())

        self.queue.task_done()
Beispiel #23
0
def main():

    config_file = os.environ.get('ALERTA_CONF_FILE') or OPTIONS['config_file']

    config = configparser.RawConfigParser(defaults=OPTIONS)
    try:
        config.read(os.path.expanduser(config_file))
    except Exception:
        sys.exit("Problem reading configuration file %s - is this an ini file?" % config_file)

    parser = argparse.ArgumentParser(
        prog='zabbix-alerta',
        usage='zabbix-alerta SENDTO SUMMARY BODY',
        description='Zabbix-to-Alerta integration script',
        epilog=epilog,
        formatter_class=argparse.RawTextHelpFormatter
    )
    parser.add_argument(
        'sendto',
        help='config profile or alerta API endpoint and key'
    )
    parser.add_argument(
        'summary',
        help='alert summary'
    )
    parser.add_argument(
        'body',
        help='alert body (see format below)'
    )
    args, left = parser.parse_known_args()

    # sendto=apiUrl[;key]
    if args.sendto.startswith('http://') or args.sendto.startswith('https://'):
        want_profile = None
        try:
            OPTIONS['endpoint'], OPTIONS['key'] = args.sendto.split(';', 1)
        except ValueError:
            OPTIONS['endpoint'] = args.sendto
    # sendto=profile
    else:
        want_profile = args.sendto or os.environ.get('ALERTA_DEFAULT_PROFILE') or config.defaults().get('profile')

        if want_profile and config.has_section('profile %s' % want_profile):
            for opt in OPTIONS:
                try:
                    OPTIONS[opt] = config.getboolean('profile %s' % want_profile, opt)
                except (ValueError, AttributeError):
                    OPTIONS[opt] = config.get('profile %s' % want_profile, opt)
        else:
            for opt in OPTIONS:
                try:
                    OPTIONS[opt] = config.getboolean('DEFAULT', opt)
                except (ValueError, AttributeError):
                    OPTIONS[opt] = config.get('DEFAULT', opt)

    parser.set_defaults(**OPTIONS)
    args = parser.parse_args()

    if args.debug or not os.path.isdir('/var/log/zabbix'):
        LOG.basicConfig(stream=sys.stderr, format=LOG_FORMAT, datefmt=LOG_DATE_FMT, level=LOG.DEBUG)
    else:
        LOG.basicConfig(filename=LOG_FILE, format=LOG_FORMAT, datefmt=LOG_DATE_FMT, level=LOG.INFO)

    LOG.info("[alerta] endpoint=%s key=%s", args.endpoint, args.key)
    api = Client(endpoint=args.endpoint, key=args.key, ssl_verify=args.sslverify)

    LOG.debug("[alerta] sendto=%s, summary=%s, body=%s", args.sendto, args.summary, args.body)
    try:
        alert = parse_zabbix(args.summary, args.body)
        api.send_alert(**alert)
    except (SystemExit, KeyboardInterrupt):
        LOG.warning("Exiting zabbix-alerta.")
        sys.exit(0)
    except Exception as e:
        LOG.error(e, exc_info=1)
        sys.exit(1)
    def setUp(self):
        self.client = Client()

        self.alert = """
    def setUp(self):
        self.client = Client()

        self.customer = """
def cli(sendto, summary, body):
    """
        Zabbix-to-Alerta integration script

    INSTALL

       $ ln -s `which zabbix-alerta` <AlertScriptsPath>

    ALERT FORMAT

    OPERATIONS

    Default subject:

    {TRIGGER.STATUS}: {TRIGGER.NAME}

    Default message:

    \b
    resource={HOST.NAME1}
    event={ITEM.KEY1}
    environment=Production
    severity={TRIGGER.SEVERITY}!!
    status={TRIGGER.STATUS}
    ack={EVENT.ACK.STATUS}
    service={TRIGGER.HOSTGROUP.NAME}
    group=Zabbix
    value={ITEM.VALUE1}
    text={TRIGGER.STATUS}: {TRIGGER.NAME}
    tags={EVENT.TAGS}
    attributes.ip={HOST.IP1}
    attributes.thresholdInfo={TRIGGER.TEMPLATE.NAME}: {TRIGGER.EXPRESSION}
    attributes.moreInfo=<a href="http://x.x.x.x/tr_events.php?triggerid={TRIGGER.ID}&eventid={EVENT.ID}">Zabbix console</a>
    type=zabbixAlert
    dateTime={EVENT.DATE}T{EVENT.TIME}Z

    RECOVERY

    Default subject:

    {TRIGGER.STATUS}: {TRIGGER.NAME}

    Default message:

    \b
    resource={HOST.NAME1}
    event={ITEM.KEY1}
    environment=Production
    severity={TRIGGER.SEVERITY}!!
    status={TRIGGER.STATUS}
    ack={EVENT.ACK.STATUS}
    service={TRIGGER.HOSTGROUP.NAME}
    group=Zabbix
    value={ITEM.VALUE1}
    text={TRIGGER.STATUS}: {ITEM.NAME1}
    tags={EVENT.RECOVERY.TAGS}
    attributes.ip={HOST.IP1}
    attributes.thresholdInfo={TRIGGER.TEMPLATE.NAME}: {TRIGGER.EXPRESSION}
    attributes.moreInfo=<a href="http://x.x.x.x/tr_events.php?triggerid={TRIGGER.ID}&eventid={EVENT.RECOVERY.ID}">Zabbix console</a>
    type=zabbixAlert
    dateTime={EVENT.RECOVERY.DATE}T{EVENT.RECOVERY.TIME}Z
    """

    # FIXME - use {ITEM.APPLICATION} for alert "group" when ZBXNEXT-2684 is resolved (see https://support.zabbix.com/browse/ZBXNEXT-2684)

    click.echo('[alerta] Sending message "{}" to {}...'.format(summary, sendto))

    options = default_config
    parser = configparser.RawConfigParser(defaults=options)

    options['config_file'] = os.environ.get('ALERTA_CONF_FILE') or options['config_file']
    parser.read(os.path.expanduser(options['config_file']))

    # sendto=apiUrl[;key]
    if sendto.startswith('http://') or sendto.startswith('https://'):
        want_profile = None
        try:
            options['endpoint'], options['key'] = sendto.split(';', 1)
        except ValueError:
            options['endpoint'] = sendto
    # sendto=profile
    else:
        want_profile = sendto or os.environ.get('ALERTA_DEFAULT_PROFILE') or parser.defaults().get('profile')

        if want_profile and parser.has_section('profile %s' % want_profile):
            for opt in options:
                try:
                    options[opt] = parser.getboolean('profile %s' % want_profile, opt)
                except (ValueError, AttributeError):
                    options[opt] = parser.get('profile %s' % want_profile, opt)
        else:
            for opt in options:
                try:
                    options[opt] = parser.getboolean('DEFAULT', opt)
                except (ValueError, AttributeError):
                    options[opt] = parser.get('DEFAULT', opt)

    options['profile'] = want_profile
    options['endpoint'] = os.environ.get('ALERTA_ENDPOINT', options['endpoint'])
    options['key'] = os.environ.get('ALERTA_API_KEY', options['key'])

    api = Client(
        endpoint=options['endpoint'], key=options['key'], timeout=options['timeout'], ssl_verify=options['sslverify']
    )

    try:
        alert = parse_zabbix(summary, body)
        api.send_alert(**alert)
    except Exception as e:
        click.secho('ERROR: {}'.format(e))
        raise click.Abort()

    click.echo('Successfully sent message "{}" to {}!'.format(summary, options['endpoint']))
Beispiel #27
0
    def setUp(self):
        self.client = Client()

        self.user = """
Beispiel #28
0
def alerta_api(alerta_config):
    endpoint = "http://{0}:{1}/api".format(alerta_config["alerta_host"],
                                           alerta_config["alerta_port"])
    client = Client(endpoint=endpoint, ssl_verify=False)
    return client
Beispiel #29
0
    def setUp(self):
        self.client = Client()

        self.key = """
Beispiel #30
0
    timeout = 900

try:
    origin = client.kv.get('alerta/origin')[1]['Value']
except TypeError:
    print("No value defined, using default")
    origin = "consul"

try:
    alerttype = client.kv.get('alerta/alerttype')[1]['Value']
except TypeError:
    print("No value defined, using default")
    alerttype = "ConsulAlert"


api = Client(endpoint=url, key=key)

SEVERITY_MAP = {
    'critical':   'critical',
    'warning':    'warning',
    'passing':    'ok',
}

def createalert( data ):
    try:
        environment = client.kv.get('alerta/env/{0}'.format(data['Node']))[1]['Value']
    except:
        try:
             environment = client.kv.get('alerta/defaultenv')[1]['Value']
        except:
             environment = "Production"