Example #1
0
def get_user_keys(user):

    query = {"user": user}
    if g.get('role', None) != 'admin':
        query['customer'] = g.get('customer')

    try:
        keys = db.get_keys(query)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    if len(keys):
        return jsonify(
            status="ok",
            total=len(keys),
            keys=keys,
            time=datetime.datetime.utcnow()
        )
    else:
        return jsonify(
            status="ok",
            message="not found",
            total=0,
            keys=[],
            time=datetime.datetime.utcnow()
        )
Example #2
0
def get_services(tenant):

    tenant = generateDBName(tenant)

    try:
        query, _, _, _, limit, _ = parse_fields(request)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 400

    try:
        services = db.get_services(tenant, query=query, limit=limit)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    if services:
        return jsonify(
            status="ok",
            total=len(services),
            services=services
        )
    else:
        return jsonify(
            status="ok",
            message="not found",
            total=0,
            services=[],
        )
Example #3
0
def get_heartbeats():

    try:
        heartbeats = db.get_heartbeats()
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    hb_list = list()
    for hb in heartbeats:
        body = hb.get_body()
        if g.get('role', None) != 'admin' and not body['customer'] == g.get('customer', None):
            continue
        body['href'] = absolute_url('/heartbeat/' + hb.id)
        hb_list.append(body)

    if hb_list:
        return jsonify(
            status="ok",
            total=len(heartbeats),
            heartbeats=hb_list,
            time=datetime.datetime.utcnow()
        )
    else:
        return jsonify(
            status="ok",
            message="not found",
            total=0,
            heartbeats=hb_list,
            time=datetime.datetime.utcnow()
        )
Example #4
0
def set_status(id):

    # FIXME - should only allow role=user to set status for alerts for that customer
    # Above comment is from original code, can ignore it for now


    status_started = status_timer.start_timer()

    tenant = getTenantFromHeader(request)

    if len(tenant) == 0:
        return jsonify(status="error", message="bad request"), 400

    data = request.json

    tenant = generateDBName(tenant)

    if data and 'status' in data:
        try:
            alert = db.set_status(tenant, id=id, status=data['status'], text=data.get('text', ''))
        except Exception as e:
            return jsonify(status="error", message=str(e)), 500
    else:
        status_timer.stop_timer(status_started)
        return jsonify(status="error", message="must supply 'status' as parameter"), 400

    if alert:
        status_timer.stop_timer(status_started)
        return jsonify(status="ok")
    else:
        status_timer.stop_timer(status_started)
        return jsonify(status="error", message="not found"), 404
Example #5
0
def get_top10(tenant):

    tenant = generateDBName(tenant)

    try:
        query, _, group, _, _, _ = parse_fields(request)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 400

    try:
        top10 = db.get_topn(tenant, query=query, group=group, limit=10)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    for item in top10:
        for resource in item['resources']:
            resource['href'] = "%s/%s" % (request.base_url.replace('alerts/top10', 'alert'), resource['id'])

    if top10:
        return jsonify(
            status="ok",
            total=len(top10),
            top10=top10
        )
    else:
        return jsonify(
            status="ok",
            message="not found",
            total=0,
            top10=[],
        )
Example #6
0
def get_history():

    try:
        query, _, _, _, limit, query_time = parse_fields(request)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 400

    try:
        history = db.get_history(query=query, limit=limit)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    for alert in history:
        alert['href'] = absolute_url('/alert/' + alert['id'])

    if len(history) > 0:
        return jsonify(
            status="ok",
            history=history,
            lastTime=history[-1]['updateTime']
        )
    else:
        return jsonify(
            status="ok",
            message="not found",
            history=[],
            lastTIme=query_time
        )
Example #7
0
def get_keys():

    if g.get('role', None) == 'admin':
        try:
            keys = db.get_keys()
        except Exception as e:
            return jsonify(status="error", message=str(e)), 500
    else:
        user = g.get('user')
        try:
            keys = db.get_user_keys(user)
        except Exception as e:
            return jsonify(status="error", message=str(e)), 500

    if keys:
        return jsonify(
            status="ok",
            total=len(keys),
            keys=keys,
            time=datetime.datetime.utcnow()
        )
    else:
        return jsonify(
            status="ok",
            message="not found",
            total=0,
            keys=[],
            time=datetime.datetime.utcnow()
        )
Example #8
0
def get_users():

    try:
        users = db.get_users()
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    if len(users):
        return jsonify(
            status="ok",
            total=len(users),
            users=users,
            domains=app.config['ALLOWED_EMAIL_DOMAINS'],
            orgs=app.config['ALLOWED_GITHUB_ORGS'],
            groups=app.config['ALLOWED_GITLAB_GROUPS'],
            time=datetime.datetime.utcnow()
        )
    else:
        return jsonify(
            status="ok",
            message="not found",
            total=0,
            users=[],
            domains=app.config['ALLOWED_EMAIL_DOMAINS'],
            orgs=app.config['ALLOWED_GITHUB_ORGS'],
            time=datetime.datetime.utcnow()
        )
Example #9
0
def get_user_keys(user):

    query = {"user": user}
    if g.get('role', None) != 'admin':
        query['customer'] = g.get('customer')

    try:
        keys = db.get_keys(query)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    if len(keys):
        return jsonify(
            status="ok",
            total=len(keys),
            keys=keys,
            time=datetime.datetime.utcnow()
        )
    else:
        return jsonify(
            status="ok",
            message="not found",
            total=0,
            keys=[],
            time=datetime.datetime.utcnow()
        )
