예제 #1
0
파일: tasks.py 프로젝트: tsibley/redash
def notify_hipchat(alert, html, new_state):
    try:
        if settings.HIPCHAT_API_URL:
            hipchat_client = hipchat.HipChat(token=settings.HIPCHAT_API_TOKEN, url=settings.HIPCHAT_API_URL)
        else:
            hipchat_client = hipchat.HipChat(token=settings.HIPCHAT_API_TOKEN)
        message = '[' + new_state.upper() + '] ' + alert.name + '<br />' + html
        hipchat_client.message_room(settings.HIPCHAT_ROOM_ID, settings.NAME, message.encode('utf-8', 'ignore'), message_format='html')
    except Exception:
        logger.exception("hipchat send ERROR.")
예제 #2
0
 def notify(self, alert, query, user, new_state, app, host, options):
     try:
         if options.url:
             hipchat_client = hipchat.HipChat(token=options.token, url=options.url)
         else:
             hipchat_client = hipchat.HipChat(token=options.token)
         html = """
         Check <a href="{host}/alerts/{alert_id}">alert</a> / check <a href="{host}/queries/{query_id}">query</a>.
         """.format(host=host, alert_id=alert.id, query_id=query.id)
         message = '[' + new_state.upper() + '] ' + alert.name + '<br />' + html
         hipchat_client.message_room(options.room_id, settings.NAME, message.encode('utf-8', 'ignore'), message_format='html')
     except Exception:
         logging.exception("hipchat send ERROR.")
예제 #3
0
 def __init__(self, bus):
     self.bus = bus
     self.bus.subscribe(self.process_event, thread=True)
     self.hc = hipchat.HipChat(token=config.hipchat_token)
     self.room = config.hipchat_room
     self.name = 'FoosBot'
     self.players = {}
예제 #4
0
def statuspage_route():
    """Send alerts for statuspage.io webhooks to rooms listed in STATUSPAGE_NOTIFY_ROOMS"""

    notification = json.loads(request.data)

    if 'component_update' in notification:
        page_id = notification['page']['id']
        component_update = notification['component_update']
        component_id = component_update['component_id']
        component_name = get_component_name(page_id, component_id)
        old_status = component_update['old_status']
        new_status = component_update['new_status']
        color = hipchat_notification_color[new_status]
        message = "[%s] status changed from %s to %s" % (component_name, old_status, new_status)

    elif 'incident' in notification:
        incident_update = notification['incident']
        incident_name = incident_update['name']
        incident_status = incident_update['status']
        incident_message = incident_update['incident_updates'][0]['body']
        color = hipchat_notification_color[incident_status]
        message = "[%s] %s: %s" % (incident_name, incident_status, incident_message)

    hipchat_api = hipchat.HipChat(token=STATUSPAGE_HIPCHAT_TOKEN)
    for channel in STATUSPAGE_NOTIFY_ROOMS.split(','):
        hipchat_api.message_room(channel, STATUSPAGE_NOTIFY_NAME, message, notify=True, color=color)

    body = { "action": "message sent" }

    return jsonify(body)
