コード例 #1
0
    def notify(self, level, alert, value, target=None, ntype=None, rule=None):
        LOGGER.debug("Handler (%s) %s", self.name, level)
        message = self.get_short(level, alert, value, target=target, ntype=ntype, rule=rule)
        LOGGER.debug('message1:%s', message)
        if level == 'normal':
            event_type = 'resolve'
        else:
            event_type = 'trigger'

        headers = {
            "Content-type": "application/json",
        }

        client_url = None
        if target:
            client_url = alert.get_graph_url(target)
        incident_key = 'graphite connect error'
        if rule:
            incident_key = "alert={},rule={}".format(alert.name, rule['raw'])

        data = {
            "service_key": self.service_key,
            "event_type": event_type,
            "description": message,
            "details": message,
            "incident_key": incident_key,
            "client": 'graphite-beacon',
            "client_url": client_url
        }
        yield self.client.fetch(
            "https://events.pagerduty.com/generic/2010-04-15/create_event.json",
            body=json.dumps(data),
            headers=headers,
            method='POST'
        )
コード例 #2
0
    def _respond_commands(self, update_response):

        if update_response.exception():
            LOGGER.error(str(update_response.exception()))

        update_content = update_response.result().body
        if not update_content:
            return
        else:
            update_content = json.loads(update_content)

        for update in update_content["result"]:
            message = update["message"]["text"].encode("utf-8")
            msp = message.split()
            self._last_update = update["update_id"]
            if msp[0].startswith("/activate"):
                try:
                    if msp[1] == self.bot_ident:
                        LOGGER.debug(
                            "Adding chat [%s] to notify list.", update["message"]["chat"]["id"])
                        self._chats.append(update["message"]["chat"]["id"])
                    yield self.client.fetch(
                        self.url + "sendMessage", body=json.dumps({
                            "chat_id": update["message"]["chat"]["id"],
                            "reply_to_message_id": update["message"]["message_id"],
                            "text": "Activated!"}),
                        method="POST",
                        headers={"Content-Type": "application/json"})
                except:
                    continue
            else:
                continue
コード例 #3
0
ファイル: pagerduty.py プロジェクト: Hodov/graphite-beacon
    def notify(self, level, alert, value, target=None, ntype=None, rule=None):
        LOGGER.debug("Handler (%s) %s", self.name, level)
        message = self.get_short(level, alert, value, target=target, ntype=ntype, rule=rule)
        LOGGER.debug('message1:%s', message)
        if level == 'normal':
            event_type = 'resolve'
        else:
            event_type = 'trigger'

        headers = {
            "Content-type": "application/json",
        }

        data = {
            "service_key": self.service_key,
            "event_type": event_type,
            "description": message,
            "details": message,
            "incident_key":  rule['raw'] if rule is not None else 'graphite connect error',
            "client": 'graphite-beacon',
            "client_url": None
        }
        yield self.client.fetch(
            "https://events.pagerduty.com/generic/2010-04-15/create_event.json",
            body=json.dumps(data),
            headers=headers,
            method='POST'
        )
コード例 #4
0
    def notify(self, level, *args, **kwargs):
        LOGGER.debug("Handler (%s) %s", self.name, level)

        msg = self.get_message(level, *args, **kwargs)
        msg['Subject'] = self.get_short(level, *args, **kwargs)
        msg['From'] = self.options['from']
        msg['To'] = ", ".join(self.options['to'])

        smtp = SMTP()
        yield smtp_connect(smtp, self.options['host'], self.options['port'])  # pylint: disable=no-value-for-parameter

        if self.options['use_tls']:
            yield smtp_starttls(smtp)  # pylint: disable=no-value-for-parameter

        if self.options['username'] and self.options['password']:
            yield smtp_login(
                smtp,  # pylint: disable=no-value-for-parameter
                self.options['username'],
                self.options['password'])

        try:
            LOGGER.debug("Send message to: %s", ", ".join(self.options['to']))
            smtp.sendmail(self.options['from'], self.options['to'],
                          msg.as_string())
        finally:
            smtp.quit()
コード例 #5
0
    def notify(self, level, *args, **kwargs):

        LOGGER.debug("Handler (%s) %s", self.name, level)

        message = self.get_message(level, *args, **kwargs)
        for chat in self._chats:
            yield self.client.fetch(
                self.url + "sendMessage", body=json.dumps({"chat_id": chat, "text": message}),
                method="POST", headers={"Content-Type": "application/json"})
