Ejemplo n.º 1
0
def pagerduty():

    data = request.json

    updated = False
    if data and 'messages' in data:
        for message in data['messages']:
            try:
                incident_key, status, text = parse_pagerduty(message)
            except ValueError as e:
                raise ApiError(str(e), 400)

            if not incident_key:
                raise ApiError('no incident key in PagerDuty data payload', 400)

            customer = g.get('customer', None)
            try:
                alert = Alert.find_by_id(id=incident_key, customer=customer)
            except Exception as e:
                raise ApiError(str(e), 500)

            if not alert:
                raise ApiError("not found", 404)

            try:
                updated = alert.set_status(status, text)
            except Exception as e:
                raise ApiError(str(e), 500)
    else:
        raise ApiError("no messages in PagerDuty data payload", 400)

    if updated:
        return jsonify(status="ok"), 200
    else:
        raise ApiError("update PagerDuty incident status failed", 500)
Ejemplo n.º 2
0
def action_alerts(alerts: List[str], action: str, text: str, timeout: int) -> None:
    updated = []
    errors = []
    for alert_id in alerts:
        alert = Alert.find_by_id(alert_id)

        try:
            previous_status = alert.status
            alert, action, text = process_action(alert, action, text)
            alert = alert.from_action(action, text, timeout)
        except RejectException as e:
            errors.append(str(e))
            continue
        except InvalidAction as e:
            errors.append(str(e))
            continue
        except Exception as e:
            errors.append(str(e))
            continue

        if previous_status != alert.status:
            try:
                alert, status, text = process_status(alert, alert.status, text)
                alert = alert.from_status(status, text, timeout)
            except RejectException as e:
                errors.append(str(e))
                continue
            except Exception as e:
                errors.append(str(e))
                continue

        updated.append(alert.id)
Ejemplo n.º 3
0
def action_alerts(alerts: List[str], action: str, text: str,
                  timeout: Optional[int]) -> None:
    updated = []
    errors = []
    for alert_id in alerts:
        alert = Alert.find_by_id(alert_id)

        try:
            previous_status = alert.status
            alert, action, text, timeout = process_action(
                alert, action, text, timeout)
            alert = alert.from_action(action, text, timeout)
        except RejectException as e:
            errors.append(str(e))
            continue
        except InvalidAction as e:
            errors.append(str(e))
            continue
        except Exception as e:
            errors.append(str(e))
            continue

        if previous_status != alert.status:
            try:
                alert, status, text = process_status(alert, alert.status, text)
                alert = alert.from_status(status, text, timeout)
            except RejectException as e:
                errors.append(str(e))
                continue
            except Exception as e:
                errors.append(str(e))
                continue

        updated.append(alert.id)
Ejemplo n.º 4
0
    def incoming(self, query_string, payload):

        updated = False
        if payload and 'messages' in payload:
            for message in payload['messages']:
                try:
                    incident_key, status, text = parse_pagerduty(message)
                except ValueError as e:
                    raise ApiError(str(e), 400)

                if not incident_key:
                    raise ApiError('no incident key in PagerDuty data payload', 400)

                customers = g.get('customers', None)
                try:
                    alert = Alert.find_by_id(id=incident_key, customers=customers)
                except Exception as e:
                    raise ApiError(str(e), 500)

                if not alert:
                    raise ApiError('not found', 404)

                try:
                    updated = alert.set_status(status, text)
                except Exception as e:
                    raise ApiError(str(e), 500)

            if updated:
                return jsonify(status='ok')
            else:
                raise ApiError('update PagerDuty incident status failed', 500)

        else:
            raise ApiError('no messages in PagerDuty data payload', 400)
