Esempio n. 1
0
    def _to_status(self, issue):
        """Return a status or None."""
        logging.debug('Handling %s' % (issue.fields.summary))

        # Guess the level.
        if callable(self.defcon):
            defcon = self.defcon(issue)
        else:
            defcon = self.defcon

        data = dict(issue.raw)
        data['me'] = data['self']
        data['issue'] = issue
        data['permalink'] = issue.permalink()
        del data['self']
        status = base.Status(
            self.render(self.title_template, data),
            defcon,
            self.render(self.link_template, data),
            description=self.render(self.description_template, data),
            # TODO: use some custom fields for dates.
            # time_start=dateparse.parse_datetime(alert['startsAt']),
            # time_end=dateparse.parse_datetime(alert['endsAt']),
        )
        return status
Esempio n. 2
0
    def _to_status(self, root_alert, block, alert):
        """Return a status or None."""
        logging.debug('Handling %s' % (alert))
        if not self.match_labels(alert['labels'], self.labels):
            return None
        if self.receiver is not None:
            if block['routeOpts']['receiver'] != self.receiver:
                return None
        if alert.get('inhibited') or alert.get('silenced'):
            logging.debug('alert is inactived')
            return None

        # Guess the level.
        if type(self.defcon) == int:
            defcon = self.defcon
        elif callable(self.defcon):
            defcon = self.defcon(alert)
        else:
            defcon = int(alert['labels'][self.defcon])

        status = base.Status(
            self.render(self.title_template, alert),
            defcon,
            self.render(self.link_template, alert),
            description=self.render(self.description_template, alert),
            time_start=dateparse.parse_datetime(alert['startsAt']),
            time_end=dateparse.parse_datetime(alert['endsAt']),
        )
        return status
Esempio n. 3
0
    def test_simple(self):
        """Test __init__."""
        p = static.StaticPlugin()
        self.assertEquals(p.short_name, 'static')

        s = base.Status('test', 2, 'test')
        p = static.StaticPlugin({'statuses': [s]})
        self.assertEquals(p.statuses(), {s['id']: s})
Esempio n. 4
0
 def _to_status(self, payload, url):
     """Return a status or None."""
     logging.debug('Handling %s' % (url))
     # if endpoint doesn't have all the infos
     # default message will be send
     status = base.Status(
         title=payload.get('name', "name not found from {}".format(url)),
         link=payload.get('link', "link not from {}".format(url)),
         defcon=payload.get('defcon', 5),
         description=payload.get('description', "description not found from {}".format(url)),
     )
     return status
Esempio n. 5
0
    def test_run_update_status(self):
        out = StringIO()
        self.addCleanup(out.close)
        status = base.Status('Test status', 5, 'http://foo/#5')

        with self.components_with_plugin(status):
            management.call_command('runplugins', stdout=out)

            status.description = 'status description'

            management.call_command('runplugins', stdout=out)
            self.assertIn("Running test Production:Fake plugin", out.getvalue())
            self.assertIn("Updated Fake plugin:Test status", out.getvalue())

            status_model = models.Status.objects.all()[0]
            self.assertEqual(status_model.description, status['description'])
Esempio n. 6
0
    def test_basic(self):
        """Test that we can create statuses."""
        s = base.Status('Test status',
                        5,
                        'http://github.com/criteo/defcon',
                        description='This is a test')
        expected = {
            'defcon': 5,
            'title': 'Test status',
            'description': 'This is a test',
            'link': 'http://github.com/criteo/defcon',
            'id': uuid.UUID('235c445a-cd6f-5f46-91af-bada596275a6'),
            'time_start': None,
            'time_end': None,
        }

        self.assertEqual(dict(s), expected)
Esempio n. 7
0
    def test_basic(self):
        """Test that we can create statuses."""
        s = base.Status('Test status',
                        5,
                        'http://github.com/iksaif/defcon',
                        description='This is a test')
        expected = {
            'defcon': 5,
            'title': 'Test status',
            'description': 'This is a test',
            'link': 'http://github.com/iksaif/defcon',
            'id': uuid.UUID('971adc54-d615-59b7-a797-2b8167153174'),
            'time_start': None,
            'time_end': None,
        }

        self.assertEqual(dict(s), expected)