예제 #5
0
def alert_hipchat(alert, metric):
    """
    Called by :func:`~trigger_alert` and sends an alert the hipchat room that is
    configured in settings.py.
    """
    sender = settings.HIPCHAT_OPTS['sender']
    import hipchat
    hipster = hipchat.HipChat(token=settings.HIPCHAT_OPTS['auth_token'])
    rooms = settings.HIPCHAT_OPTS['rooms'][alert[0]]

    graph_title = '&title=skyline%%20analyzer%%20ALERT%%20at%%20%s%%20hours%%0A%s%%20-%%20%s' % (str(int(full_duration_in_hours)), metric[1], metric[0])
    if settings.GRAPHITE_PORT != '':
        # @modified 20190520 - Branch #3002: docker
        # link = '%s://%s:%s/render/?from=-%shour&target=cactiStyle(%s)%s%s&colorList=orange' % (settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, settings.GRAPHITE_PORT, str(int(full_duration_in_hours)), metric[1], settings.GRAPHITE_GRAPH_SETTINGS, graph_title)
        # @modified 20200417 - Task #3294: py3 - handle system parameter in Graphite cactiStyle
        # link = '%s://%s:%s/%s/?from=-%shour&target=cactiStyle(%s)%s%s&colorList=orange' % (
        link = '%s://%s:%s/%s/?from=-%shour&target=cactiStyle(%s,%%27si%%27)%s%s&colorList=orange' % (
            settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, settings.GRAPHITE_PORT,
            settings.GRAPHITE_RENDER_URI, str(int(full_duration_in_hours)), metric[1],
            settings.GRAPHITE_GRAPH_SETTINGS, graph_title)
    else:
        # @modified 20190520 - Branch #3002: docker
        # link = '%s://%s/render/?from=-%shour&target=cactiStyle(%s)%s%s&colorList=orange' % (settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, str(int(full_duration_in_hours)), metric[1], settings.GRAPHITE_GRAPH_SETTINGS, graph_title)
        # @modified 20200417 - Task #3294: py3 - handle system parameter in Graphite cactiStyle
        # link = '%s://%s/%s/?from=-%shour&target=cactiStyle(%s)%s%s&colorList=orange' % (
        link = '%s://%s/%s/?from=-%shour&target=cactiStyle(%s,%%27si%%27)%s%s&colorList=orange' % (
            settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST,
            settings.GRAPHITE_RENDER_URI, str(int(full_duration_in_hours)), metric[1],
            settings.GRAPHITE_GRAPH_SETTINGS, graph_title)
    embed_graph = "<a href='" + link + "'><img height='308' src='" + link + "'>" + metric[1] + "</a>"

    for room in rooms:
        hipster.method('rooms/message', method='POST', parameters={'room_id': room, 'from': 'skyline', 'color': settings.HIPCHAT_OPTS['color'], 'message': '%s - analyzer - Anomalous metric: %s (value: %s) at %s hours %s' % (sender, metric[1], metric[0], str(int(full_duration_in_hours)), embed_graph)})
예제 #6
0
    def __init__(self):
        self.enabled = "HIPCHAT_TOKEN" in os.environ
        if not self.enabled:
            return

        # make sure we got our imports
        if not hipchat:
            raise ImportError(
                "The hipchat plugin requires the hipchat Python module, "
                "which is not installed or was not found.")
        if not prettytable:
            raise ImportError(
                "The hipchat plugin requires the prettytable Python module, "
                "which is not installed or was not found.")
        self.start_time = time.time()
        self.task_report = []
        self.last_task = None
        self.last_task_changed = False
        self.last_task_count = 0
        self.last_task_delta = 0
        self.last_task_start = time.time()
        self.condensed_task_report = (os.getenv('HIPCHAT_CONDENSED',
                                                True) == True)
        self.room = os.getenv('HIPCHAT_ROOM', 'ansible')
        self.from_name = os.getenv('HIPCHAT_FROM', 'ansible')
        self.allow_notify = (os.getenv('HIPCHAT_NOTIFY') != 'false')
        try:
            self.hipchat_conn = hipchat.HipChat(
                token=os.getenv('HIPCHAT_TOKEN'))
        except Exception as e:
            utils.warning("Unable to connect to hipchat: {}".format(e))
        self.hipchat_msg_prefix = os.getenv('HIPCHAT_MSG_PREFIX', '')
        self.hipchat_msg_color = os.getenv('HIPCHAT_MSG_COLOR', '')
        self.printed_playbook = False
        self.playbook_name = None