Ejemplo n.º 5
0
def add_note(alert_id):
    note_text = request.json.get('text') or request.json.get('note')

    if not note_text:
        raise ApiError("must supply 'note' text", 400)

    customers = g.get('customers', None)
    alert = Alert.find_by_id(alert_id, customers)

    if not alert:
        raise ApiError('not found', 404)

    try:
        alert, note_text = process_note(alert, note_text)
        note = alert.add_note(note_text)
    except RejectException as e:
        write_audit_trail.send(current_app._get_current_object(), event='alert-note-rejected', message='',
                               user=g.login, customers=g.customers, scopes=g.scopes, resource_id=note.id, type='note',
                               request=request)
        raise ApiError(str(e), 400)
    except ForwardingLoop as e:
        return jsonify(status='ok', message=str(e)), 202
    except AlertaException as e:
        raise ApiError(e.message, code=e.code, errors=e.errors)
    except Exception as e:
        raise ApiError(str(e), 500)

    write_audit_trail.send(current_app._get_current_object(), event='alert-note-added', message='', user=g.login,
                           customers=g.customers, scopes=g.scopes, resource_id=note.id, type='note', request=request)

    if note:
        return jsonify(status='ok', id=note.id, note=note.serialize), 201, {'Location': absolute_url('/alert/{}/note/{}'.format(alert.id, note.id))}
    else:
        raise ApiError('failed to add note for alert', 500)
Ejemplo n.º 6
0
def action_alert(alert_id):
    action = request.json.get('action', None)
    text = request.json.get('text', '%s operator action' % action)
    timeout = request.json.get('timeout', None)

    if not action:
        raise ApiError("must supply 'action' as json data", 400)

    customers = g.get('customers', None)
    alert = Alert.find_by_id(alert_id, customers)

    if not alert:
        raise ApiError('not found', 404)

    try:
        previous_status = alert.status
        alert, action, text = process_action(alert, action, text)
        alert = alert.from_action(action, text, timeout)
    except RejectException as e:
        raise ApiError(str(e), 400)
    except Exception as e:
        raise ApiError(str(e), 500)

    if previous_status != alert.status:
        try:
            alert, status, text = process_status(alert, alert.status, text)
        except RejectException as e:
            raise ApiError(str(e), 400)
        except Exception as e:
            raise ApiError(str(e), 500)

    if alert:
        return jsonify(status='ok')
    else:
        raise ApiError('failed to action alert', 500)
Ejemplo n.º 7
0
def delete_alert(alert_id):
    customers = g.get('customers', None)
    alert = Alert.find_by_id(alert_id, customers)

    if not alert:
        raise ApiError('not found', 404)

    try:
        deleted = process_delete(alert)
    except RejectException as e:
        write_audit_trail.send(current_app._get_current_object(), event='alert-delete-rejected', message=alert.text,
                               user=g.login, customers=g.customers, scopes=g.scopes, resource_id=alert.id, type='alert',
                               request=request)
        raise ApiError(str(e), 400)
    except AlertaException as e:
        raise ApiError(e.message, code=e.code, errors=e.errors)
    except Exception as e:
        raise ApiError(str(e), 500)

    write_audit_trail.send(current_app._get_current_object(), event='alert-deleted', message='', user=g.login,
                           customers=g.customers, scopes=g.scopes, resource_id=alert.id, type='alert', request=request)

    if deleted:
        return jsonify(status='ok')
    else:
        raise ApiError('failed to delete alert', 500)
Ejemplo n.º 8
0
def telegram():

    data = request.json
    if 'callback_query' in data:
        author = data['callback_query']['from']
        user = "******".format(author.get('first_name'), author.get('last_name'))
        command, alert_id = data['callback_query']['data'].split(' ', 1)

        alert = Alert.find_by_id(alert_id)
        if not alert:
            jsonify(status="error", message="alert not found for Telegram message")

        action = command.lstrip('/')
        if action in ['open', 'ack', 'close']:
            alert.set_status(status=action, text='status change via Telegram')
        elif action in ['watch', 'unwatch']:
            alert.untag(tags=["{}:{}".format(action, user)])
        elif action == 'blackout':
            environment, resource, event = alert.split('|', 2)
            blackout = Blackout(environment, resource=resource, event=event)
            blackout.create()

        send_message_reply(alert, action, user, data)
        return jsonify(status="ok")
    else:
        return jsonify(status="error", message="no callback_query in Telegram message"), 400