Example #10
0
def get_history():

    try:
        query, _, _, _, _, limit, query_time = parse_fields(request)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 400

    try:
        history = db.get_history(query=query, limit=limit)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    for alert in history:
        alert['href'] = absolute_url('/alert/' + alert['id'])

    if len(history) > 0:
        return jsonify(
            status="ok",
            history=history,
            lastTime=history[-1]['updateTime']
        )
    else:
        return jsonify(
            status="ok",
            message="not found",
            history=[],
            lastTIme=query_time
        )
Example #11
0
def newrelic():

    hook_started = webhook_timer.start_timer()
    try:
        incomingAlert = parse_newrelic(request.json)
    except ValueError as e:
        webhook_timer.stop_timer(hook_started)
        return jsonify(status="error", message=str(e)), 400

    if g.get("customer", None):
        incomingAlert.customer = g.get("customer")

    try:
        alert = process_alert(incomingAlert)
    except RejectException as e:
        webhook_timer.stop_timer(hook_started)
        return jsonify(status="error", message=str(e)), 403
    except Exception as e:
        webhook_timer.stop_timer(hook_started)
        return jsonify(status="error", message=str(e)), 500

    webhook_timer.stop_timer(hook_started)

    if alert:
        body = alert.get_body()
        body["href"] = absolute_url("/alert/" + alert.id)
        return jsonify(status="ok", id=alert.id, alert=body), 201, {"Location": body["href"]}
    else:
        return jsonify(status="error", message="insert or update of New Relic alert failed"), 500
Example #12
0
def create_key():

    if g.get('role', None) == 'admin':
        try:
            user = request.json.get('user', g.user)
            customer = request.json.get('customer', None)
        except AttributeError:
            return jsonify(status="error", message="Must supply 'user' as parameter"), 400
    else:
        try:
            user = g.user
            customer = g.get('customer', None)
        except AttributeError:
            return jsonify(status="error", message="Must supply API Key or Bearer Token when creating new API key"), 400

    type = request.json.get("type", "read-only")
    if type not in ['read-only', 'read-write']:
        return jsonify(status="error", message="API key 'type' must be 'read-only' or 'read-write'"), 400

    text = request.json.get("text", "API Key for %s" % user)
    try:
        key = db.create_key(user, type, customer, text)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    return jsonify(status="ok", key=key), 201, {'Location': absolute_url('/key/' + key)}
Example #13
0
def cloudwatch():

    hook_started = webhook_timer.start_timer()
    try:
        incomingAlert = parse_notification(request.data)
    except ValueError as e:
        webhook_timer.stop_timer(hook_started)
        return jsonify(status="error", message=str(e)), 400

    try:
        alert = process_alert(incomingAlert)
    except RejectException as e:
        webhook_timer.stop_timer(hook_started)
        return jsonify(status="error", message=str(e)), 403
    except Exception as e:
        webhook_timer.stop_timer(hook_started)
        return jsonify(status="error", message=str(e)), 500

    webhook_timer.stop_timer(hook_started)

    if alert:
        body = alert.get_body()
        body["href"] = "%s/%s" % (request.base_url, alert.id)
        return jsonify(status="ok", id=alert.id, alert=body), 201, {"Location": "%s/%s" % (request.base_url, alert.id)}
    else:
        return jsonify(status="error", message="insert or update of cloudwatch alarm failed"), 500
Example #14
0
def get_heartbeats():

    try:
        heartbeats = db.get_heartbeats()
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    hb_list = list()
    for hb in heartbeats:
        body = hb.get_body()
        body['href'] = "%s/%s" % (request.base_url.replace(
            'heartbeats', 'heartbeat'), hb.id)
        hb_list.append(body)

    if hb_list:
        return jsonify(status="ok",
                       total=len(heartbeats),
                       heartbeats=hb_list,
                       time=datetime.datetime.utcnow())
    else:
        return jsonify(status="ok",
                       message="not found",
                       total=0,
                       heartbeats=hb_list,
                       time=datetime.datetime.utcnow())
Example #15
0
def set_status(id):

    # FIXME - should only allow role=user to set status for alerts for that customer

    status_started = status_timer.start_timer()
    data = request.json

    if data and 'status' in data:
        try:
            alert = db.set_status(id=id,
                                  status=data['status'],
                                  text=data.get('text', ''))
        except Exception as e:
            return jsonify(status="error", message=str(e)), 500
    else:
        status_timer.stop_timer(status_started)
        return jsonify(status="error",
                       message="must supply 'status' as parameter"), 400

    if alert:
        status_timer.stop_timer(status_started)
        return jsonify(status="ok")
    else:
        status_timer.stop_timer(status_started)
        return jsonify(status="error", message="not found"), 404