예제 #7
0
def alert_hipchat(alert, metric, second_order_resolution_seconds):
    """
    Called by :func:`~trigger_alert` and sends an alert the hipchat room that is
    configured in settings.py.
    """

    # SECOND_ORDER_RESOLUTION_SECONDS to hours so that Mirage surfaces the
    # relevant timeseries data in the graph
    second_order_resolution_in_hours = int(second_order_resolution_seconds) / 3600

    if settings.HIPCHAT_ENABLED:
        sender = settings.HIPCHAT_OPTS['sender']
        import hipchat
        hipster = hipchat.HipChat(token=settings.HIPCHAT_OPTS['auth_token'])
        rooms = settings.HIPCHAT_OPTS['rooms'][alert[0]]

        unencoded_graph_title = 'Skyline Mirage - ALERT at %s hours - anomalous data point - %s' % (
            second_order_resolution_in_hours, metric[0])
        graph_title_string = quote(unencoded_graph_title, safe='')
        graph_title = '&title=%s' % graph_title_string

        if settings.GRAPHITE_PORT != '':
            link = '%s://%s:%s/render/?from=-%shour&target=cactiStyle(%s)%s%s&colorList=orange' % (settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, settings.GRAPHITE_PORT, second_order_resolution_in_hours, metric[1], settings.GRAPHITE_GRAPH_SETTINGS, graph_title)
        else:
            link = '%s://%s/render/?from=-%shour&target=cactiStyle(%s)%s%s&colorList=orange' % (settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, second_order_resolution_in_hours, metric[1], settings.GRAPHITE_GRAPH_SETTINGS, graph_title)
        embed_graph = "<a href='" + link + "'><img height='308' src='" + link + "'>" + metric[1] + "</a>"

        for room in rooms:
            hipster.method('rooms/message', method='POST', parameters={'room_id': room, 'from': 'skyline', 'color': settings.HIPCHAT_OPTS['color'], 'message': '%s - Mirage - Anomalous metric: %s (value: %s) at %s hours %s' % (sender, metric[1], metric[0], second_order_resolution_in_hours, embed_graph)})
    else:
        return False
예제 #8
0
    def __init__(self):

        if 'HIPCHAT_TOKEN' in os.environ:
            self.start_time = time.time()
            self.task_report = []
            self.last_task = None
            self.last_task_changed = False
            self.last_task_count = 0
            self.last_task_delta = 0
            self.last_task_start = time.time()
            self.condensed_task_report = (os.getenv('HIPCHAT_CONDENSED',
                                                    True) == True)
            self.room = os.getenv('HIPCHAT_ROOM', 'ansible')
            self.from_name = os.getenv('HIPCHAT_FROM', 'ansible')
            self.allow_notify = (os.getenv('HIPCHAT_NOTIFY') != 'false')
            try:
                self.hipchat_conn = hipchat.HipChat(
                    token=os.getenv('HIPCHAT_TOKEN'))
            except Exception as e:
                utils.warning("Unable to connect to hipchat: {}".format(e))
            self.hipchat_msg_prefix = os.getenv('HIPCHAT_MSG_PREFIX', '')
            self.hipchat_msg_color = os.getenv('HIPCHAT_MSG_COLOR', '')
            self.printed_playbook = False
            self.playbook_name = None
            self.enabled = True
        else:
            self.enabled = False
예제 #9
0
파일: alerters.py 프로젝트: kryptx/skyline
def alert_hipchat(alert, metric):
    import hipchat
    hipster = hipchat.HipChat(token = settings.HIPCHAT_OPTS['auth_token'])
    rooms = settings.HIPCHAT_OPTS['rooms'][alert[0]]
    link = '%s/render/?width=588&height=308&target=%s' % (settings.GRAPHITE_HOST, metric[1])

    for room in rooms:
        hipster.method('rooms/message', method='POST', parameters={'room_id': room, 'from': 'Skyline', 'color': settings.HIPCHAT_OPTS['color'], 'message': 'Anomaly: <a href="%s">%s</a> : %s' % (link, metric[1], metric[0])})
예제 #10
0
def alert_hipchat(alert, metric):
    import hipchat
    hipster = hipchat.HipChat(token=settings.HIPCHAT_OPTS['auth_token'])
    rooms = settings.HIPCHAT_OPTS['rooms'][alert[0]]
    link = settings.GRAPH_URL % (metric[1])

    for room in rooms:
        hipster.method('rooms/message', method='POST', parameters={'room_id': room, 'from': 'cloudbrain', 'color': settings.HIPCHAT_OPTS['color'], 'message': 'Anomaly: <a href="%s">%s</a> : %s' % (link, metric[1], metric[0])})