Ejemplo n.º 9
0
def delete_note(alert_id, note_id):
    customers = g.get('customers', None)
    alert = Alert.find_by_id(alert_id, customers)

    if not alert:
        raise ApiError('alert not found', 404)

    note = Note.find_by_id(note_id)

    if not note:
        raise ApiError('note not found', 404)

    write_audit_trail.send(current_app._get_current_object(),
                           event='alert-note-deleted',
                           message='',
                           user=g.login,
                           customers=g.customers,
                           scopes=g.scopes,
                           resource_id=note.id,
                           type='note',
                           request=request)

    if note.delete():
        return jsonify(status='ok')
    else:
        raise ApiError('failed to delete note', 500)
Ejemplo n.º 10
0
def pagerduty():

    data = request.json

    updated = False
    if data and 'messages' in data:
        for message in data['messages']:
            try:
                incident_key, status, text = parse_pagerduty(message)
            except ValueError as e:
                raise ApiError(str(e), 400)

            if not incident_key:
                raise ApiError('no incident key in PagerDuty data payload', 400)

            customers = g.get('customers', None)
            try:
                alert = Alert.find_by_id(id=incident_key, customers=customers)
            except Exception as e:
                raise ApiError(str(e), 500)

            if not alert:
                raise ApiError('not found', 404)

            try:
                updated = alert.set_status(status, text)
            except Exception as e:
                raise ApiError(str(e), 500)
    else:
        raise ApiError('no messages in PagerDuty data payload', 400)

    if updated:
        return jsonify(status='ok'), 200
    else:
        raise ApiError('update PagerDuty incident status failed', 500)
    def incoming(self, query_string, payload):
        # Note: This doesn't validate MS Teams Authorization: Bearer JWT
        # instead we're relying on alerta to validate X-API-Key header

        action = payload.get('action', 'missing')
        if action not in [ 'ack', 'close', 'blackout' ]:
            resp = make_response(jsonify(status='error', message='Invalid action'), 400)
            return resp

        if action in [ 'ack', 'close' ]:
            alert_id = payload.get('alert_id', None)
            err = make_response(jsonify(status='error', message='Missing/invalid alert_id'), 400)
            if not alert_id:
                return err

            try:
                # check that alert_id looks like uuid
                uuidval = UUID(alert_id, version=4)
                if str(uuidval) != alert_id.lower():
                    return err
            except Exception:
                return err

            alert = Alert.find_by_id(alert_id, customers=g.get('customers', None))
            if not alert:
                return err
            else:
                alert.set_status(status=action, text='status changed via MS Teams webhook')
                resp = make_response(jsonify(status='ok', message='status changed'), 200)
                resp.headers['CARD-ACTION-STATUS'] = 'Alert {}d'.format(action.capitalize())

                text = 'alert updated via msteams webhook'
                write_audit_trail.send(current_app._get_current_object(), event='webhook-updated', message=text,
                                       user=g.login, customers=g.customers, scopes=g.scopes, resource_id=alert.id,
                                       type='alert', request=request)

        elif action == 'blackout':
            environment = payload.get('environment', None)
            resource = payload.get('resource', None)
            event = payload.get('event', None)

            if environment and resource and event:
                duration = payload.get('duration', None) or current_app.config['BLACKOUT_DURATION']
                try:
                    if not duration or float(duration) < 0.0:
                        # Should not happen: set default duration
                        duration = 3600
                except ValueError:
                    # Should not happen: set default duration
                    duration = 3600
                blackout = Blackout(environment, resource=resource, event=event, duration=duration)
                blackout.create()
                resp = make_response(jsonify(status='ok', message='blackout created'), 201)
                resp.headers['CARD-ACTION-STATUS'] = 'Blackout created for {0:.1f} hours'.format(float(duration) / 3600)

            else:
                # Missging env, resource or event
                resp = make_response(jsonify(status='error', message='Missing blackout params'), 412)

        return resp