Example #16
0
File: auth.py Project: iselu/alerta
def github():
    access_token_url = 'https://github.com/login/oauth/access_token'
    users_api_url = 'https://api.github.com/user'

    params = {
        'client_id': request.json['clientId'],
        'redirect_uri': request.json['redirectUri'],
        'client_secret': app.config['OAUTH2_CLIENT_SECRET'],
        'code': request.json['code']
    }

    headers = {'Accept': 'application/json'}
    r = requests.get(access_token_url, headers=headers, params=params)
    access_token = r.json()

    r = requests.get(users_api_url, params=access_token)
    profile = r.json()

    r = requests.get(profile['organizations_url'], params=access_token)
    organizations = [o['login'] for o in r.json()]
    login = profile['login']

    try:
        customer = customer_match(login, organizations)
    except NoCustomerMatch:
        return jsonify(status="error", message="No customer lookup defined for user %s" % login), 403

    if app.config['AUTH_REQUIRED'] and not ('*' in app.config['ALLOWED_GITHUB_ORGS']
            or set(app.config['ALLOWED_GITHUB_ORGS']).intersection(set(organizations))
            or db.is_user_valid(login=login)):
        return jsonify(status="error", message="User %s is not authorized" % login), 403

    token = create_token(profile['id'], profile.get('name', None) or '@'+login, login, provider='github',
                         customer=customer, role=role(login))
    return jsonify(token=token)
Example #17
0
def signup():

    if request.json and "name" in request.json:
        name = request.json["name"]
        email = request.json["email"]
        password = request.json["password"]
        provider = request.json.get("provider", "basic")
        text = request.json.get("text", "")
        try:
            user_id = db.save_user(str(uuid4()), name, email, password, provider, text)
        except Exception as e:
            return jsonify(status="error", message=str(e)), 500
    else:
        return jsonify(status="error", message="must supply user 'name', 'email' and 'password' as parameters"), 400

    if user_id:
        user = db.get_user(user_id)
    else:
        user = db.get_users(query={"login": email})[0]

    if app.config["CUSTOMER_VIEWS"]:
        try:
            customer = customer_match(email, groups=[email.split("@")[1]])
        except NoCustomerMatch:
            return jsonify(status="error", message="No customer lookup defined for user %s" % email), 403
    else:
        customer = None

    token = create_token(user["id"], user["name"], email, provider="basic", customer=customer, role=role(email))
    return jsonify(token=token)
Example #18
0
def prometheus():

    if request.json:
        hook_started = webhook_timer.start_timer()
        for notification in request.json:
            try:
                incomingAlert = parse_prometheus(notification)
            except ValueError as e:
                webhook_timer.stop_timer(hook_started)
                return jsonify(status="error", message=str(e)), 400

            try:
                process_alert(incomingAlert)
            except RejectException as e:
                webhook_timer.stop_timer(hook_started)
                return jsonify(status="error", message=str(e)), 403
            except Exception as e:
                webhook_timer.stop_timer(hook_started)
                return jsonify(status="error", message=str(e)), 500

        webhook_timer.stop_timer(hook_started)
    else:
        return jsonify(status="error", message="no alerts in Prometheus notification payload"), 400

    return jsonify(status="ok"), 200
Example #19
0
def get_heartbeats():

    customer = g.get('customer', None)
    if customer:
        query = {'customer': customer}
    else:
        query = {}

    try:
        heartbeats = db.get_heartbeats(query)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    hb_list = list()
    for hb in heartbeats:
        body = hb.get_body()
        body['href'] = absolute_url('/heartbeat/' + hb.id)
        hb_list.append(body)

    if hb_list:
        return jsonify(
            status="ok",
            total=len(heartbeats),
            heartbeats=hb_list,
            time=datetime.datetime.utcnow()
        )
    else:
        return jsonify(
            status="ok",
            message="not found",
            total=0,
            heartbeats=hb_list,
            time=datetime.datetime.utcnow()
        )
Example #20
0
def pingdom():

    hook_started = webhook_timer.start_timer()
    try:
        incomingAlert = parse_pingdom(request.args.get('message'))
    except ValueError as e:
        webhook_timer.stop_timer(hook_started)
        return jsonify(status="error", message=str(e)), 400

    try:
        alert = process_alert(incomingAlert)
    except RejectException as e:
        webhook_timer.stop_timer(hook_started)
        return jsonify(status="error", message=str(e)), 403
    except Exception as e:
        webhook_timer.stop_timer(hook_started)
        return jsonify(status="error", message=str(e)), 500

    webhook_timer.stop_timer(hook_started)

    if alert:
        body = alert.get_body()
        body['href'] = "%s/%s" % (request.base_url, alert.id)
        return jsonify(status="ok", id=alert.id, alert=body), 201, {'Location': '%s/%s' % (request.base_url, alert.id)}
    else:
        return jsonify(status="error", message="insert or update of pingdom check failed"), 500
Example #21
0
def get_history(tenant):

    tenant = generateDBName(tenant)

    try:
        query, _, _, _, limit, query_time = parse_fields(request)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 400

    try:
        history = db.get_history(tenant, query=query, limit=limit)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    for alert in history:
        alert['href'] = "%s/%s" % (request.base_url.replace('alerts/history', 'alert'), alert['id'])

    if len(history) > 0:
        return jsonify(
            status="ok",
            history=history,
            lastTime=history[-1]['updateTime']
        )
    else:
        return jsonify(
            status="ok",
            message="not found",
            history=[],
            lastTIme=query_time
        )
Example #22
0
def get_users():

    try:
        users = db.get_users()
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    if len(users):
        return jsonify(
            status="ok",
            total=len(users),
            users=users,
            domains=app.config['ALLOWED_EMAIL_DOMAINS'],
            orgs=app.config['ALLOWED_GITHUB_ORGS'],
            groups=app.config['ALLOWED_GITLAB_GROUPS'],
            time=datetime.datetime.utcnow()
        )
    else:
        return jsonify(
            status="ok",
            message="not found",
            total=0,
            users=[],
            domains=app.config['ALLOWED_EMAIL_DOMAINS'],
            orgs=app.config['ALLOWED_GITHUB_ORGS'],
            time=datetime.datetime.utcnow()
        )