예제 #11
0
def deploy(upgrade_env=False, reload_nginx=False, soft=False):
    """
    Update Server to latest code revision.
    * `upgrade_env=True to update the virtual env
    * `reload_nginx=True` to reload nginx
    * `soft=True` if changes don't affect celery (usually just aesthetic
      changes: html, css)
    """

    print "Using Github User: %s" % env.server_github_user

    with cd(env.PROJECT_ROOT):
        sudo('git pull', user=env.server_github_user)

        with cd('src'):
            if upgrade_env:
                sudo(env.PIP + ' install -r requirements.txt --upgrade',
                     user=env.server_github_user)
            else:
                sudo(env.PIP + ' install -r requirements.txt',
                     user=env.server_github_user)

            # sudo(env.PYTHON_INTERPRETER + ' manage.py syncdb --migrate',
            #      user=env.server_github_user)
            sudo(env.PYTHON + ' manage.py collectstatic --noinput',
                 user=env.server_github_user)

    if soft:
        # Only restart gunicorn
        sudo('/usr/bin/supervisorctl stop %s%s' %
             (env.SUPERVISOR_GROUP, env.SUPERVISOR_GUNICORN_NAME))
        sudo('/usr/bin/supervisorctl start %s%s' %
             (env.SUPERVISOR_GROUP, env.SUPERVISOR_GUNICORN_NAME))
    else:
        for worker in env.SUPERVISOR_CELERY_WORKER_NAMES:
            sudo('/usr/bin/supervisorctl stop %s%s' %
                 (env.SUPERVISOR_GROUP, worker))
        sudo('/usr/bin/supervisorctl stop %s%s' %
             (env.SUPERVISOR_GROUP, env.SUPERVISOR_CELERY_BEAT_NAME))
        sudo('/usr/bin/supervisorctl stop %s' % env.SUPERVISOR_GROUP)
        sudo('/usr/bin/supervisorctl start %s' % env.SUPERVISOR_GROUP)

    if reload_nginx:
        sudo('/etc/init.d/nginx reload')

    # Send notification to HipChat
    if hasattr(env, 'server_name') and HIPCHAT_TOKEN:
        # Notification to HipChat
        hc = hipchat.HipChat(token=HIPCHAT_TOKEN)
        msg = 'Hey team, %s just deployed to %s' % (env.user, env.server_name)
        hc.method('rooms/message',
                  parameters={
                      'room_id': 440862,
                      'from': 'Deployer',
                      'message': msg,
                      'message_format': 'text',
                      'notify': 1
                  })
예제 #12
0
def chat(text, color=None):
    parameters = {'room_id':'143582',
                  'message': text,
                  'from': 'paul'
                  }
    if color:
        parameters['color'] = color
    chat = hipchat.HipChat(token="<INSERT_TOKEN_HERE>")
    chat.method("rooms/message", method="POST", parameters=parameters)
예제 #13
0
def annoy_route(channel):
    """Spam a particular room"""

    hipchat_api = hipchat.HipChat(token=ANNOY_HIPCHAT_TOKEN)
    hipchat_api.message_room(channel, 'Screamer', 'test', notify=True)

    body = {"action": "message sent"}

    return jsonify(body)
예제 #14
0
def send_hipchat_message(message):
    #If hipchat is configured send the details to the specified room
    if args.hipchat_api_token and args.hipchat_room_id:
        import hipchat
        try:
            hipchat = hipchat.HipChat(token=args.hipchat_api_token)
            hipchat.message_room(args.hipchat_room_id, 'AbbeyNormal', message)
        except Exception as e:
            print("Hipchat messaging resulted in an error: %s." % e)
    def __init__(self, storage, config):
        super(HipChatNotifier, self).__init__(storage, config)
        self._rooms = set()

        required = ['HIPCHAT_KEY', 'HIPCHAT_ROOM']
        self.enabled = config.has_keys(required)
        if self.enabled:
            self._client = hipchat.HipChat(config.get('HIPCHAT_KEY'))
            self.add_room(config.get('HIPCHAT_ROOM'))
예제 #16
0
파일: tasks.py 프로젝트: aadu/redash
def notify_hipchat(alert, html, new_state):
    try:
        hipchat_client = hipchat.HipChat(token=settings.HIPCHAT_API_TOKEN)
        message = '[' + new_state.upper() + '] ' + alert.name + '<br />' + html
        hipchat_client.message_room(settings.HIPCHAT_ROOM_ID,
                                    settings.NAME,
                                    message,
                                    message_format='html')
    except:
        logger.exception("hipchat send ERROR.")