Ejemplo n.º 12
0
    def incoming(self, query_string, payload):

        if 'callback_query' in payload:
            author = payload['callback_query']['from']
            user = '******'.format(author.get('first_name'), author.get('last_name'))
            command, alert_id = payload['callback_query']['data'].split(' ', 1)

            customers = g.get('customers', None)
            alert = Alert.find_by_id(alert_id, customers=customers)
            if not alert:
                jsonify(status='error', message='alert not found for Telegram message')

            action = command.lstrip('/')
            if action in ['open', 'ack', 'close']:
                alert.set_status(status=action, text='status change via Telegram')
            elif action in ['watch', 'unwatch']:
                alert.untag(tags=['{}:{}'.format(action, user)])
            elif action == 'blackout':
                environment, resource, event = command.split('|', 2)
                blackout = Blackout(environment, resource=resource, event=event)
                blackout.create()

            send_message_reply(alert, action, user, payload)

            text = 'alert updated via telegram webhook'
            write_audit_trail.send(current_app._get_current_object(), event='webhook-updated', message=text,
                                   user=g.login, customers=g.customers, scopes=g.scopes, resource_id=alert.id,
                                   type='alert', request=request)

            return jsonify(status='ok')
        else:
            return jsonify(status='ok', message='no callback_query in Telegram message')
Ejemplo n.º 13
0
def add_note(alert_id):
    note_text = request.json.get('note', None)

    if not note_text:
        raise ApiError("must supply 'note' text")

    customers = g.get('customers', None)
    alert = Alert.find_by_id(alert_id, customers)

    if not alert:
        raise ApiError('not found', 404)

    note = alert.add_note(note_text)

    write_audit_trail.send(current_app._get_current_object(),
                           event='alert-note-added',
                           message='',
                           user=g.login,
                           customers=g.customers,
                           scopes=g.scopes,
                           resource_id=note.id,
                           type='note',
                           request=request)

    if note:
        return jsonify(status='ok', id=note.id, note=note.serialize), 201, {
            'Location':
            absolute_url('/alert/{}/note/{}'.format(alert.id, note.id))
        }
    else:
        raise ApiError('failed to add note for alert', 500)
Ejemplo n.º 14
0
def action_alert(alert_id):
    action = request.json.get('action', None)
    text = request.json.get('text', '%s operator action' % action)
    timeout = request.json.get('timeout', None)

    if not action:
        raise ApiError("must supply 'action' as json data", 400)

    customers = g.get('customers', None)
    alert = Alert.find_by_id(alert_id, customers)

    if not alert:
        raise ApiError('not found', 404)

    try:
        alert, action, text, timeout = process_action(alert, action, text, timeout)
        alert = alert.from_action(action, text, timeout)
    except RejectException as e:
        write_audit_trail.send(current_app._get_current_object(), event='alert-action-rejected', message=alert.text,
                               user=g.login, customers=g.customers, scopes=g.scopes, resource_id=alert.id, type='alert',
                               request=request)
        raise ApiError(str(e), 400)
    except InvalidAction as e:
        raise ApiError(str(e), 409)
    except Exception as e:
        raise ApiError(str(e), 500)

    write_audit_trail.send(current_app._get_current_object(), event='alert-actioned', message=text, user=g.login,
                           customers=g.customers, scopes=g.scopes, resource_id=alert.id, type='alert', request=request)

    if alert:
        return jsonify(status='ok')
    else:
        raise ApiError('failed to action alert', 500)
Ejemplo n.º 15
0
def set_status(alert_id):
    status = request.json.get('status', None)
    text = request.json.get('text', '')
    timeout = request.json.get('timeout', None)

    if not status:
        raise ApiError("must supply 'status' as json data", 400)

    customers = g.get('customers', None)
    alert = Alert.find_by_id(alert_id, customers)

    if not alert:
        raise ApiError('not found', 404)

    try:
        alert, status, text = process_status(alert, status, text)
        alert = alert.from_status(status, text, timeout)
    except RejectException as e:
        raise ApiError(str(e), 400)
    except Exception as e:
        raise ApiError(str(e), 500)

    write_audit_trail.send(current_app._get_current_object(), event='alert-status-changed', message=text, user=g.user,
                           customers=g.customers, scopes=g.scopes, resource_id=alert.id, type='alert', request=request)
    if alert:
        return jsonify(status='ok')
    else:
        raise ApiError('failed to set status', 500)