Example #23
0
def tag_alert(tenant, id):

    # FIXME - should only allow role=user to set status for alerts for that customer
    # Above comment is from original code, can ignore for now

    tag_started = tag_timer.start_timer()

    data = request.json

    tenant = generateDBName(tenant)

    if data and 'tags' in data:
        try:
            response = db.tag_alert(id, tenant, data['tags'])
        except Exception as e:
            return jsonify(status="error", message=str(e)), 500
    else:
        tag_timer.stop_timer(tag_started)
        return jsonify(status="error", message="must supply 'tags' as list parameter"), 400

    tag_timer.stop_timer(tag_started)
    if response:
        return jsonify(status="ok")
    else:
        return jsonify(status="error", message="not found"), 404
Example #24
0
def pingdom():

    hook_started = webhook_timer.start_timer()
    try:
        incomingAlert = parse_pingdom(request.args.get('message'))
    except ValueError as e:
        webhook_timer.stop_timer(hook_started)
        return jsonify(status="error", message=str(e)), 400

    try:
        alert = process_alert(incomingAlert)
    except RejectException as e:
        webhook_timer.stop_timer(hook_started)
        return jsonify(status="error", message=str(e)), 403
    except Exception as e:
        webhook_timer.stop_timer(hook_started)
        return jsonify(status="error", message=str(e)), 500

    webhook_timer.stop_timer(hook_started)

    if alert:
        body = alert.get_body()
        body['href'] = "%s/%s" % (request.base_url, alert.id)
        return jsonify(status="ok", id=alert.id, alert=body), 201, {
            'Location': '%s/%s' % (request.base_url, alert.id)
        }
    else:
        return jsonify(status="error",
                       message="insert or update of pingdom check failed"), 500
Example #25
0
def get_environments(tenant):

    tenant = generateDBName(tenant)

    try:
        query, _, _, _, limit, _ = parse_fields(request)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 400

    try:
        environments = db.get_environments(tenant, query=query, limit=limit)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    if environments:
        return jsonify(
            status="ok",
            total=len(environments),
            environments=environments
        )
    else:
        return jsonify(
            status="ok",
            message="not found",
            total=0,
            environments=[],
        )
Example #26
0
def create_blackout(tenant):

    data = request.json

    tenant = generateDBName(tenant)

    if request.json and 'environment' in request.json:
        environment = request.json['environment']
    else:
        return jsonify(status="error", message="must supply 'environment' as parameter"), 400

    resource = request.json.get("resource", None)
    service = request.json.get("service", None)
    event = request.json.get("event", None)
    group = request.json.get("group", None)
    tags = request.json.get("tags", None)
    start_time = request.json.get("startTime", None)
    end_time = request.json.get("endTime", None)
    duration = request.json.get("duration", None)

    if start_time:
        start_time = datetime.datetime.strptime(start_time, '%Y-%m-%dT%H:%M:%S.%fZ')
    if end_time:
        end_time = datetime.datetime.strptime(end_time, '%Y-%m-%dT%H:%M:%S.%fZ')

    try:
        blackout = db.create_blackout(tenant,environment, resource, service, event, group, tags, start_time, end_time, duration)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    return jsonify(status="ok", blackout=blackout), 201, {'Location': '%s/%s' % (request.base_url, blackout)}
Example #27
0
def cloudwatch():

    hook_started = webhook_timer.start_timer()
    try:
        incomingAlert = parse_notification(request.data)
    except ValueError as e:
        webhook_timer.stop_timer(hook_started)
        return jsonify(status="error", message=str(e)), 400

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

    try:
        alert = process_alert(incomingAlert)
    except RejectException as e:
        webhook_timer.stop_timer(hook_started)
        return jsonify(status="error", message=str(e)), 403
    except Exception as e:
        webhook_timer.stop_timer(hook_started)
        return jsonify(status="error", message=str(e)), 500

    webhook_timer.stop_timer(hook_started)

    if alert:
        body = alert.get_body()
        body['href'] = absolute_url('/alert/' + alert.id)
        return jsonify(status="ok", id=alert.id, alert=body), 201, {'Location': body['href']}
    else:
        return jsonify(status="error", message="insert or update of cloudwatch alarm failed"), 500
Example #28
0
def get_heartbeats(tenant):

    tenant = generateDBName(tenant)

    try:
        heartbeats = db.get_heartbeats(tenant)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    hb_list = list()
    for hb in heartbeats:
        body = hb.get_body()
        if g.get('role', None) != 'admin' and not body['customer'] == g.get('customer', None):
            continue
        body['href'] = "%s/%s" % (request.base_url.replace('heartbeats', 'heartbeat'), hb.id)
        hb_list.append(body)

    if hb_list:
        return jsonify(
            status="ok",
            total=len(heartbeats),
            heartbeats=hb_list,
            time=datetime.datetime.utcnow()
        )
    else:
        return jsonify(
            status="ok",
            message="not found",
            total=0,
            heartbeats=hb_list,
            time=datetime.datetime.utcnow()
        )