コード例 #6
0
def get_chatlist(chatfile):
    """Try reading ids of saved chats from file.
    If we fail, return empty set"""
    if not chatfile:
        return set()
    try:
        with open(chatfile) as file_contents:
            return set(int(chat) for chat in file_contents)
    except (OSError, IOError) as exc:
        LOGGER.error('could not load saved chats:\n%s', exc)
        return set()
コード例 #7
0
    def notify(self, level, alert, value, target=None, ntype=None, rule=None):
        LOGGER.debug("Handler (%s) %s", self.name, level)

        message = self.get_short(level, alert, value, target=target, ntype=ntype, rule=rule)
        data = {'entity_display_name': alert.name, 'state_message': message, 'message_type': level}
        if target:
            data['target'] = target
        if rule:
            data['rule'] = rule['raw']
        body = json.dumps(data)
        headers = {'Content-Type': 'application/json;'}
        yield self.client.fetch(self.url, method="POST", body=body, headers=headers)
コード例 #8
0
    def notify(self, level, *args, **kwargs):
        """Sends alerts to telegram chats.
        This method is called from top level module.
        Do not rename it.
        """

        LOGGER.debug('Handler (%s) %s', self.name, level)

        notify_text = self.get_message(level, *args, **kwargs)
        for chat in self.chats.copy():
            data = {"chat_id": chat, "text": notify_text}
            yield self.client.send_message(data)
コード例 #9
0
ファイル: slack.py プロジェクト: yakaas/graphite-beacon
    def notify(self, level, *args, **kwargs):
        LOGGER.debug("Handler (%s) %s", self.name, level)

        message = self.get_message(level, *args, **kwargs)
        data = dict()
        data['username'] = self.username
        data['text'] = message
        data['icon_emoji'] = self.emoji.get(level, ':warning:')
        if self.channel:
            data['channel'] = self.channel

        body = json.dumps(data)
        yield self.client.fetch(self.webhook, method='POST', body=body)
コード例 #10
0
ファイル: slack.py プロジェクト: Hodov/graphite-beacon
    def notify(self, level, *args, **kwargs):
        LOGGER.debug("Handler (%s) %s", self.name, level)

        message = self.get_message(level, *args, **kwargs)
        data = dict()
        data['username'] = self.username
        data['text'] = message
        data['icon_emoji'] = self.emoji.get(level, ':warning:')
        if self.channel:
            data['channel'] = self.channel

        body = json.dumps(data)
        yield self.client.fetch(self.webhook, method='POST', body=body)
コード例 #11
0
    def notify(self, level, *args, **kwargs):
        LOGGER.debug("Handler (%s) %s", self.name, level)

        data = {
            'message': self.get_short(level, *args, **kwargs).decode('UTF-8'),
            'notify': True,
            'color': self.colors.get(level, 'gray'),
            'message_format': 'text',
        }

        yield self.client.fetch('{url}/v2/room/{room}/notification?auth_token={token}'.format(
            url=self.options.url, room=self.room, token=self.key), headers={
                'Content-Type': 'application/json'}, method='POST', body=json.dumps(data))
コード例 #12
0
    def _respond_commands(self, update_response):
        """Extract commands to bot from update and
        act accordingly. For description of commands,
        see HELP_MESSAGE variable on top of this module.
        """

        chatfile = self.chatfile
        chats = self.chats

        exc, upd = update_response.exception(), update_response.result().body
        if exc:
            LOGGER.error(str(exc))
        if not upd:
            return

        data = get_data(upd, self.bot_ident)
        for update_id, chat_id, message_id, command in data:
            self._last_update = update_id
            chat_is_known = chat_id in chats
            chats_changed = False
            reply_text = None

            if command == '/activate':
                if chat_is_known:
                    reply_text = 'This chat is already activated.'
                else:
                    LOGGER.debug('Adding chat [%s] to notify list.', chat_id)
                    reply_text = 'Activated.'
                    chats.add(chat_id)
                    chats_changed = True

            elif command == '/deactivate':
                if chat_is_known:
                    LOGGER.debug('Deleting chat [%s] from notify list.',
                                 chat_id)
                    reply_text = 'Deactivated.'
                    chats.remove(chat_id)
                    chats_changed = True

            if chats_changed and chatfile:
                write_to_file(chats, chatfile)

            elif command == '/help':
                reply_text = HELP_MESSAGE

            else:
                LOGGER.warning('Could not parse command: '
                               'bot ident is wrong or missing')

            if reply_text:
                yield self.client.send_message({
                    'chat_id': chat_id,
                    'reply_to_message_id': message_id,
                    'text': reply_text,
                    'parse_mode': 'Markdown',
                })