예제 #17
0
파일: __init__.py 프로젝트: kabisote/muninn
    def run(self, events):
        config = self.config
        hipster = hipchat.HipChat(token=config.get("token"))
        template = Template(config.get("template_message"))

        for event in events:
            message = template.render(data=event.data)
            hipster.message_room(config.get("room_id"),
                                 config.get("sender", 'Munnin'), message)
            event.done()
예제 #18
0
def alert_hipchat(datapoint, metric_name, expiration_time, metric_trigger, algorithm):

    if settings.HIPCHAT_ENABLED:
        sender = settings.BOUNDARY_HIPCHAT_OPTS['sender']
        import hipchat
        hipster = hipchat.HipChat(token=settings.BOUNDARY_HIPCHAT_OPTS['auth_token'])

        # Allow for absolute path metric namespaces but also allow for and match
        # match wildcard namepaces if there is not an absolute path metric namespace
        rooms = 'unknown'
        notify_rooms = []
        matched_rooms = []
        try:
            rooms = settings.BOUNDARY_HIPCHAT_OPTS['rooms'][metric_name]
            notify_rooms.append(rooms)
        except:
            for room in settings.BOUNDARY_HIPCHAT_OPTS['rooms']:
                print(room)
                CHECK_MATCH_PATTERN = room
                check_match_pattern = re.compile(CHECK_MATCH_PATTERN)
                pattern_match = check_match_pattern.match(metric_name)
                if pattern_match:
                    matched_rooms.append(room)

        if matched_rooms != []:
            for i_metric_name in matched_rooms:
                rooms = settings.BOUNDARY_HIPCHAT_OPTS['rooms'][i_metric_name]
                notify_rooms.append(rooms)

        alert_algo = str(algorithm)
        alert_context = alert_algo.upper()

        unencoded_graph_title = 'Skyline Boundary - %s at %s hours - %s - %s' % (
            alert_context, graphite_previous_hours, metric_name, datapoint)
        graph_title_string = quote(unencoded_graph_title, safe='')
        graph_title = '&title=%s' % graph_title_string

        if settings.GRAPHITE_PORT != '':
            link = '%s://%s:%s/render/?from=-%shour&target=cactiStyle(%s)%s%s&colorList=%s' % (
                settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, settings.GRAPHITE_PORT,
                graphite_previous_hours, metric_name, settings.GRAPHITE_GRAPH_SETTINGS,
                graph_title, graphite_graph_line_color)
        else:
            link = '%s://%s/render/?from=-%shour&target=cactiStyle(%s)%s%s&colorList=%s' % (
                settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, graphite_previous_hours,
                metric_name, settings.GRAPHITE_GRAPH_SETTINGS, graph_title,
                graphite_graph_line_color)

        embed_graph = "<a href='" + link + "'><img height='308' src='" + link + "'>" + metric_name + "</a>"

        for rooms in notify_rooms:
            for room in rooms:
                hipster.method('rooms/message', method='POST', parameters={'room_id': room, 'from': 'skyline', 'color': settings.BOUNDARY_HIPCHAT_OPTS['color'], 'message': '%s - Boundary - %s - Anomalous metric: %s (value: %s) at %s hours %s' % (sender, algorithm, metric_name, datapoint, graphite_previous_hours, embed_graph)})
    else:
        return False
예제 #19
0
파일: alerts.py 프로젝트: klynch/skyline
def alert_hipchat(metric, datapoint, ensemble, args, settings):
    import hipchat
    hipster = hipchat.HipChat(token=settings['auth_token'])
    rooms = args['rooms']
    link = ""  # settings.GRAPH_URL.format(metric)
    # body = 'Anomalous metric: {0} (datapoint: {1})<br><a href="{2}"><img src="{2}"/></a>'.format(metric, datapoint, link)
    body = 'Anomalous metric: {0} (datapoint: {1})'.format(metric, datapoint)
    for room in rooms:
        hipster.method('rooms/message', method='POST', parameters={'room_id': room,
                                                                   'from': 'Skyline',
                                                                   'color': settings.get('color', 'red'),
                                                                   'message': body})
예제 #20
0
    def __init__(self, name, room, token):
        if not room:
            raise exceptions.InvalidAuditorConfigurationException(
                'Missing HipChat room name!')
        if not token:
            raise exceptions.InvalidAuditorConfigurationException(
                'Missing HipChat API token!')

        self._name = name if name else maestro_name
        self._room = room

        import hipchat
        self._hc = hipchat.HipChat(token)