Ejemplo n.º 16
0
def update_attributes(alert_id):
    attributes = request.json.get('attributes', None)

    if not attributes:
        raise ApiError("must supply 'attributes' as json data", 400)

    customers = g.get('customers', None)
    alert = Alert.find_by_id(alert_id, customers)

    if not alert:
        raise ApiError('not found', 404)

    write_audit_trail.send(current_app._get_current_object(),
                           event='alert-attributes-updated',
                           message='',
                           user=g.login,
                           customers=g.customers,
                           scopes=g.scopes,
                           resource_id=alert.id,
                           type='alert',
                           request=request)

    if alert.update_attributes(attributes):
        return jsonify(status='ok')
    else:
        raise ApiError('failed to update attributes', 500)
Ejemplo n.º 17
0
def untag_alert(alert_id):
    tags = request.json.get('tags', None)

    if not tags:
        raise ApiError("must supply 'tags' as json list")

    customers = g.get('customers', None)
    alert = Alert.find_by_id(alert_id, customers)

    if not alert:
        raise ApiError('not found', 404)

    write_audit_trail.send(current_app._get_current_object(),
                           event='alert-untagged',
                           message='',
                           user=g.login,
                           customers=g.customers,
                           scopes=g.scopes,
                           resource_id=alert.id,
                           type='alert',
                           request=request)

    if alert.untag(tags):
        return jsonify(status='ok')
    else:
        raise ApiError('failed to untag alert', 500)
Ejemplo n.º 18
0
def telegram():

    data = request.json
    if 'callback_query' in data:
        author = data['callback_query']['from']
        user = "******".format(author.get('first_name'),
                              author.get('last_name'))
        command, alert_id = data['callback_query']['data'].split(' ', 1)

        alert = Alert.find_by_id(alert_id)
        if not alert:
            jsonify(status="error",
                    message="alert not found for Telegram message")

        action = command.lstrip('/')
        if action in ['open', 'ack', 'close']:
            alert.set_status(status=action, text='status change via Telegram')
        elif action in ['watch', 'unwatch']:
            alert.untag(tags=["{}:{}".format(action, user)])
        elif action == 'blackout':
            environment, resource, event = alert.split('|', 2)
            blackout = Blackout(environment, resource=resource, event=event)
            blackout.create()

        send_message_reply(alert, action, user, data)
        return jsonify(status="ok")
    else:
        return jsonify(status="error",
                       message="no callback_query in Telegram message"), 400
Ejemplo n.º 19
0
def add_note(alert_id):
    note = request.json.get('note', None)

    if not note:
        raise ApiError("must supply 'note' text")

    customers = g.get('customers', None)
    alert = Alert.find_by_id(alert_id, customers)

    if not alert:
        raise ApiError('not found', 404)

    write_audit_trail.send(current_app._get_current_object(),
                           event='alert-note-added',
                           message='',
                           user=g.login,
                           customers=g.customers,
                           scopes=g.scopes,
                           resource_id=alert.id,
                           type='alert',
                           request=request)

    if alert.add_note(note):
        return jsonify(status='ok')
    else:
        raise ApiError('failed to add note to alert', 500)
Ejemplo n.º 20
0
def update_note(alert_id, note_id):
    if not request.json:
        raise ApiError('nothing to change', 400)

    customers = g.get('customers', None)
    alert = Alert.find_by_id(alert_id, customers)

    if not alert:
        raise ApiError('not found', 404)

    note = Note.find_by_id(note_id)

    if not note:
        raise ApiError('not found', 404)

    update = request.json
    update['user'] = g.login

    write_audit_trail.send(current_app._get_current_object(),
                           event='alert-note-updated',
                           message='',
                           user=g.login,
                           customers=g.customers,
                           scopes=g.scopes,
                           resource_id=note.id,
                           type='note',
                           request=request)

    if note.update(**update):
        return jsonify(status='ok')
    else:
        raise ApiError('failed to update note', 500)
Ejemplo n.º 21
0
def set_status(alert_id):
    status = request.json.get('status', None)
    text = request.json.get('text', '')
    timeout = request.json.get('timeout', None)

    if not status:
        raise ApiError("must supply 'status' as json data")

    customers = g.get('customers', None)
    alert = Alert.find_by_id(alert_id, customers)

    if not alert:
        raise ApiError("not found", 404)

    try:
        alert, status, text = process_status(alert, status, text)
    except RejectException as e:
        raise ApiError(str(e), 400)
    except Exception as e:
        raise ApiError(str(e), 500)

    if alert.set_status(status, text, timeout):
        return jsonify(status="ok")
    else:
        raise ApiError("failed to set alert status", 500)
