Пример #1
0
def update_frontend_rating_config() -> Response:
    """Edit a configuration, from the frontend."""
    received = load_from_form(request.form)
    try:
        schema.validate_request_content(received)
    except schema.ValidationError as exc:
        abort(make_response(jsonify(message=exc.message), 400))

    try:
        api = client.CustomObjectsApi(get_client())
        cr = api.get_namespaced_custom_object(
            **{
                'group': 'rating.alterway.fr',
                'version': 'v1',
                'plural': 'ratingrules',
                'namespace': envvar('RATING_NAMESPACE'),
                'name': received['name']
            })

        cr['spec'] = {
            'metrics': received.get('metrics', cr['spec']['metrics']),
            'rules': received.get('rules', cr['spec']['rules'])
        }
        api.patch_namespaced_custom_object(
            **{
                'group': 'rating.alterway.fr',
                'version': 'v1',
                'plural': 'ratingrules',
                'namespace': envvar('RATING_NAMESPACE'),
                'name': received['name'],
                'body': cr
            })
    except ApiException as exc:
        abort(make_response(str(exc), 400))
    return make_response(f'RatingRule {received["name"]} edited', 200)
Пример #2
0
def update_tenant_namespaces(tenant: AnyStr, namespaces: AnyStr):
    """
    Create the kubernetes namespaces for the tenant.

    :tenant (AnyStr) A string representing the tenant
    :namespaces (AnyStr) the user namespaces
    """
    api = client.CoreV1Api(get_client())
    for namespace in namespaces.split('-'):
        if not tenant:
            continue
        try:
            ns = api.read_namespace(name=namespace)
            labels = ns.metadata.labels
            if labels:
                if labels.get('tenants'):
                    labels['tenants'] += f'-{tenant}' \
                        if tenant not in labels['tenants'] else ''
                else:
                    labels['tenants'] = tenant
            api.patch_namespace(namespace,
                                body={'metadata': {
                                    'labels': labels
                                }})
        except ApiException:
            meta = client.V1ObjectMeta(labels={'tenants': tenant},
                                       name=namespace)
            ns = client.V1Namespace(metadata=meta)
            api.create_namespace(ns)
Пример #3
0
def new_frontend_rating_config() -> Response:
    """Add a new configuration, from the frontend."""
    received = load_from_form(request.form)
    try:
        schema.validate_request_content(received)
    except schema.ValidationError as exc:
        abort(make_response(jsonify(message=exc.message), 400))
    body = {
        'apiVersion': 'rating.alterway.fr/v1',
        'kind': 'RatingRule',
        'metadata': {
            'name': received['name'],
            'namespace': envvar('RATING_NAMESPACE')
        },
        'spec': {
            'metrics': received['metrics'],
            'rules': received['rules']
        }
    }

    try:
        api = client.CustomObjectsApi(get_client())
        api.create_namespaced_custom_object(
            **{
                'group': 'rating.alterway.fr',
                'version': 'v1',
                'namespace': envvar('RATING_NAMESPACE'),
                'plural': 'ratingrules',
                'body': body
            })
    except ApiException as exc:
        abort(make_response(str(exc), 400))
    return make_response(f'RatingRule {received["body"]["name"]} created', 200)
Пример #4
0
def models_rule_new() -> Response:
    """Create a RatingRuleModels."""
    config = request.form or request.get_json()
    body = {
        'apiVersion': 'rating.alterway.fr/v1',
        'kind': 'RatingRuleModels',
        'metadata': {
            'name': config['name']
        },
        'spec': {
            'timeframe': config['timeframe'],
            'metric': config['metric'],
            'name': config['metric_name']
        }
    }
    api = client.CustomObjectsApi(get_client())
    try:
        api.create_namespaced_custom_object(
            **{
                'group': 'rating.alterway.fr',
                'version': 'v1',
                'namespace': envvar('RATING_NAMESPACE'),
                'plural': 'ratingrulemodels',
                'body': body
            })
    except ApiException as exc:
        abort(make_response(str(exc), 400))
    return make_response(f'RatingRuleModels {config["name"]} created', 200)