예제 #21
0
def hipchat_broadcast(by='HipChat',
                      message='Hello, World!',
                      room_id=HIPCHAT_CODE_ROOM_ID):
    """Says random stuff on our Hipchat boards."""
    hip = hipchat.HipChat(token=HIPCHAT_API_TOKEN)
    hip.method("rooms/message",
               method="POST",
               parameters={
                   "room_id": room_id,
                   "from": by,
                   "message": message,
                   "message_format": "text"
               })
예제 #22
0
def send_hipchat(rooms, text, color='green'):
    hipster = hipchat.HipChat(token=HIPCHAT_API_KEY)
    for room in rooms:
        hipster.method('rooms/message',
                       method='POST',
                       parameters={
                           'room_id': room,
                           'from': 'IVR Bot',
                           'message': text,
                           'notify': 1,
                           'color': color
                       })
    return True
예제 #23
0
def send_hipchat_message(message):
    print(message)
    if args.callback_url:
        r = requests.get("{}/{}".format(args.callback_url, message))
    else:
        #If hipchat is configured send the details to the specified room
        if args.hipchat_api_token and args.hipchat_room_id:
            import hipchat
            try:
                hipchat = hipchat.HipChat(token=args.hipchat_api_token)
                hipchat.message_room(args.hipchat_room_id, 'AbbeyNormal',
                                     message)
            except Exception as e:
                print("Hipchat messaging resulted in an error: %s." % e)
예제 #24
0
def alert_hipchat(alert, metric):
    """
    Called by :func:`~trigger_alert` and sends an alert the hipchat room that is
    configured in settings.py.
    """

    if settings.HIPCHAT_ENABLED:
        sender = settings.HIPCHAT_OPTS['sender']
        import hipchat
        hipster = hipchat.HipChat(token=settings.HIPCHAT_OPTS['auth_token'])
        rooms = settings.HIPCHAT_OPTS['rooms'][alert[0]]

        unencoded_graph_title = 'Skyline Analyzer - ALERT at %s hours %s - %s' % (
            full_duration_in_hours, metric[1], metric[0])
        graph_title_string = quote(unencoded_graph_title, safe='')
        graph_title = '&title=%s' % graph_title_string

        if settings.GRAPHITE_PORT != '':
            link = '%s://%s:%s/render/?from=-%shours&target=cactiStyle(%s)%s%s&colorList=orange' % (
                settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST,
                settings.GRAPHITE_PORT, full_duration_in_hours, metric[1],
                settings.GRAPHITE_GRAPH_SETTINGS, graph_title)
        else:
            link = '%s://%s/render/?from=-%shours&target=cactiStyle(%s)%s%s&colorList=orange' % (
                settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST,
                full_duration_in_hours, metric[1],
                settings.GRAPHITE_GRAPH_SETTINGS, graph_title)
        embed_graph = "<a href='" + link + "'><img height='308' src='" + link + "'>" + metric[
            1] + "</a>"

        for room in rooms:
            message = '%s - Analyzer - anomalous metric: %s (value: %s) at %s hours %s' % (
                sender, metric[1], metric[0], full_duration_in_hours,
                embed_graph)
            hipchat_color = settings.HIPCHAT_OPTS['color']
            hipster.method('rooms/message',
                           method='POST',
                           parameters={
                               'room_id': room,
                               'from': 'Skyline',
                               'color': hipchat_color,
                               'message': message
                           })
    else:
        return
