예제 #1
0
파일: telegram.py 프로젝트: 3IWOH/alerta
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
예제 #2
0
파일: telegram.py 프로젝트: guardian/alerta
    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')
예제 #3
0
파일: blackouts.py 프로젝트: 3IWOH/alerta
def delete_blackout(blackout_id):
    customer = g.get('customer', None)
    blackout = Blackout.find_by_id(blackout_id, customer)

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

    if blackout.delete():
        return jsonify(status="ok")
    else:
        raise ApiError("failed to delete blackout", 500)
예제 #4
0
def delete_blackout(blackout_id):
    customer = g.get('customer', None)
    blackout = Blackout.find_by_id(blackout_id, customer)

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

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

    if blackout.delete():
        return jsonify(status='ok')
    else:
        raise ApiError('failed to delete blackout', 500)
예제 #5
0
def list_blackouts():
    query = qb.from_params(request.args, customers=g.customers)
    blackouts = Blackout.find_all(query)

    if blackouts:
        return jsonify(
            status='ok',
            blackouts=[blackout.serialize for blackout in blackouts],
            total=len(blackouts)
        )
    else:
        return jsonify(
            status='ok',
            message='not found',
            blackouts=[],
            total=0
        )
예제 #6
0
파일: blackouts.py 프로젝트: 3IWOH/alerta
def list_blackouts():
    query = qb.from_params(request.args)
    blackouts = Blackout.find_all(query)

    if blackouts:
        return jsonify(
            status="ok",
            blackouts=[blackout.serialize for blackout in blackouts],
            total=len(blackouts)
        )
    else:
        return jsonify(
            status="ok",
            message="not found",
            blackouts=[],
            total=0
        )
예제 #7
0
파일: blackouts.py 프로젝트: 3IWOH/alerta
def create_blackout():
    try:
        blackout = Blackout.parse(request.json)
    except Exception as e:
        raise ApiError(str(e), 400)

    if g.get('customer', None):
        blackout.customer = g.get('customer')

    try:
        blackout = blackout.create()
    except Exception as e:
        raise ApiError(str(e), 500)

    if blackout:
        return jsonify(status="ok", id=blackout.id, blackout=blackout.serialize), 201, {'Location': absolute_url('/blackout/' + blackout.id)}
    else:
        raise ApiError("insert blackout failed", 500)
예제 #8
0
def create_blackout():
    try:
        blackout = Blackout.parse(request.json)
    except Exception as e:
        raise ApiError(str(e), 400)

    if g.get('customer', None):
        blackout.customer = g.get('customer')

    try:
        blackout = blackout.create()
    except Exception as e:
        raise ApiError(str(e), 500)

    if blackout:
        return jsonify(status="ok",
                       id=blackout.id,
                       blackout=blackout.serialize), 201, {
                           'Location': absolute_url('/blackout/' + blackout.id)
                       }
    else:
        raise ApiError("insert blackout failed", 500)
예제 #9
0
def create_blackout():
    try:
        blackout = Blackout.parse(request.json)
    except Exception as e:
        raise ApiError(str(e), 400)

    blackout.customer = assign_customer(wanted=blackout.customer,
                                        permission='admin:blackouts')

    try:
        blackout = blackout.create()
    except Exception as e:
        raise ApiError(str(e), 500)

    if blackout:
        return jsonify(status="ok",
                       id=blackout.id,
                       blackout=blackout.serialize), 201, {
                           'Location': absolute_url('/blackout/' + blackout.id)
                       }
    else:
        raise ApiError("insert blackout failed", 500)
예제 #10
0
def update_blackout(blackout_id):
    if not request.json:
        raise ApiError('nothing to change', 400)

    blackout = Blackout.find_by_id(blackout_id)

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

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

    if blackout.update(**request.json):
        return jsonify(status='ok')
    else:
        raise ApiError('failed to update blackout', 500)
예제 #11
0
def create_blackout():
    try:
        blackout = Blackout.parse(request.json)
    except Exception as e:
        raise ApiError(str(e), 400)

    if Scope.admin in g.scopes or Scope.admin_blackouts in g.scopes:
        blackout.user = blackout.user or g.user
    else:
        blackout.user = g.user

    blackout.customer = assign_customer(wanted=blackout.customer,
                                        permission=Scope.admin_blackouts)

    try:
        blackout = blackout.create()
    except Exception as e:
        raise ApiError(str(e), 500)

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

    if blackout:
        return jsonify(status='ok',
                       id=blackout.id,
                       blackout=blackout.serialize), 201, {
                           'Location': absolute_url('/blackout/' + blackout.id)
                       }
    else:
        raise ApiError('insert blackout 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.from_action(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