Example #29
0
def get_top10():

    try:
        query, _, group, _, _ = parse_fields(request)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 400

    try:
        top10 = db.get_topn(query=query, group=group, limit=10)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    for item in top10:
        for resource in item['resources']:
            resource['href'] = "%s/%s" % (request.base_url.replace('alerts/top10', 'alert'), resource['id'])

    if top10:
        return jsonify(
            status="ok",
            total=len(top10),
            top10=top10
        )
    else:
        return jsonify(
            status="ok",
            message="not found",
            total=0,
            top10=[],
        )
Example #30
0
def get_keys():

    if g.get('role', None) == 'admin':
        try:
            keys = db.get_keys()
        except Exception as e:
            return jsonify(status="error", message=str(e)), 500
    else:
        user = g.get('user')
        try:
            keys = db.get_user_keys(user)
        except Exception as e:
            return jsonify(status="error", message=str(e)), 500

    if keys:
        return jsonify(status="ok",
                       total=len(keys),
                       keys=keys,
                       time=datetime.datetime.utcnow())
    else:
        return jsonify(status="ok",
                       message="not found",
                       total=0,
                       keys=[],
                       time=datetime.datetime.utcnow())
Example #31
0
def newrelic():

    hook_started = webhook_timer.start_timer()
    try:
        incomingAlert = parse_newrelic(request.json)
    except ValueError as e:
        webhook_timer.stop_timer(hook_started)
        return jsonify(status="error", message=str(e)), 400

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

    try:
        alert = process_alert(incomingAlert)
    except RejectException as e:
        webhook_timer.stop_timer(hook_started)
        return jsonify(status="error", message=str(e)), 403
    except Exception as e:
        webhook_timer.stop_timer(hook_started)
        return jsonify(status="error", message=str(e)), 500

    webhook_timer.stop_timer(hook_started)

    if alert:
        body = alert.get_body()
        body['href'] = absolute_url('/alert/' + alert.id)
        return jsonify(status="ok", id=alert.id, alert=body), 201, {
            'Location': body['href']
        }
    else:
        return jsonify(
            status="error",
            message="insert or update of New Relic alert failed"), 500
Example #32
0
def create_user():

    if request.json and 'name' in request.json:
        name = request.json["name"]
        login = request.json["login"]
        password = request.json.get("password", None)
        provider = request.json["provider"]
        text = request.json.get("text", "")
        try:
            user_id = db.save_user(str(uuid4()), name, login, password,
                                   provider, text)
        except Exception as e:
            return jsonify(status="error", message=str(e)), 500
    else:
        return jsonify(
            status="error",
            message=
            "must supply user 'name', 'login' and 'provider' as parameters"
        ), 400

    if user_id:
        return jsonify(status="ok", user=user_id), 201, {
            'Location': absolute_url('/user/' + user_id)
        }
    else:
        return jsonify(status="error",
                       message="User with that login already exists"), 409
Example #33
0
def update_user(user):

    if not request.json:
        return jsonify(status="ok",
                       user=user,
                       message="Nothing to update, request was empty")

    name = request.json.get('name', None)
    login = request.json.get('login', None)
    password = request.json.get('password', None)
    provider = request.json.get('provider', None)
    text = request.json.get('text', None)
    email_verified = request.json.get('email_verified', None)

    try:
        user = db.update_user(user,
                              name=name,
                              login=login,
                              password=password,
                              provider=provider,
                              text=text,
                              email_verified=email_verified)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    if user:
        return jsonify(status="ok", user=user)
    else:
        return jsonify(status="error", message="not found"), 404
Example #34
0
def create_blackout():

    if request.json and 'environment' in request.json:
        environment = request.json['environment']
    else:
        return jsonify(status="error",
                       message="must supply 'environment' as parameter"), 400

    resource = request.json.get("resource", None)
    service = request.json.get("service", None)
    event = request.json.get("event", None)
    group = request.json.get("group", None)
    tags = request.json.get("tags", None)
    customer = request.json.get("customer", None)
    start_time = request.json.get("startTime", None)
    end_time = request.json.get("endTime", None)
    duration = request.json.get("duration", None)

    if start_time:
        start_time = datetime.datetime.strptime(start_time,
                                                '%Y-%m-%dT%H:%M:%S.%fZ')
    if end_time:
        end_time = datetime.datetime.strptime(end_time,
                                              '%Y-%m-%dT%H:%M:%S.%fZ')

    try:
        blackout = db.create_blackout(environment, resource, service, event,
                                      group, tags, customer, start_time,
                                      end_time, duration)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    return jsonify(status="ok", blackout=blackout), 201, {
        'Location': absolute_url('/blackout/' + blackout)
    }
Example #35
0
def get_user_keys(user):

    if not db.is_user_valid(user):
        return jsonify(status="error", message="not found"), 404

    try:
        keys = db.get_keys({"user": user})
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    if len(keys):
        return jsonify(
            status="ok",
            total=len(keys),
            keys=keys,
            time=datetime.datetime.utcnow()
        )
    else:
        return jsonify(
            status="ok",
            message="not found",
            total=0,
            keys=[],
            time=datetime.datetime.utcnow()
        )
Example #36
0
def get_counts():

    try:
        query, _, _, _, _, _, _ = parse_fields(request)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 400

    try:
        severity_count = db.get_counts(query=query,
                                       fields={"severity": 1},
                                       group="severity")
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    try:
        status_count = db.get_counts(query=query,
                                     fields={"status": 1},
                                     group="status")
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    if sum(severity_count.values()):
        return jsonify(status="ok",
                       total=sum(severity_count.values()),
                       severityCounts=severity_count,
                       statusCounts=status_count)
    else:
        return jsonify(status="ok",
                       message="not found",
                       total=0,
                       severityCounts=severity_count,
                       statusCounts=status_count)