예제 #25
0
def alert_hipchat(alert, metric, second_order_resolution_seconds, context):
    """
    Called by :func:`~trigger_alert` and sends an alert the hipchat room that is
    configured in settings.py.
    """

    # SECOND_ORDER_RESOLUTION_SECONDS to hours so that Mirage surfaces the
    # relevant timeseries data in the graph
    second_order_resolution_in_hours = int(second_order_resolution_seconds) / 3600

    if settings.HIPCHAT_ENABLED:
        sender = settings.HIPCHAT_OPTS['sender']
        import hipchat
        hipster = hipchat.HipChat(token=settings.HIPCHAT_OPTS['auth_token'])
        rooms = settings.HIPCHAT_OPTS['rooms'][alert[0]]
        unencoded_graph_title = 'Skyline %s - ALERT at %s hours - %s' % (
            context, str(int(second_order_resolution_in_hours)), str(metric[0]))
        graph_title_string = quote(unencoded_graph_title, safe='')
        graph_title = '&title=%s' % graph_title_string

        # @added 20180809 - Bug #2498: Incorrect scale in some graphs
        # If -xhours is used the scale is incorrect if x hours > than first
        # retention period, passing from and until renders the graph with the
        # correct scale.
        from_timestamp = int(time())
        until_timestamp = from_timestamp - int(second_order_resolution_seconds)
        graphite_from = dt.datetime.fromtimestamp(int(from_timestamp)).strftime('%H:%M_%Y%m%d')
        logger.info('graphite_from - %s' % str(graphite_from))
        graphite_until = dt.datetime.fromtimestamp(int(until_timestamp)).strftime('%H:%M_%Y%m%d')
        logger.info('graphite_until - %s' % str(graphite_until))

        if settings.GRAPHITE_PORT != '':
            # @modified 20180809 - Bug #2498: Incorrect scale in some graphs
            # link = '%s://%s:%s/render/?from=-%shour&target=cactiStyle(%s)%s%s&colorList=orange' % (settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, settings.GRAPHITE_PORT, str(int(second_order_resolution_in_hours)), metric[1], settings.GRAPHITE_GRAPH_SETTINGS, graph_title)
            link = '%s://%s:%s/render/?from=%s&until=%s&target=cactiStyle(%s)%s%s&colorList=orange' % (settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, settings.GRAPHITE_PORT, str(graphite_from), str(graphite_until), metric[1], settings.GRAPHITE_GRAPH_SETTINGS, graph_title)
        else:
            # @modified 20180809 - Bug #2498: Incorrect scale in some graphs
            # link = '%s://%s/render/?from=-%shour&target=cactiStyle(%s)%s%s&colorList=orange' % (settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, str(int(second_order_resolution_in_hours)), metric[1], settings.GRAPHITE_GRAPH_SETTINGS, graph_title)
            link = '%s://%s/render/?from=%s&until=%s&target=cactiStyle(%s)%s%s&colorList=orange' % (settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, str(graphite_from), str(graphite_until), metric[1], settings.GRAPHITE_GRAPH_SETTINGS, graph_title)
        embed_graph = "<a href='" + link + "'><img height='308' src='" + link + "'>" + metric[1] + "</a>"

        for room in rooms:
            hipster.method('rooms/message', method='POST', parameters={'room_id': room, 'from': 'skyline', 'color': settings.HIPCHAT_OPTS['color'], 'message': '%s - %s - Anomalous metric: %s (value: %s) at %s hours %s' % (sender, context, metric[1], str(metric[0]), str(int(second_order_resolution_in_hours)), embed_graph)})
    else:
        return False
예제 #26
0
    def send_notification(self, subject, message, recipient=None):

        try:

            room_id = recipient or self.room_id
            logger.info("Sending notification hipchat '%s'..." % subject)
            hipster = hipchat.HipChat(token=self.api_token)

            hipchat_message = "%s\n\n%s" % (subject, message)
            # limit message to 9000 chars
            if len(hipchat_message) > 9000:
                hipchat_message = hipchat_message[:9000] + "..."
            hipster.message_room(room_id, self.from_name, hipchat_message, color=self.color)

            logger.info("Hipchat sent successfully!")
        except Exception, e:
            logger.error("Error while sending hipchat message:\n%s" %
                         traceback.format_exc())
예제 #27
0
    def handle(self, *args, **kwargs):
        today = date.today()
        events = Event.objects.filter(start_time__year=today.year,
                                      start_time__month=today.month,
                                      start_time__day=today.day,
                                      location__icontains='minna')
        # TODO Ask if precise location can be used: 410 Minna St, San Francisco

        hipster = hipchat.HipChat(token=HIPCHAT_API_TOKEN)
        for event in events:
            vendors = [vendor.name for vendor in event.vendors.all()]

            if not vendors:
                vendors = [('Checkout https://facebook.com/events/{}'
                            ' for more information.'.format(event.fb_id))]

            message = '\n'.join([event.name] + vendors)
            hipster.message_room(HIPCHAT_ROOM_ID, 'foodiebot', message)
