Esempio n. 1
0
def service_catalog(request, form: ServiceForm = None, received_context={}):
    if form is None:
        form = ServiceForm()

    must_configure = esm_endpoint_check(request)
    if must_configure:
        return must_configure

    url = request.session.get('esm_endpoint', "") + "/v2/catalog"
    headers = {
        'Accept': "application/json",
        'X-Broker-Api-Version': "2.12",
        'Cache-Control': "no-cache",
        'Postman-Token': "72c68829-43b4-916d-afc8-a8ecc3d7f8bd"
    }
    response = requests.request("GET", url, headers=headers)

    context = {
        'services': parse_services(json.loads(response.text)),
        'bootstrap_services': bootstrap_services(),
        'form': form,
    }
    context = {**received_context, **context}

    return render(request, 'services/index.html', context)
Esempio n. 2
0
def delete_instance(request, parameter):
    # todo add Are you sure? modal
    must_configure = esm_endpoint_check(request)
    if must_configure:
        return must_configure

    url = request.session.get(
        'esm_endpoint') + "/v2/service_instances/{}".format(parameter)

    querystring = {
        "service_id": "b1620b13-7d11-4abc-a762-f34a108ea49c",
        "plan_id": "36ed4b3e-c132-4746-af71-26dee76e59cb",
        "accept_incomplete": "false"
    }

    headers = {
        'Accept': "application/json",
        'X-Broker-Api-Version': "2.12",
        'Cache-Control': "no-cache",
        'Postman-Token': "fd232188-3e1e-68c3-f1ef-79135efb9be1"
    }

    response = requests.request("DELETE",
                                url,
                                headers=headers,
                                params=querystring)
    print('instance deprovisioned', response.text)

    if response.status_code == 200:
        messages.success(request, utils.SUCCESS_DEPROVISION_MESSAGE)
        return redirect('/instances/index.html')

    else:
        messages.error(request, utils.ERROR_DEPROVISION_MESSAGE)
        return redirect('/instances/index.html')
Esempio n. 3
0
def import_service(request):
    json_data = json.loads(json.dumps(request.POST))
    print("Received form JSON: {}".format(json_data))

    # verify ESM connection established
    must_configure = esm_endpoint_check(request)
    if must_configure:
        return must_configure

    # validate URL and get what matters
    selected = get_selected_services(
        request.POST.getlist('service_definitions'),
        request.POST.get('import_service_form_url'))
    print("Filtered selected: {}".format(selected))

    responses = {}
    responses_numeric = 0
    for k, v in selected.items():
        response_temp = 0

        # Register Service and Plans
        service_cache = v['service']
        url, payload, headers = build_create_service_request(
            request, service_cache)
        response = requests.request("PUT", url, data=payload, headers=headers)
        print('service registered', response.text)
        if response.status_code == 200:
            response_temp += 1

        # Register Manifest
        for manifest_cache in v['manifests']:
            url, payload, headers = build_create_manifest_request(
                request, manifest_cache)
            response = requests.request("PUT",
                                        url,
                                        data=payload,
                                        headers=headers)
            print('manifest registered', response.text)
            if response.status_code == 200:
                response_temp += 1

        responses[k] = True if response_temp > 0 else False
        responses_numeric += response_temp

    if responses_numeric > 0:
        # TODO adapt message to show the result of each service :]
        messages.success(request, utils.SUCCESS_MESSAGE + str(responses))
        return redirect('/catalog/')

    else:
        messages.error(request, utils.ERROR_MESSAGE + str(responses))
        return redirect('/catalog/')