Ejemplo n.º 22
0
def action_alert(alert_id):
    action = request.json.get('action', None)
    text = request.json.get('text', '%s operator action' % action)
    timeout = request.json.get('timeout', None)

    if not action:
        raise ApiError("must supply 'action' as json data")

    customers = g.get('customers', None)
    alert = Alert.find_by_id(alert_id, customers)

    if not alert:
        raise ApiError("not found", 404)

    try:
        alert = process_action(alert, action, text, timeout)
    except RejectException as e:
        raise ApiError(str(e), 400)
    except Exception as e:
        raise ApiError(str(e), 500)

    if alert:
        return jsonify(status="ok")
    else:
        raise ApiError("failed to perform action", 500)
Ejemplo n.º 23
0
    def incoming(self, path, query_string, payload):

        alert_id, user, action = parse_slack(payload)

        customers = g.get('customers', None)
        alert = Alert.find_by_id(alert_id, customers=customers)
        if not alert:
            jsonify(status='error',
                    message='alert not found for #slack message')

        if action in ['open', 'ack', 'close']:
            alert.from_action(action,
                              text=f'status change via #slack by {user}')
        elif action in ['watch', 'unwatch']:
            alert.untag(tags=[f'{action}:{user}'])
        else:
            raise ApiError('Unsupported #slack action', 400)

        text = 'alert updated via slack webhook'
        write_audit_trail.send(current_app._get_current_object(),
                               event='webhook-updated',
                               message=text,
                               user=g.login,
                               customers=g.customers,
                               scopes=g.scopes,
                               resource_id=alert.id,
                               type='alert',
                               request=request)

        response = build_slack_response(alert, action, user, payload)
        return jsonify(**response), 201
Ejemplo n.º 24
0
def get_alert(alert_id):
    customer = g.get('customer', None)
    alert = Alert.find_by_id(alert_id, customer)

    if alert:
        return jsonify(status="ok", total=1, alert=alert.serialize)
    else:
        raise ApiError("not found", 404)
Ejemplo n.º 25
0
def get_alert(alert_id):
    customers = g.get('customers', None)
    alert = Alert.find_by_id(alert_id, customers)

    if alert:
        return jsonify(status='ok', total=1, alert=alert.serialize)
    else:
        raise ApiError('not found', 404)
Ejemplo n.º 26
0
def delete_alert(alert_id):
    customer = g.get('customer', None)
    alert = Alert.find_by_id(alert_id, customer)

    if not alert:
        raise ApiError("not found", 404)

    if alert.delete():
        return jsonify(status="ok")
    else:
        raise ApiError("failed to delete alert", 500)
Ejemplo n.º 27
0
def delete_alert(alert_id):
    customers = g.get('customers', None)
    alert = Alert.find_by_id(alert_id, customers)

    if not alert:
        raise ApiError('not found', 404)

    if alert.delete():
        return jsonify(status='ok')
    else:
        raise ApiError('failed to delete alert', 500)
Ejemplo n.º 28
0
def set_customer(alert_id):
    want_customer = request.json.get('customer', None)
    query = qb.from_params(MultiDict([]), customers=g.customers)
    query_data = [
        c for c in Customer.find_all(query) if Scope.admin in g.scopes
        or Scope.admin_customers in g.scopes or c.customer in g.customers
    ]
    if query_data:
        list_customers = [q.serialize for q in query_data]
    else:
        raise ApiError('not found any customer ', 404)
    #LOG.info(list_customers)
    found = False
    for c in list_customers:
        if want_customer == c['customer']:
            found = True

    if found == False:
        raise ApiError('not found customer ', 404)

    alert = Alert.find_by_id(alert_id, g.get('customers', None))
    if not alert:
        raise ApiError('not found alert', 404)
    try:
        alert = alert.from_customer(want_customer)
    except RejectException as e:
        write_audit_trail.send(current_app._get_current_object(),
                               event='alert-customer-change-rejected',
                               message=alert.text,
                               user=g.login,
                               customers=g.customers,
                               scopes=g.scopes,
                               resource_id=alert.id,
                               type='alert',
                               request=request)
        raise ApiError(str(e), 400)
    except Exception as e:
        raise ApiError(str(e), 500)

    write_audit_trail.send(current_app._get_current_object(),
                           event='alert-customer-changed',
                           message='change customer to' + want_customer,
                           user=g.login,
                           customers=g.customers,
                           scopes=g.scopes,
                           resource_id=alert.id,
                           type='alert',
                           request=request)
    if alert:
        return jsonify(status='ok')
    else:
        raise ApiError('failed to set customer', 500)