Example #37
0
def get_top10():

    try:
        query, _, _, group, _, _, _ = parse_fields(request)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 400

    try:
        top10 = db.get_topn(query=query, group=group, limit=10)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    for item in top10:
        for resource in item['resources']:
            resource['href'] = absolute_url('/alert/' + resource['id'])

    if top10:
        return jsonify(status="ok", total=len(top10), top10=top10)
    else:
        return jsonify(
            status="ok",
            message="not found",
            total=0,
            top10=[],
        )
Example #38
0
def create_key():

    if g.get('role', None) == 'admin':
        try:
            user = request.json.get('user', g.user)
            customer = request.json.get('customer', None)
        except AttributeError:
            return jsonify(status="error",
                           message="Must supply 'user' as parameter"), 400
    else:
        try:
            user = g.user
            customer = g.get('customer', None)
        except AttributeError:
            return jsonify(
                status="error",
                message=
                "Must supply API Key or Bearer Token when creating new API key"
            ), 400

    type = request.json.get("type", "read-only")
    if type not in ['read-only', 'read-write']:
        return jsonify(
            status="error",
            message="API key 'type' must be 'read-only' or 'read-write'"), 400

    text = request.json.get("text", "API Key for %s" % user)
    try:
        key = db.create_key(user, type, customer, text)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    return jsonify(status="ok", key=key), 201, {
        'Location': absolute_url('/key/' + key)
    }
Example #39
0
def twitter():
    request_token_url = 'https://api.twitter.com/oauth/request_token'
    access_token_url = 'https://api.twitter.com/oauth/access_token'

    if request.json.get('oauth_token') and request.json.get('oauth_verifier'):
        auth = OAuth1(app.config['OAUTH2_CLIENT_ID'],
                      client_secret=app.config['OAUTH2_CLIENT_SECRET'],
                      resource_owner_key=request.json.get('oauth_token'),
                      verifier=request.json.get('oauth_verifier'))
        r = requests.post(access_token_url, auth=auth)
        profile = dict(parse_qsl(r.text))

        login = profile['screen_name']
        if app.config['AUTH_REQUIRED'] and not db.is_user_valid(login=login):
            return jsonify(status="error",
                           message="User %s is not authorized" % login), 403

        token = create_token(profile['user_id'],
                             '@' + login,
                             login,
                             provider='twitter')
        return jsonify(token=token)
    else:
        oauth = OAuth1(app.config['OAUTH2_CLIENT_ID'],
                       client_secret=app.config['OAUTH2_CLIENT_SECRET'],
                       callback_uri=app.config.get(
                           'TWITTER_CALLBACK_URL',
                           request.headers.get('Referer', '')))
        r = requests.post(request_token_url, auth=oauth)
        oauth_token = dict(parse_qsl(r.text))
        return jsonify(oauth_token)
Example #40
0
def get_device(deviceid):
    tenant = getTenantFromHeader(request)

    if len(tenant) == 0:
        return jsonify(status="error", message="bad request"), 400

    response = getSitewhereTenantInfo(tenant)


    if response and response.status_code is not 200:
        return jsonify(status=response.reason, message=response.content), response.status_code

    response = response.json()

    try:

        authToken = response['authenticationToken']

        url = "http://scamps.cit.ie:8888/sitewhere/api/devices/" + deviceid

        response = getDeviceInfo(url, authToken)

        print response
        print response.text
        print response.request.headers
        return jsonify(message=response.text), response.status_code
    except KeyError as ke:

        return jsonify(status="401",message="authentication token missing"), 401
Example #41
0
def get_environments():

    try:
        query, _, _, limit, _ = parse_fields(request)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 400

    try:
        environments = db.get_environments(query=query, limit=limit)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    if environments:
        return jsonify(
            status="ok",
            total=len(environments),
            environments=environments
        )
    else:
        return jsonify(
            status="ok",
            message="not found",
            total=0,
            environments=[],
        )
Example #42
0
def get_heartbeats():

    customer = g.get('customer', None)
    if customer:
        query = {'customer': customer}
    else:
        query = {}

    try:
        heartbeats = db.get_heartbeats(query)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    hb_list = list()
    for hb in heartbeats:
        body = hb.get_body()
        body['href'] = absolute_url('/heartbeat/' + hb.id)
        hb_list.append(body)

    if hb_list:
        return jsonify(status="ok",
                       total=len(heartbeats),
                       heartbeats=hb_list,
                       time=datetime.datetime.utcnow())
    else:
        return jsonify(status="ok",
                       message="not found",
                       total=0,
                       heartbeats=hb_list,
                       time=datetime.datetime.utcnow())
Example #43
0
def get_heartbeats():

    try:
        heartbeats = db.get_heartbeats()
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    hb_list = list()
    for hb in heartbeats:
        body = hb.get_body()
        body['href'] = "%s/%s" % (request.base_url.replace('heartbeats', 'heartbeat'), hb.id)
        hb_list.append(body)

    if hb_list:
        return jsonify(
            status="ok",
            total=len(heartbeats),
            heartbeats=hb_list,
            time=datetime.datetime.utcnow()
        )
    else:
        return jsonify(
            status="ok",
            message="not found",
            total=0,
            heartbeats=hb_list,
            time=datetime.datetime.utcnow()
        )