Пример #5
0
def models_rule_edit() -> Response:
    """Edit a RatingRuleModels."""
    config = request.form or request.get_json()
    api = client.CustomObjectsApi(get_client())
    try:
        cr = api.get_namespaced_custom_object(
            **{
                'group': 'rating.alterway.fr',
                'version': 'v1',
                'plural': 'ratingrulemodels',
                'namespace': envvar('RATING_NAMESPACE'),
                'name': config['name']
            })

        cr['spec'] = {
            'metric': config.get('metric', cr['spec']['metric']),
            'timeframe': config.get('timeframe', cr['spec']['timeframe']),
            'name': config.get('metric_name', cr['spec']['name'])
        }
        api.patch_namespaced_custom_object(
            **{
                'group': 'rating.alterway.fr',
                'version': 'v1',
                'plural': 'ratingrulemodels',
                'namespace': envvar('RATING_NAMESPACE'),
                'name': config['name'],
                'body': cr
            })
    except ApiException as exc:
        abort(make_response(str(exc), 400))
    return make_response(f'RatingRuleModels {config["name"]} edited', 200)
Пример #6
0
def prometheus_config_get() -> Response:
    """Get the rating PrometheusRule."""
    try:
        api = client.CustomObjectsApi(get_client())
        response = api.get_namespaced_custom_object(**prometheus_object())
    except ApiException as exc:
        abort(make_response(str(exc), 400))
    return {'results': response, 'total': len(response['spec']['groups'])}
Пример #7
0
def delete_namespace(namespace: AnyStr):
    """
    Delete the namespace.

    :namespace (AnyStr) A string to represent the namespace.
    """
    try:
        client.CoreV1Api(get_client()).delete_namespace(namespace)
    except ApiException as exc:
        if exc.status == 404:
            abort(make_response(jsonify(msg=str(exc))), exc.status)
        raise exc
Пример #8
0
def prometheus_metric_delete() -> Response:
    """Delete a rule to the rating PrometheusRule."""
    api = client.CustomObjectsApi(get_client())
    prom_object = api.get_namespaced_custom_object(**prometheus_object())
    for group in prom_object['spec']['groups']:
        if group['name'] == request.form['group']:
            for rule in group['rules']:
                if rule['record'] == request.form['record']:
                    group['rules'].remove(rule)
    try:
        api.patch_namespaced_custom_object(**prometheus_object(),
                                           body=prom_object)
    except ApiException as exc:
        abort(make_response(str(exc), 400))
    return make_response('Metric removed', 200)
Пример #9
0
def models_rule_get() -> Response:
    """Get a RatingRuleModels."""
    api = client.CustomObjectsApi(get_client())
    try:
        response = api.get_namespaced_custom_object(
            **{
                'group': 'rating.alterway.fr',
                'version': 'v1',
                'plural': 'ratingrulemodels',
                'namespace': envvar('RATING_NAMESPACE'),
                'name': request.args.to_dict()['name']
            })
    except ApiException as exc:
        abort(make_response(str(exc), 400))
    return {'results': response, 'total': 1}
Пример #10
0
def delete_frontend_rating_config() -> Response:
    """Delete a configuration, from the frontend."""
    try:
        api = client.CustomObjectsApi(get_client())
        api.delete_namespaced_custom_object(
            **{
                'group': 'rating.alterway.fr',
                'version': 'v1',
                'namespace': envvar('RATING_NAMESPACE'),
                'plural': 'ratingrules',
                'name': request.form['name']
            })
    except ApiException as exc:
        abort(make_response(str(exc), 400))
    return make_response(f'RatingRule {request.form["name"]} deleted', 200)
Пример #11
0
def models_rule_delete() -> Response:
    """Delete a RatingRuleModels."""
    config = request.form or request.get_json()
    api = client.CustomObjectsApi(get_client())
    try:
        api.delete_namespaced_custom_object(
            **{
                'group': 'rating.alterway.fr',
                'version': 'v1',
                'namespace': envvar('RATING_NAMESPACE'),
                'plural': 'ratingrulemodels',
                'name': config['name']
            })
    except ApiException as exc:
        abort(make_response(str(exc), 400))
    return make_response(f'RatingRuleModels {config["name"]} deleted', 200)
Пример #12
0
def models_rule_list() -> Response:
    """Get the RatingRuleModel."""
    try:
        api = client.CustomObjectsApi(get_client())
        response = api.list_namespaced_custom_object(
            **{
                'group': 'rating.alterway.fr',
                'version': 'v1',
                'plural': 'ratingrulemodels',
                'namespace': envvar('RATING_NAMESPACE')
            })
    except ApiException as exc:
        abort(make_response(str(exc), 400))
    return {
        'results': [item['metadata']['name'] for item in response['items']],
        'total': 1
    }