Esempio n. 4
0
def create_service(request):
    must_configure = esm_endpoint_check(request)
    if must_configure:
        return must_configure

    form = ServiceForm(request.POST, request.FILES)

    if form.is_valid():
        cache = form.cleaned_data
        cache['preview_image'] = parse_image(
            request.FILES.get('preview_image'))
        cache['logo_image'] = parse_image(request.FILES.get('logo_image'))
        cache['plans'] = parse_plans(cache, request.POST)
        cache['service_variables'] = parse_variables(cache, request.POST)
        cache['service_id'] = uuid.uuid4().hex
        # TODO add support for multiple plans
        # cache['plan_id'] = uuid.uuid4().hex
        cache['manifest_id'] = uuid.uuid4().hex

        # Register Service and Plans
        url, payload, headers = build_create_service_request(request, cache)
        response = requests.request("PUT", url, data=payload, headers=headers)
        print('service registered', response.text)

        # Register Manifest
        # todo adjust to new plans
        for plan in cache['plans']:
            url, payload, headers = build_create_manifest_request(
                request, cache, plan['id'])
            response = requests.request("PUT",
                                        url,
                                        data=payload,
                                        headers=headers)
            print('manifest registered', response.text)

        if response.status_code == 200:
            messages.success(request, utils.SUCCESS_MESSAGE)
            return redirect('/catalog/')

        else:
            messages.error(request, utils.ERROR_MESSAGE)
            return redirect('/catalog/')

    # from django.http import HttpResponse
    # return HttpResponse('errors' + str(form.errors))
    else:
        return service_catalog(request, form)
Esempio n. 5
0
def create_instance(request, parameter=None):
    # todo block to create an instance thats already running (plan, service) too often
    must_configure = esm_endpoint_check(request)
    if must_configure:
        return must_configure

    if 'k' in parameter:
        service_id, plan_id = parameter.split("k")
        instance_id = uuid.uuid4().hex
        url = request.session.get(
            'esm_endpoint') + "/v2/service_instances/" + instance_id

        querystring = {"accept_incomplete": "false"}

        payload = "{\"organization_guid\": \"org\", \"plan_id\": \"" + plan_id + "\", \"service_id\": \"" + service_id + "\",\"space_guid\": \"space\"}"

        headers = {
            'Accept': "application/json",
            'Content-Type': "application/json",
            'X-Broker-Api-Version': "2.12",
            'Cache-Control': "no-cache",
            'Postman-Token': "7d98544d-3d9c-aa34-b6b1-4755fad9c8b6"
        }

        response = requests.request("PUT",
                                    url,
                                    data=payload,
                                    headers=headers,
                                    params=querystring)
        print('instance', response.text)
        print('instance response status_code', response.status_code)
        if response.status_code == 200:
            messages.success(request, utils.SUCCESS_PROVISION_MESSAGE)
            return redirect('/instances/')

        else:
            messages.error(request, response.text)
            return redirect('/instances/'.format(service_id))
    else:
        # this would only happen when someone tries to forge a request
        messages.error(request, utils.ERROR_MESSAGE)
        return redirect('/instances/')
Esempio n. 6
0
def service_detail(request, service_id=None):
    must_configure = esm_endpoint_check(request)
    if must_configure:
        return must_configure

    url = request.session.get('esm_endpoint') + "/v2/catalog"
    headers = {
        'Accept': "application/json",
        'X-Broker-Api-Version': "2.12",
        'Cache-Control': "no-cache",
        'Postman-Token': "72c68829-43b4-916d-afc8-a8ecc3d7f8bd"
    }
    response = requests.request("GET", url, headers=headers)

    parsed_services = parse_services(json.loads(response.text))
    for service in parsed_services:
        if service['id'] == service_id:
            context = {'service': service}
            return render(request, 'services/show.html', context)

    # todo return error message item not found
    return redirect('/catalog/')
Esempio n. 7
0
def instance_catalog(request, previous_context={}):
    must_configure = esm_endpoint_check(request)
    if must_configure:
        return must_configure

    url = request.session.get('esm_endpoint') + "/v2/et/service_instances"
    headers = {
        'X-Broker-Api-Version': "2.12",
        'Cache-Control': "no-cache",
        'Postman-Token': "8a6bfa39-d96f-fa28-61d8-e3a480c937db"
    }
    response = requests.request("GET", url, headers=headers)

    if response.status_code == 200:
        parsed_instances = parse_instances(request, json.loads(response.text))
    else:
        parsed_instances = []
    # return render(request, 'instances/index.html', {'instances': parsed_instances + bootstrap_instances()})
    context = {
        'instances': parsed_instances,
        'bootstrap_instances': bootstrap_instances(),
    }
    context = {**context, **previous_context}
    return render(request, 'instances/index.html', context)