Esempio n. 8
0
    def test_run_add_status(self):
        out = StringIO()
        self.addCleanup(out.close)
        status = base.Status('Test status', 5, 'http://foo/#5')

        with self.components_with_plugin(status):
            management.call_command('runplugins', stdout=out)
            self.assertIn("Running test Production:Fake plugin",
                          out.getvalue())
            self.assertIn("Created Fake plugin:Test status", out.getvalue())

            status_model = models.Status.objects.get(id=status['id'])

            self.assertEqual(status_model.title, status['title'])
            self.assertEqual(status_model.link, status['link'])
            self.assertEqual(status_model.description, status['description'])
            self.assertEqual(status_model.defcon, status['defcon'])
            self.assertFalse(status_model.override)
Esempio n. 9
0
    def _to_status(self, alert):
        """Return a status or None."""
        logging.debug('Handling %s' % (alert))
        if not self.match_labels(alert['labels'], self.labels):
            return None
        status = alert.get('status', {})

        # Check Receiver
        if self.receiver is not None:
            if alert.get('receivers') is not None:
                receiverList = []
                for receveir in alert.get("receivers"):
                    if receveir["name"] is not None:
                        receiverList.append(receveir["name"])
                if self.receiver not in receiverList:
                    return None

        # Old API
        if alert.get('inhibited') or alert.get('silenced'):
            logging.debug('alert is inactive')
            return None
        # New API
        if status.get('state', 'active') != 'active':
            logging.debug('alert is inactived: %s' % status)
            return None

        # Guess the level.
        if type(self.defcon) == int:
            defcon = self.defcon
        elif callable(self.defcon):
            defcon = self.defcon(alert)
        else:
            defcon = int(alert['labels'][self.defcon])

        status = base.Status(
            self.render(self.title_template, alert),
            defcon,
            self.render(self.link_template, alert),
            description=self.render(self.description_template, alert),
            time_start=dateparse.parse_datetime(alert['startsAt']),
            time_end=dateparse.parse_datetime(alert['endsAt']),
        )
        return status
Esempio n. 10
0
"""Local settings."""
from defcon.plugins import base

SECRET_KEY = 'cepowqjcenwqcnewqoinwqowq'
DEBUG = True

ALERTMANAGER_URL = 'http://demo.robustperception.io:9093/api/v1/'

PLUGINS_PRODUCTION = [
    # Some static statuses.
    {
        'plugin': 'static',
        'name': 'static test',
        'config': {
            'statuses': [
                base.Status('Test status', 5, 'http://foo/#5'),
                base.Status('Other test', 2, 'http://bar/#1')
            ]
        }
    },
    # For a specific job.
    {
        'plugin': 'alertmanager',
        'name': 'alertmanager-labels',
        'config': {
            'api': ALERTMANAGER_URL,
            'labels': {
                'job': 'prometheus'
            },
            'defcon': 2,
        }
Esempio n. 11
0
    def statuses(self):
        """Return the generated statuses."""
        ret = {}

        if self._config is None:
            return ret
        if len(self.groups) > 0:
            h = self.zapi.host.get(groupids=self.groups,
                                   filter=self.f,
                                   output=['hostid', 'name'])
        else:
            h = self.zapi.host.get(filter=self.f, output=['hostid', 'name'])
        host_list = [p['hostid'] for p in h]
        host_dict = {a['hostid']: a['name'] for a in h}

        triggers = self.zapi.trigger.get(
            only_true=1,
            skipDependent=1,
            monitored=1,
            active=1,
            output='extend',
            expandDescription=1,
            filter={'hostid': host_list},
            selectHosts=host_list,
            selectTags='extend',
        )

        unack_triggers = self.zapi.trigger.get(
            only_true=1,
            skipDependent=1,
            monitored=1,
            active=1,
            output=['description', 'name', 'hosts'],
            expandDescription=1,
            filter={'hostid': host_list},
            selectHosts=host_list,
            withLastEventUnacknowledged=1,
        )
        unack_trigger_ids = [t['triggerid'] for t in unack_triggers]
        for t in triggers:
            t['unacknowledged'] = True if t['triggerid'] in unack_trigger_ids \
                else False
        for t in triggers:
            status = None
            if int(t['value']) != 1:
                continue
            if not t['unacknowledged']:
                continue
            if int(t['priority']) >= self.severity:
                # Try to
                try:
                    self.defcon = int({i['tag']: i['value'] \
                                       for i in t['tags']}['defcon'])
                except KeyError:
                    pass
                status = base.Status(
                    'zabbix alert, host: {}'.format(
                        host_dict[t['hosts'][0]['hostid']]),
                    self.defcon,
                    '{}/hostinventories.php?hostid={}&triggerid={}'.format(
                        self.api_url, t['hosts'][0]['hostid'], t['triggerid']),
                    description='desc: {}'.format(t['description']),
                    time_start=self.time,
                )
                if status is not None:
                    ret[status['id']] = status

        return ret