Ejemplo n.º 29
0
def untag_alert(alert_id):
    if not request.json.get('tags', None):
        raise ApiError("must supply 'tags' as json list")

    customer = g.get('customer', None)
    alert = Alert.find_by_id(alert_id, customer)

    if not alert:
        raise ApiError("not found", 404)

    if alert.untag(tags=request.json['tags']):
        return jsonify(status="ok")
    else:
        raise ApiError("failed to untag alert", 500)
Ejemplo n.º 30
0
def update_attributes(alert_id):
    if not request.json.get('attributes', None):
        raise ApiError("must supply 'attributes' as json data", 400)

    customer = g.get('customer', None)
    alert = Alert.find_by_id(alert_id, customer)

    if not alert:
        raise ApiError("not found", 404)

    if alert.update_attributes(request.json['attributes']):
        return jsonify(status="ok")
    else:
        raise ApiError("failed to update attributes", 500)
Ejemplo n.º 31
0
def tag_alert(alert_id):
    if not request.json.get('tags', None):
        raise ApiError("must supply 'tags' as json list")

    customers = g.get('customers', None)
    alert = Alert.find_by_id(alert_id, customers)

    if not alert:
        raise ApiError('not found', 404)

    if alert.tag(tags=request.json['tags']):
        return jsonify(status='ok')
    else:
        raise ApiError('failed to tag alert', 500)
Ejemplo n.º 32
0
def get_notes(alert_id):
    customers = g.get('customers', None)
    alert = Alert.find_by_id(alert_id, customers)

    if not alert:
        raise ApiError('not found', 404)

    notes = alert.get_alert_notes()

    if notes:
        return jsonify(status='ok',
                       notes=[note.serialize for note in notes],
                       total=len(notes))
    else:
        return jsonify(status='ok', message='not found', notes=[], total=0)
Ejemplo n.º 33
0
    def incoming(self, path, query_string, payload):

        if 'callback_query' in payload:
            author = payload['callback_query']['from']
            user = '******'.format(author.get('first_name'),
                                  author.get('last_name'))
            command, alert_id = payload['callback_query']['data'].split(' ', 1)

            customers = g.get('customers', None)
            alert = Alert.find_by_id(alert_id, customers=customers)
            action = command.lstrip('/')
            if not alert and action != 'blackout':
                return jsonify(status='error',
                               message='alert not found for Telegram message')

            if action in ['open', 'ack', 'close']:
                alert.from_action(action, text='status change via Telegram')
            elif action in ['watch', 'unwatch']:
                alert.untag(tags=['{}:{}'.format(action, user)])
            elif action == 'blackout':
                if alert:
                    # new style paremeters: only alert_id
                    environment = alert.environment
                    resource = alert.resource
                    event = alert.event

                blackout = Blackout(environment,
                                    resource=resource,
                                    event=event)
                blackout.create()

            send_message_reply(alert, action, user, payload)

            text = 'alert updated via telegram webhook'
            write_audit_trail.send(current_app._get_current_object(),
                                   event='webhook-updated',
                                   message=text,
                                   user=g.login,
                                   customers=g.customers,
                                   scopes=g.scopes,
                                   resource_id=alert.id,
                                   type='alert',
                                   request=request)

            return jsonify(status='ok')
        else:
            return jsonify(status='ok',
                           message='no callback_query in Telegram message')