コード例 #13
0
ファイル: http.py プロジェクト: Hodov/graphite-beacon
    def notify(self, level, alert, value, target=None, ntype=None, rule=None):
        LOGGER.debug("Handler (%s) %s", self.name, level)

        message = self.get_short(level, alert, value, target=target, ntype=ntype, rule=rule)
        data = {'alert': alert.name, 'desc': message, 'level': level}
        if target:
            data['target'] = target
        if rule:
            data['rule'] = rule['raw']

        if alert.source == 'graphite':
            data['graph_url'] = alert.get_graph_url(target)
            data['value'] = value

        data.update(self.params)
        body = urllib.urlencode(data)
        yield self.client.fetch(self.url, method=self.method, body=body)
コード例 #14
0
ファイル: cli.py プロジェクト: yakaas/graphite-beacon
    def notify(self, level, *args, **kwargs):
        LOGGER.debug("Handler (%s) %s", self.name, level)

        def getAlertName(*args):
            name = str(args[0])
            # remove time characteristics e.g. (1minute)
            return name.rsplit(' ', 1)[0].strip()

        # Run only for whitelisted names if specified
        if not self.whitelist or getAlertName(*args) in self.whitelist:
            command = substituteVariables(self.commandTemplate, level, *args,
                                          **kwargs)
            subprocess.Popen(command,
                             shell=True,
                             stdin=None,
                             stdout=None,
                             stderr=None,
                             close_fds=True)
コード例 #15
0
ファイル: cli.py プロジェクト: klen/graphite-beacon
    def notify(self, level, *args, **kwargs):
        LOGGER.debug("Handler (%s) %s", self.name, level)

        def get_alert_name(*args):
            name = str(args[0])
            # remove time characteristics e.g. (1minute)
            return name.rsplit(' ', 1)[0].strip()

        # Run only for whitelisted names if specified
        if not self.whitelist or get_alert_name(*args) in self.whitelist:
            command = substitute_variables(self.command_template, level, *args, **kwargs)
            subprocess.Popen(
                command,
                shell=True,
                stdin=None,
                stdout=None,
                stderr=None,
                close_fds=True)
コード例 #16
0
    def init_handler(self):

        token = self.options.get('token')
        assert token, 'Telegram bot API token is not defined.'

        self.client = CustomClient(token)

        self.bot_ident = self.options.get('bot_ident')
        assert self.bot_ident, 'Telegram bot ident token is not defined.'

        chatfile = self.options.get('chatfile')
        if not chatfile:
            LOGGER.warning('chatfile not found in configs')
        elif not exists(chatfile):
            LOGGER.error('chatfile specified in configs does not exist')
            chatfile = None
        self.chatfile = chatfile
        self.chats = get_chatlist(self.chatfile)

        self._listen_commands()
コード例 #17
0
ファイル: smtp.py プロジェクト: Hodov/graphite-beacon
    def notify(self, level, *args, **kwargs):
        LOGGER.debug("Handler (%s) %s", self.name, level)

        msg = self.get_message(level, *args, **kwargs)
        msg['Subject'] = self.get_short(level, *args, **kwargs)
        msg['From'] = self.options['from']
        msg['To'] = ", ".join(self.options['to'])

        smtp = SMTP()
        yield smtp_connect(smtp, self.options['host'], self.options['port'])

        if self.options['use_tls']:
            yield smtp_starttls(smtp)

        if self.options['username'] and self.options['password']:
            yield smtp_login(smtp, self.options['username'], self.options['password'])

        try:
            LOGGER.debug("Send message to: %s", ", ".join(self.options['to']))
            smtp.sendmail(self.options['from'], self.options['to'], msg.as_string())
        finally:
            smtp.quit()
コード例 #18
0
    def notify(self, level, alert, value, target=None, ntype=None, rule=None):
        LOGGER.debug("Handler (%s) %s", self.name, level)

        message = self.get_short(level,
                                 alert,
                                 value,
                                 target=target,
                                 ntype=ntype,
                                 rule=rule)
        data = {'alert': alert.name, 'desc': message, 'level': level}
        if target:
            data['target'] = target
        if rule:
            data['rule'] = rule['raw']

        if alert.source == 'graphite':
            data['graph_url'] = alert.get_graph_url(target)
            data['value'] = value

        data.update(self.params)
        body = urllib.urlencode(data)
        yield self.client.fetch(self.url, method=self.method, body=body)