Example #44
0
def get_counts():

    try:
        query, _, _, _, _ = parse_fields(request)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 400

    try:
        severity_count = db.get_counts(query=query, fields={"severity": 1}, group="severity")
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    try:
        status_count = db.get_counts(query=query, fields={"status": 1}, group="status")
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    if sum(severity_count.values()):
        return jsonify(
            status="ok",
            total=sum(severity_count.values()),
            severityCounts=severity_count,
            statusCounts=status_count
        )
    else:
        return jsonify(
            status="ok",
            message="not found",
            total=0,
            severityCounts=severity_count,
            statusCounts=status_count
        )
Example #45
0
def get_heartbeats():

    try:
        heartbeats = db.get_heartbeats()
    except Exception as e:
        return jsonify(status="error", message=str(e)), 500

    hb_list = list()
    for hb in heartbeats:
        body = hb.get_body()
        if g.get('role', None) != 'admin' and not body['customer'] == g.get(
                'customer', None):
            continue
        body['href'] = absolute_url('/heartbeat/' + hb.id)
        hb_list.append(body)

    if hb_list:
        return jsonify(status="ok",
                       total=len(heartbeats),
                       heartbeats=hb_list,
                       time=datetime.datetime.utcnow())
    else:
        return jsonify(status="ok",
                       message="not found",
                       total=0,
                       heartbeats=hb_list,
                       time=datetime.datetime.utcnow())
Example #46
0
def prometheus():

    if request.json and 'alerts' in request.json:
        hook_started = webhook_timer.start_timer()
        status = request.json['status']
        for alert in request.json['alerts']:
            try:
                incomingAlert = parse_prometheus(status, alert)
            except ValueError as e:
                webhook_timer.stop_timer(hook_started)
                return jsonify(status="error", message=str(e)), 400

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

            try:
                process_alert(incomingAlert)
            except RejectException as e:
                webhook_timer.stop_timer(hook_started)
                return jsonify(status="error", message=str(e)), 403
            except Exception as e:
                webhook_timer.stop_timer(hook_started)
                return jsonify(status="error", message=str(e)), 500

        webhook_timer.stop_timer(hook_started)
    else:
        return jsonify(status="error", message="no alerts in Prometheus notification payload"), 400

    return jsonify(status="ok"), 200
Example #47
0
def twitter():
    request_token_url = 'https://api.twitter.com/oauth/request_token'
    access_token_url = 'https://api.twitter.com/oauth/access_token'
    authenticate_url = 'https://api.twitter.com/oauth/authenticate'

    if request.args.get('oauth_token') and request.args.get('oauth_verifier'):
        auth = OAuth1(app.config['OAUTH2_CLIENT_ID'],
                      client_secret=app.config['OAUTH2_CLIENT_SECRET'],
                      resource_owner_key=request.args.get('oauth_token'),
                      verifier=request.args.get('oauth_verifier'))
        r = requests.post(access_token_url, auth=auth)
        profile = dict(parse_qsl(r.text))

        login = profile['screen_name']
        if app.config['AUTH_REQUIRED'] and not db.is_user_valid(login=login):
            return jsonify(status="error", message="User %s is not authorized" % login), 403

        token = create_token(profile['user_id'], '@'+login, login, provider='twitter')
        return jsonify(token=token)
    else:
        oauth = OAuth1(app.config['OAUTH2_CLIENT_ID'],
                       client_secret=app.config['OAUTH2_CLIENT_SECRET'],
                       callback_uri=app.config.get('TWITTER_CALLBACK_URL', request.headers.get('Referer', ''))
        )
        r = requests.post(request_token_url, auth=oauth)
        oauth_token = dict(parse_qsl(r.text))
        qs = urlencode(dict(oauth_token=oauth_token['oauth_token']))
        return redirect(authenticate_url + '?' + qs)
Example #48
0
def pagerduty():

    hook_started = webhook_timer.start_timer()
    data = request.json

    if data and 'messages' in data:
        for message in data['messages']:
            try:
                id, status, text = parse_pagerduty(message)
            except IndexError as e:
                webhook_timer.stop_timer(hook_started)
                return jsonify(status="error", message=str(e)), 400

            try:
                alert = db.set_status(id=id, status=status, text=text)
            except Exception as e:
                webhook_timer.stop_timer(hook_started)
                return jsonify(status="error", message=str(e)), 500
    else:
        webhook_timer.stop_timer(hook_started)
        return jsonify(status="error", message="no messages in PagerDuty data payload"), 400

    webhook_timer.stop_timer(hook_started)

    if alert:
        return jsonify(status="ok"), 200
    else:
        return jsonify(status="error", message="update PagerDuty incident status failed"), 500
Example #49
0
def github():
    access_token_url = 'https://github.com/login/oauth/access_token'
    users_api_url = 'https://api.github.com/user'

    params = {
        'client_id': request.json['clientId'],
        'redirect_uri': request.json['redirectUri'],
        'client_secret': app.config['OAUTH2_CLIENT_SECRET'],
        'code': request.json['code']
    }

    r = requests.get(access_token_url, params=params)
    access_token = dict(parse_qsl(r.text))

    r = requests.get(users_api_url, params=access_token)
    profile = json.loads(r.text)

    r = requests.get(profile['organizations_url'], params=access_token)
    organizations = [o['login'] for o in json.loads(r.text)]

    login = profile['login']
    if app.config['AUTH_REQUIRED'] and not ('*' in app.config['ALLOWED_GITHUB_ORGS']
            or set(app.config['ALLOWED_GITHUB_ORGS']).intersection(set(organizations))
            or db.is_user_valid(login=login)):
        return jsonify(status="error", message="User %s is not authorized" % profile['login']), 403

    token = create_token(profile['id'], profile.get('name', None) or '@'+login, login, provider='github')
    return jsonify(token=token)