Пример #13
0
def modify_namespace(tenant: AnyStr, namespace: AnyStr):
    """
    Modify the tenant assigned to a namespace.

    :tenant (AnyStr) A string representing the tenant.
    :namespace (AnyStr) A string representing the namespace to assign to the tenant.
    """
    api = client.CoreV1Api(get_client())
    labels = {'tenant': tenant}
    meta = client.V1ObjectMeta(labels=labels, name=namespace)
    ns = client.V1Namespace(metadata=meta)
    try:
        api.patch_namespace(namespace, ns)
    except ApiException as exc:
        if exc.status == 404:
            abort(make_response(jsonify(msg=str(exc))), exc.status)
        raise exc
Пример #14
0
def frontend_rating_config(config_name: AnyStr) -> Response:
    """
    Get the RatingRule for a given configuration name.

    :config_name (AnyStr) A string representing the configuration name.

    Return the configuration or abort.
    """
    try:
        api = client.CustomObjectsApi(get_client())
        response = api.get_namespaced_custom_object(
            **{
                'group': 'rating.alterway.fr',
                'version': 'v1',
                'plural': 'ratingrules',
                'namespace': envvar('RATING_NAMESPACE'),
                'name': config_name
            })
    except ApiException as exc:
        abort(make_response(str(exc), 400))
    return {'results': response, 'total': 1}
Пример #15
0
def update_rated_metrics_object(metric: AnyStr, last_insert: AnyStr):
    """
    Update a RatedMetrics object.

    :metric (AnyStr) A name representing the metric to be updated
    :last_insert (AnyStr) The timestamp of the latest data frame rating
    """
    config.load_incluster_config()
    rated_metric = f'rated-{metric.replace("_", "-")}'
    rated_namespace = envvar('RATING_NAMESPACE')
    custom_api = client.CustomObjectsApi(get_client())
    body = {
        'apiVersion': 'rating.alterway.fr/v1',
        'kind': 'RatedMetric',
        'metadata': {
            'namespace': rated_namespace,
            'name': rated_metric,
        },
        'spec': {
            'metric': metric,
            'date': last_insert
        }
    }
    try:
        custom_api.create_namespaced_custom_object(group='rating.alterway.fr',
                                                   version='v1',
                                                   namespace=rated_namespace,
                                                   plural='ratedmetrics',
                                                   body=body)
    except ApiException as exc:
        if exc.status != 409:
            raise exc
        custom_api.patch_namespaced_custom_object(group='rating.alterway.fr',
                                                  version='v1',
                                                  namespace=rated_namespace,
                                                  plural='ratedmetrics',
                                                  name=rated_metric,
                                                  body=body)
Пример #16
0
def create_tenant_namespace(tenant: AnyStr, quantity: int):
    """
    Create namespaces for the tenant.

    :tenant (AnyStr) A string to represent the tenant name, to annotate the namespaces.
    :quantity (int) A number of namespaces to create and assign to the tenant.
    """
    api = client.CoreV1Api(get_client())
    labels = {'tenant': tenant}
    for number in range(int(quantity)):
        rd = ''.join([
            random.choice(string.ascii_letters + string.digits)
            for n in range(8)
        ])
        name = f'{tenant}-{number}-{rd}'.lower()
        meta = client.V1ObjectMeta(labels=labels, name=name)
        namespace = client.V1Namespace(metadata=meta)
        try:
            api.create_namespace(namespace)
        except ApiException as exc:
            if exc.status == 403:
                abort(make_response(jsonify(msg=str(exc))), exc.status)
            raise exc
Пример #17
0
def prometheus_metric_add():
    """Add a rule to the rating PrometheusRule."""
    api = client.CustomObjectsApi(get_client())
    prom_object = api.get_namespaced_custom_object(**prometheus_object())
    found = False
    payload = {'expr': request.form['expr'], 'record': request.form['record']}
    for group in prom_object['spec']['groups']:
        if group['name'] == request.form['group']:
            if payload in group['rules']:
                abort(make_response('Metric already exist', 400))
            group['rules'].append(payload)
            found = True
    if not found:
        prom_object['spec']['groups'].append({
            'name': request.form['group'],
            'rules': [payload]
        })
    try:
        api.patch_namespaced_custom_object(**prometheus_object(),
                                           body=prom_object)
    except ApiException as exc:
        abort(make_response(str(exc), 400))
    return make_response('Metric added', 200)