Пример #1
0
def relist_service_broker(kwargs):
    try:
        openshift_config.load_kube_config()
        token = openshift_client.Configuration().get_api_key_with_prefix('authorization')
        cluster_host = openshift_client.Configuration().host
        broker_name = kwargs['broker_name']
        headers = {}
        if kwargs['basic_auth_username'] is not None and kwargs['basic_auth_password'] is not None:
            headers = {'Authorization': "Basic " +
                       base64.b64encode("{0}:{1}".format(kwargs['basic_auth_username'],
                                                         kwargs['basic_auth_password']))
                       }
        else:
            headers = {'Authorization': token}

        response = requests.request(
            "get",
            broker_resource_url(cluster_host, broker_name),
            verify=kwargs['verify'], headers=headers)

        if response.status_code != 200:
            errMsg = "Received non-200 status code while retrieving broker: {}\n".format(broker_name) + \
                "Response body:\n" + \
                str(response.text)
            raise Exception(errMsg)

        spec = response.json().get('spec', None)
        if spec is None:
            errMsg = "Spec not found in broker reponse. Response body: \n{}".format(response.text)
            raise Exception(errMsg)

        relist_requests = spec.get('relistRequests', None)
        if relist_requests is None:
            errMsg = "relistRequests not found within the spec of broker: {}\n".format(broker_name) + \
                     "Are you sure you are using a ServiceCatalog of >= v0.0.21?"
            raise Exception(errMsg)

        inc_relist_requests = relist_requests + 1

        headers['Content-Type'] = 'application/strategic-merge-patch+json'
        response = requests.request(
            "patch",
            broker_resource_url(cluster_host, broker_name),
            json={'spec': {'relistRequests': inc_relist_requests}},
            verify=kwargs['verify'], headers=headers)

        if response.status_code != 200:
            errMsg = "Received non-200 status code while patching relistRequests of broker: {}\n".format(
                broker_name) + \
                "Response body:\n{}".format(str(response.text))
            raise Exception(errMsg)

        print("Successfully relisted the Service Catalog")
    except Exception as e:
        print("Relist failure: {}".format(e))
Пример #2
0
def push_apb(registry, tag):
    try:
        client = create_docker_client()
        openshift_config.load_kube_config()
        api_key = openshift_client.Configuration().get_api_key_with_prefix(
            'authorization')
        if api_key is None:
            raise Exception(
                "No api key found in kubeconfig. NOTE: system:admin " +
                "*cannot* be used with apb, since it does not have a token.")
        token = api_key.split(" ")[1]
        username = "******" if is_minishift() else "unused"
        client.login(username=username,
                     password=token,
                     registry=registry,
                     reauth=True)
        delete_old_images(tag)

        print("Pushing the image, this could take a minute...")
        client.images.push(tag)
        print("Successfully pushed image: " + tag)
    except docker.errors.DockerException:
        print("Error accessing the docker API. Is the daemon running?")
        raise
    except docker.errors.APIError:
        print("Failed to login to the docker API.")
        raise
Пример #3
0
def broker_request(broker, service_route, method, **kwargs):
    if broker is None:
        broker = get_asb_route()

    if broker is None:
        raise Exception(
            "Could not find route to ansible-service-broker. "
            "Use --broker or log into the cluster using \"oc login\"")

    if not broker.endswith('/ansible-service-broker'):
        if not broker.endswith('/'):
            broker = broker + '/'
        broker = broker + 'ansible-service-broker'

    if not broker.startswith('http'):
        broker = 'https://' + broker

    url = broker + service_route
    print("Contacting the ansible-service-broker at: %s" % url)

    try:
        openshift_config.load_kube_config()
        headers = {}
        if kwargs['basic_auth_username'] is not None and kwargs[
                'basic_auth_password'] is not None:
            headers = {
                'Authorization':
                "Basic " + base64.b64encode("{0}:{1}".format(
                    kwargs['basic_auth_username'],
                    kwargs['basic_auth_password']))
            }
        else:
            token = openshift_client.Configuration().get_api_key_with_prefix(
                'authorization')
            headers = {'Authorization': token}
        response = requests.request(method,
                                    url,
                                    verify=kwargs["verify"],
                                    headers=headers,
                                    data=kwargs.get("data"))
    except Exception as e:
        print("ERROR: Failed broker request (%s) %s" % (method, url))
        raise e

    return response
Пример #4
0
def push_apb(registry, tag):
    try:
        client = create_docker_client()
        openshift_config.load_kube_config()
        token = openshift_client.Configuration().get_api_key_with_prefix(
            'authorization').split(" ")[1]
        username = "******" if is_minishift() else "unused"
        client.login(username=username,
                     password=token,
                     registry=registry,
                     reauth=True)

        print("Pushing the image, this could take a minute...")
        client.images.push(tag)
        print("Successfully pushed image: " + tag)
    except docker.errors.DockerException:
        print("Error accessing the docker API. Is the daemon running?")
        raise
    except docker.errors.APIError:
        print("Failed to login to the docker API.")
        raise
Пример #5
0
def cmdrun_push(**kwargs):
    project = kwargs['base_path']
    spec = get_spec(project, 'string')
    dict_spec = get_spec(project, 'dict')
    blob = base64.b64encode(spec)
    data_spec = {'apbSpec': blob}
    broker = kwargs["broker"]
    if broker is None:
        broker = get_asb_route()
    print(spec)
    if kwargs['broker_push']:
        response = broker_request(
            broker,
            "/v2/apb",
            "post",
            data=data_spec,
            verify=kwargs["verify"],
            basic_auth_username=kwargs.get("basic_auth_username"),
            basic_auth_password=kwargs.get("basic_auth_password"))

        if response.status_code != 200:
            print(
                "Error: Attempt to add APB to the Broker returned status: %d" %
                response.status_code)
            print("Unable to add APB to Ansible Service Broker.")
            exit(1)

        print("Successfully added APB to Ansible Service Broker")
        return

    namespace = kwargs['reg_namespace']
    service = kwargs['reg_svc_name']
    registry_route = kwargs['reg_route']

    if registry_route:
        registry = registry_route
    elif is_minishift():
        registry = get_minishift_registry()
    else:
        registry = get_registry_service_ip(namespace, service)
        if registry is None:
            print("Failed to find registry service IP address.")
            raise Exception("Unable to get registry IP from namespace %s" %
                            namespace)

    tag = registry + "/" + kwargs['namespace'] + "/" + dict_spec['name']
    print("Building image with the tag: " + tag)
    try:
        client = create_docker_client()
        client.images.build(path=project,
                            tag=tag,
                            dockerfile=kwargs['dockerfile'])
        openshift_config.load_kube_config()
        token = openshift_client.Configuration().get_api_key_with_prefix(
            'authorization').split(" ")[1]
        username = "******" if is_minishift() else "unused"
        client.login(username=username,
                     password=token,
                     registry=registry,
                     reauth=True)

        print("Pushing the image, this could take a minute...")
        client.images.push(tag)

        print("Successfully pushed image: " + tag)
        bootstrap(broker, kwargs.get("basic_auth_username"),
                  kwargs.get("basic_auth_password"), kwargs["verify"])
    except docker.errors.DockerException:
        print("Error accessing the docker API. Is the daemon running?")
        raise
    except docker.errors.APIError:
        print("Failed to login to the docker API.")
        raise

    if not kwargs['no_relist']:
        relist_service_broker(kwargs)