예제 #28
0
def main(**kwargs):
    global arg
    arg = kwargs

    hipster = hipchat.HipChat(token=arg['hipchattoken'])
    params = {
        'duration': arg['duration'],
        'subject[chart][id]': arg['chartid'],
        'subject[chart][source]': '',
        'subject[chart][type]': arg['charttype']
    }
    url = 'https://metrics.librato.com/metrics-api/v1/snapshots'
    snapshotRequest = requests.post(url,
                                    params=params,
                                    auth=(arg['username'], arg['password']))

    if snapshotRequest.status_code == 401:
        print("Not Authorized Librato")
        sys.exit(2)

    snapshotRequestResponse = json.loads(snapshotRequest.text)
    print(snapshotRequestResponse['href'])

    readyImage = False
    while not readyImage:
        snapshotImageRequest = requests.get(snapshotRequestResponse['href'],
                                            auth=(arg['username'],
                                                  arg['password']))
        imageHref = json.loads(snapshotImageRequest.text)['image_href']
        if imageHref:
            hipster.method('rooms/message',
                           method='POST',
                           parameters={
                               'room_id': arg['hipchatroomid'],
                               'from': 'Librato',
                               'message': "<img src='{0}' />".format(imageHref)
                           })
            readyImage = True
        else:
            time.sleep(1)

    sys.exit(0)
예제 #29
0
def alert_hipchat(alert, metric, second_order_resolution_seconds):

    # SECOND_ORDER_RESOLUTION_SECONDS to hours so that mirage surfaces the
    # relevant timeseries data in the graph
    second_order_resolution_in_hours = int(
        second_order_resolution_seconds) / 3600

    sender = settings.HIPCHAT_OPTS['sender']
    import hipchat
    hipster = hipchat.HipChat(token=settings.HIPCHAT_OPTS['auth_token'])
    rooms = settings.HIPCHAT_OPTS['rooms'][alert[0]]
    graph_title = '&title=skyline%%20mirage%%20ALERT%%20at%%20%s%%20hours%%0A%s%%20-%%20%s' % (
        second_order_resolution_in_hours, metric[1], metric[0])
    if settings.GRAPHITE_PORT != '':
        link = '%s://%s:%s/render/?from=-%shour&target=cactiStyle(%s)%s%s&colorList=orange' % (
            settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST,
            settings.GRAPHITE_PORT, second_order_resolution_in_hours,
            metric[1], settings.GRAPHITE_GRAPH_SETTINGS, graph_title)
    else:
        link = '%s://%s/render/?from=-%shour&target=cactiStyle(%s)%s%s&colorList=orange' % (
            settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST,
            second_order_resolution_in_hours, metric[1],
            settings.GRAPHITE_GRAPH_SETTINGS, graph_title)
    embed_graph = "<a href='" + link + "'><img height='308' src='" + link + "'>" + metric[
        1] + "</a>"

    for room in rooms:
        hipster.method(
            'rooms/message',
            method='POST',
            parameters={
                'room_id':
                room,
                'from':
                'skyline',
                'color':
                settings.HIPCHAT_OPTS['color'],
                'message':
                '%s - mirage - Anomalous metric: %s (value: %s) at %s hours %s'
                % (sender, metric[1], metric[0],
                   second_order_resolution_in_hours, embed_graph)
            })
예제 #30
0
def post_todays_minna_vendors():
    """
	Posts today's trucks on minna street to hipchat server
	"""
    address = '410 Minna St'
    hipchat_token = '35b7de36961929ed984c34bbfc0d08'
    hipchat_room_id = 320022
    hipchat_user = '******'
    hipster = hipchat.HipChat(token=hipchat_token)

    lst = facebook_scraper.scrape_todays_vendors(address)
    if lst:  # make get_vendors_list is populated
        rtn_str = "Today's trucks: " + ', '.join(lst)
        hipster.method('rooms/message',
                       method='POST',
                       parameters={
                           'room_id': hipchat_room_id,
                           'from': hipchat_user,
                           'message': rtn_str
                       })