Example #50
0
def cloudwatch():

    hook_started = webhook_timer.start_timer()
    try:
        incomingAlert = parse_notification(request.data)
    except ValueError as e:
        webhook_timer.stop_timer(hook_started)
        return jsonify(status="error", message=str(e)), 400

    try:
        alert = process_alert(incomingAlert)
    except RejectException as e:
        webhook_timer.stop_timer(hook_started)
        return jsonify(status="error", message=str(e)), 403
    except Exception as e:
        webhook_timer.stop_timer(hook_started)
        return jsonify(status="error", message=str(e)), 500

    webhook_timer.stop_timer(hook_started)

    if alert:
        body = alert.get_body()
        body['href'] = absolute_url('/alert/' + alert.id)
        return jsonify(status="ok", id=alert.id, alert=body), 201, {
            'Location': body['href']
        }
    else:
        return jsonify(
            status="error",
            message="insert or update of cloudwatch alarm failed"), 500
Example #51
0
def prometheus():

    if request.json and 'alerts' in request.json:
        hook_started = webhook_timer.start_timer()
        status = request.json['status']
        for alert in request.json['alerts']:
            try:
                incomingAlert = parse_prometheus(status, alert)
            except ValueError as e:
                webhook_timer.stop_timer(hook_started)
                return jsonify(status="error", message=str(e)), 400

            try:
                process_alert(incomingAlert)
            except RejectException as e:
                webhook_timer.stop_timer(hook_started)
                return jsonify(status="error", message=str(e)), 403
            except Exception as e:
                webhook_timer.stop_timer(hook_started)
                return jsonify(status="error", message=str(e)), 500

        webhook_timer.stop_timer(hook_started)
    else:
        return jsonify(
            status="error",
            message="no alerts in Prometheus notification payload"), 400

    return jsonify(status="ok"), 200
Example #52
0
def pagerduty():

    hook_started = webhook_timer.start_timer()
    data = request.json

    if data and 'messages' in data:
        for message in data['messages']:
            try:
                id, status, text = parse_pagerduty(message)
            except IndexError as e:
                webhook_timer.stop_timer(hook_started)
                return jsonify(status="error", message=str(e)), 400

            try:
                alert = db.set_status(id=id, status=status, text=text)
            except Exception as e:
                webhook_timer.stop_timer(hook_started)
                return jsonify(status="error", message=str(e)), 500
    else:
        webhook_timer.stop_timer(hook_started)
        return jsonify(status="error",
                       message="no messages in PagerDuty data payload"), 400

    webhook_timer.stop_timer(hook_started)

    if alert:
        return jsonify(status="ok"), 200
    else:
        return jsonify(status="error",
                       message="update PagerDuty incident status failed"), 500
Example #53
0
File: auth.py Project: tdi/alerta
def gitlab():

    if not app.config['GITLAB_URL']:
        return jsonify(
            status="error",
            message="Must define GITLAB_URL setting in server configuration."
        ), 503

    access_token_url = app.config['GITLAB_URL'] + '/oauth/token'
    gitlab_api_url = app.config['GITLAB_URL'] + '/api/v3'

    payload = {
        'client_id': request.json['clientId'],
        'client_secret': app.config['OAUTH2_CLIENT_SECRET'],
        'redirect_uri': request.json['redirectUri'],
        'grant_type': 'authorization_code',
        'code': request.json['code'],
    }

    try:
        r = requests.post(access_token_url, data=payload)
    except Exception:
        return jsonify(status="error",
                       message="Failed to call Gitlab API over HTTPS")
    access_token = r.json()

    r = requests.get(gitlab_api_url + '/user', params=access_token)
    profile = r.json()

    r = requests.get(gitlab_api_url + '/groups', params=access_token)
    groups = [g['path'] for g in r.json()]
    login = profile['username']

    if app.config['AUTH_REQUIRED'] and not (
            '*' in app.config['ALLOWED_GITLAB_GROUPS']
            or set(app.config['ALLOWED_GITLAB_GROUPS']).intersection(
                set(groups))):
        return jsonify(status="error",
                       message="User %s is not authorized" % login), 403

    if app.config['CUSTOMER_VIEWS']:
        try:
            customer = customer_match(login, groups)
        except NoCustomerMatch:
            return jsonify(status="error",
                           message="No customer lookup defined for user %s" %
                           login), 403
    else:
        customer = None

    token = create_token(profile['id'],
                         profile.get('name', None) or '@' + login,
                         login,
                         provider='gitlab',
                         customer=customer,
                         role=role(login))
    return jsonify(token=token)
Example #54
0
def get_services():

    try:
        query, _, _, limit, _ = parse_fields(request)
    except Exception as e:
        return jsonify(status="error", message=str(e)), 400

    try:
        services = db.get_services(query=query, limit=limit)
    except Exception, e:
        return jsonify(status="error", message=str(e)), 500