Ejemplo n.º 34
0
def slack():
    alert_id, user, action = parse_slack(request.form)

    alert = Alert.find_by_id(alert_id)
    if not alert:
        jsonify(status="error", message="alert not found for #slack message")

    if action in ['open', 'ack', 'close']:
        alert.set_status(status=action, text="status change via #slack by {}".format(user))
    elif action in ['watch', 'unwatch']:
        alert.untag(alert.id, ["{}:{}".format(action, user)])
    else:
        raise ApiError('Unsupported #slack action', 400)

    response = build_slack_response(alert, action, user, request.form)
    return jsonify(**response), 201
Ejemplo n.º 35
0
def pagerduty():

    data = request.json

    updated = False
    if data and 'messages' in data:
        for message in data['messages']:
            try:
                incident_key, status, text = parse_pagerduty(message)
            except ValueError as e:
                raise ApiError(str(e), 400)

            if not incident_key:
                raise ApiError('no incident key in PagerDuty data payload',
                               400)

            customers = g.get('customers', None)
            try:
                alert = Alert.find_by_id(id=incident_key, customers=customers)
            except Exception as e:
                raise ApiError(str(e), 500)

            if not alert:
                raise ApiError('not found', 404)

            try:
                updated = alert.set_status(status, text)
            except Exception as e:
                raise ApiError(str(e), 500)

            text = 'alert updated via pagerduty webhook'
            write_audit_trail.send(current_app._get_current_object(),
                                   event='webhook-updated',
                                   message=text,
                                   user=g.user,
                                   customers=g.customers,
                                   scopes=g.scopes,
                                   resource_id=alert.id,
                                   type='alert',
                                   request=request)
    else:
        raise ApiError('no messages in PagerDuty data payload', 400)

    if updated:
        return jsonify(status='ok'), 200
    else:
        raise ApiError('update PagerDuty incident status failed', 500)
Ejemplo n.º 36
0
def slack():
    alert_id, user, action = parse_slack(request.form)

    customers = g.get('customers', None)
    alert = Alert.find_by_id(alert_id, customers=customers)
    if not alert:
        jsonify(status="error", message="alert not found for #slack message")

    if action in ['open', 'ack', 'close']:
        alert.set_status(status=action, text="status change via #slack by {}".format(user))
    elif action in ['watch', 'unwatch']:
        alert.untag(alert.id, ["{}:{}".format(action, user)])
    else:
        raise ApiError('Unsupported #slack action', 400)

    response = build_slack_response(alert, action, user, request.form)
    return jsonify(**response), 201
Ejemplo n.º 37
0
    def incoming(self, query_string, payload):

        alert_id, user, action = parse_slack(payload)

        customers = g.get('customers', None)
        alert = Alert.find_by_id(alert_id, customers=customers)
        if not alert:
            jsonify(status='error', message='alert not found for #slack message')

        if action in ['open', 'ack', 'close']:
            alert.set_status(status=action, text='status change via #slack by {}'.format(user))
        elif action in ['watch', 'unwatch']:
            alert.untag(tags=['{}:{}'.format(action, user)])
        else:
            raise ApiError('Unsupported #slack action', 400)

        text = 'alert updated via slack webhook'
        write_audit_trail.send(current_app._get_current_object(), event='webhook-updated', message=text,
                               user=g.login, customers=g.customers, scopes=g.scopes, resource_id=alert.id,
                               type='alert', request=request)

        response = build_slack_response(alert, action, user, payload)
        return jsonify(**response), 201
Ejemplo n.º 38
0
def set_status(alert_id):
    status = request.json.get('status', None)
    text = request.json.get('text', '')

    if not status:
        raise ApiError("must supply 'status' as json data")

    customer = g.get('customer', None)
    alert = Alert.find_by_id(alert_id, customer)

    if not alert:
        raise ApiError("not found", 404)

    try:
        alert, status, text = process_status(alert, status, text)
    except RejectException as e:
        raise ApiError(str(e), 403)
    except Exception as e:
        raise ApiError(str(e), 500)

    if alert.set_status(status, text):
        return jsonify(status="ok")
    else:
        raise ApiError("failed to set alert status", 500)