Esempio n. 8
0
def instance_detail(request, instance_id=None):
    must_configure = esm_endpoint_check(request)
    if must_configure:
        return must_configure

    url = request.session.get(
        'esm_endpoint') + "/v2/et/service_instances/{}".format(instance_id)

    headers = {
        'X-Broker-Api-Version': "2.12",
        'Cache-Control': "no-cache",
        'Postman-Token': "66fba99d-2fe6-d11e-0424-1488c889132b"
    }

    response = requests.request("GET", url, headers=headers)

    if response.status_code == 200:
        parsed_instance = parse_instances(request,
                                          [json.loads(response.text)])[0]

        # query influx db: containers_data
        host = 'kafka.cloudlab.zhaw.ch'
        port = 8086
        user = '******'
        password = '******'
        dbname = 'user-1-elastest_tss'
        query = 'select * from "service-docker-stats" group by "container-name" order by desc limit 10;'
        from influxdb import InfluxDBClient
        client = InfluxDBClient(host, port, user, password, dbname)
        print("Querying data: " + query)
        containers_data = client.query(query)
        # name = result.raw['series'][0]['name']  # str
        # columns = result.raw['series'][0]['columns']  # []
        # values = result.raw['series'][0]['values']  # [[]]
        containers = []
        global fake_flag
        print('containers found from parsed instance: ',
              parsed_instance['container_names'])
        # print('query result: ', containers_data)
        if containers_data:
            for serie in containers_data.raw['series']:
                CPU_series = []
                RAM_series = []
                name = serie['tags']['container-name']
                # todo remove
                print('sentinel container name:', name)
                if name in parsed_instance['container_names']:
                    # if True:
                    print('container match found!')
                    for x in serie['values']:
                        CPU_series.append(x[3])
                    for x in serie['values']:
                        RAM_series.append(x[5])
                    name = name.split('_', 1)[-1]
                    CPU_series = [0, 2, 3.4, 0.4, 0.1]
                    RAM_series = [0, 50, 60, 10, 2]

                    CPU_series = reverse_and_fill_series(CPU_series)
                    RAM_series = reverse_and_fill_series(RAM_series)
                    print('resulting..', CPU_series)
                    containers.append([name, CPU_series, RAM_series])
            # print(containers)

        query = 'select * from "service-health-check" order by desc limit 10;'
        health_data = client.query(query).raw
        health_series = []
        # demo
        health_series = [1, 1, 0, 0]
        health_series = reverse_and_fill_series(health_series)

        print('status...', parsed_instance['status'])
        print('health data queried: ', health_data)
        print(parsed_instance)
        if len(health_data) > 1:
            print('health data > 1...')
            health_data = health_data['series'][0]
            # print('instance id: ', instance_id)
            if 'instance_id' in health_data['columns']:
                # instance_index = health_data['columns'].index('instance_id')
                # msg_index = health_data['columns'].index('msg')
                # # health_series = ['alive' in record['msg'] for record in health_data['values'] if instance_id == record[index]]
                # health_series = [int('alive' in record[msg_index]) for record in health_data['values']]
                # # for record in health_data['values']:
                # #     if instance_id == record[index]:
                # #         if 'alive' in record['msg']:
                # #             status = 1
                # #         else:
                # #             status = 0
                # #         health_series.append(status)
                health_series = [0, 1, 1, 1]
                health_series = reverse_and_fill_series(health_series)
                print('health series for this instance:', health_series)
        elif parsed_instance['status'] != 'running':
            parsed_instance['color'] = 'warning'
            parsed_instance['status_icon'] = 'more_horiz'
            # parsed_instance['hex_color'] = '#4caf50'
            parsed_instance['hex_color'] = '#fd9a0f'

        return render(
            request, 'instances/show.html', {
                'instance': parsed_instance,
                'containers': json.dumps(containers),
                'health_series': health_series
            })
    else:
        # todo return error message instance not found
        return instance_catalog(request)
Esempio n. 9
0
def welcome(request):
    must_configure = esm_endpoint_check(request)
    if must_configure:
        return must_configure

    return render(request, 'welcome.html')