def set_ovdc_container_provider_metadata(self,
                                             ovdc_id,
                                             container_prov_data=None,
                                             container_provider=None):
        """Set the container provider metadata of given ovdc.

        :param resource ovdc: vdc resource
        :param dict container_prov_data: container provider context details
        :param str container_provider: name of container provider for which
            the ovdc is being enabled to deploy k8 clusters on.
        """
        client = None
        try:
            client = get_sys_admin_client()
            ovdc = get_vdc(client, vdc_id=ovdc_id)
            ovdc_name = ovdc.get_resource().get('name')

            metadata = {}
            metadata[K8S_PROVIDER_KEY] = container_provider or \
                K8sProviders.NONE

            if container_provider != K8sProviders.PKS:
                LOGGER.debug(f"Remove existing metadata for ovdc:{ovdc_name}")
                self._remove_metadata_from_ovdc(ovdc, PksCache.get_pks_keys())

                LOGGER.debug(f"Updated metadata for {container_provider}:"
                             f"{metadata}")
            else:
                container_prov_data.pop('username')
                container_prov_data.pop('secret')
                container_prov_data.pop('nsxt')
                metadata.update(container_prov_data)

            # set ovdc metadata into Vcd
            LOGGER.debug(f"On ovdc:{ovdc_name}, setting metadata:{metadata}")
            return ovdc.set_multiple_metadata(metadata, MetadataDomain.SYSTEM,
                                              MetadataVisibility.PRIVATE)
        finally:
            if client:
                client.logout()
    def _list_clusters(self):
        """Get list of clusters in PKS environment.

        :return: a list of cluster-dictionaries

        :rtype: list
        """
        cluster_api = ClusterApiV1(api_client=self.client_v1)

        LOGGER.debug(f"Sending request to PKS: {self.pks_host_uri} "
                     f"to list all clusters")
        try:
            clusters = cluster_api.list_clusters()
        except v1Exception as err:
            LOGGER.debug(f"Listing PKS clusters failed with error:\n {err}")
            raise PksServerError(err.status, err.body)

        list_of_cluster_dicts = []
        for cluster in clusters:
            # TODO() Below is a temporary fix to retrieve compute_profile_name.
            #  Expensive _get_cluster_info() call must be removed once PKS team
            #  moves list_clusters to v1beta endpoint.
            v1_beta_cluster = self._get_cluster_info(cluster_name=cluster.name)
            # cluster_dict = {
            #     'name': cluster.name,
            #     'plan_name': cluster.plan_name,
            #     'uuid': cluster.uuid,
            #     'status': cluster.last_action_state,
            #     'last_action': cluster.last_action,
            #     'k8_master_ips': cluster.kubernetes_master_ips,
            #     'compute_profile_name': cluster.compute_profile_name,
            #     'worker_count':
            #     cluster.parameters.kubernetes_worker_instances
            # }
            # list_of_cluster_dicts.append(cluster_dict)
            list_of_cluster_dicts.append(v1_beta_cluster)

        LOGGER.debug(f"Received response from PKS: {self.pks_host_uri} on the"
                     f" list of clusters: {list_of_cluster_dicts}")
        return list_of_cluster_dicts
    def find_cluster_in_org(self, cluster_name, is_org_admin_search=False):
        """Invoke all PKS brokers in the org to find the cluster.

        'is_org_admin_search' is used here to prevent cluster creation with
        same cluster-name by users within org. If it is true,
        cluster list is filtered by the org name of the logged-in user.

        If cluster found:
            Return a tuple of (cluster and the broker instance used to find
            the cluster)
        Else:
            (None, None) if cluster not found.
        """
        pks_ctx_list = \
            self.create_pks_context_for_all_accounts_in_org()
        for pks_ctx in pks_ctx_list:
            pksbroker = PKSBroker(self.tenant_auth_token, self.req_spec,
                                  pks_ctx)
            try:
                return pksbroker.get_cluster_info(
                    cluster_name=cluster_name,
                    is_org_admin_search=is_org_admin_search), pksbroker
            except PksClusterNotFoundError as err:
                # If a cluster is not found, then broker_manager will
                # decide if it wants to raise an error or ignore it if was it
                # just scanning the broker to check if it can handle the
                # cluster request or not.
                LOGGER.debug(f"Get cluster info on {cluster_name}"
                             f"on PKS failed with error: {err}")
            except PksDuplicateClusterError as err:
                LOGGER.debug(f"Get cluster info on {cluster_name}"
                             f"on PKS failed with error: {err}")
                raise
            except PksServerError as err:
                LOGGER.debug(f"Get cluster info on {cluster_name} failed "
                             f"on {pks_ctx['host']} with error: {err}")
        return None, None
Exemplo n.º 4
0
def process_request(message):
    from container_service_extension.service import Service
    LOGGER.debug(f"Incoming request message: {json.dumps(message)}")

    api_version_header = _parse_accept_header(
        accept_header=message['headers'].get('Accept'))
    api_version = _get_api_version_from_accept_header(
        api_version_header=api_version_header)

    url_data = _get_url_data(method=message['method'],
                             url=message['requestUri'],
                             api_version=api_version)  # noqa: E501
    operation = url_data[_OPERATION_KEY]

    # Check api version and if server is disabled or not
    # /system operations are excluded from these checks
    if operation not in (CseOperation.SYSTEM_INFO, CseOperation.SYSTEM_UPDATE):
        if not Service().is_running():
            raise cse_exception.BadRequestError(
                error_message='CSE service is disabled. '
                'Contact the System Administrator.')
        else:
            server_api_version = utils.get_server_api_version()
            if api_version != server_api_version:
                raise cse_exception.NotAcceptableRequestError(
                    error_message="Invalid api version specified. Expected "
                    f"api version '{server_api_version}'.")

    # create request data dict from incoming message data
    request_data = {}
    is_cse_3_0_request = _is_cse_3_0_endpoint(message['requestUri'])
    if len(message['body']) > 0:
        raw_body = base64.b64decode(message['body']).decode(
            sys.getfilesystemencoding())  # noqa: E501
        request_body = json.loads(raw_body)
        if is_cse_3_0_request:
            request_data[shared_constants.RequestKey.V35_SPEC] = request_body
        else:
            request_data.update(request_body)
        LOGGER.debug(f"request body: {request_data}")
    # update request data dict with query params data
    if message['queryString']:
        query_params = dict(parse_qsl(message['queryString']))
        if is_cse_3_0_request:
            request_data[shared_constants.RequestKey.V35_QUERY] = query_params
        else:
            request_data.update(query_params)
        LOGGER.debug(f"query parameters: {query_params}")
    # update request spec with operation specific data in the url
    request_data.update(url_data)
    # remove None values from request payload
    data = {k: v for k, v in request_data.items() if v is not None}
    # extract out the authorization token
    tenant_auth_token = message['headers'].get('x-vcloud-authorization')
    is_jwt_token = False
    auth_header = message['headers'].get('Authorization')
    if auth_header:
        tokens = auth_header.split(" ")
        if len(tokens) == 2 and tokens[0].lower() == 'bearer':
            tenant_auth_token = tokens[1]
            is_jwt_token = True

    # create operation context
    operation_ctx = ctx.OperationContext(tenant_auth_token,
                                         is_jwt=is_jwt_token,
                                         request_id=message['id'])

    try:
        body_content = OPERATION_TO_HANDLER[operation](data, operation_ctx)
    finally:
        if not operation_ctx.is_async:
            operation_ctx.end()

    if not isinstance(body_content, (list, dict)):
        body_content = \
            {shared_constants.RESPONSE_MESSAGE_KEY: str(body_content)}
    response = {
        'status_code': operation.ideal_response_code,
        'body': body_content,
    }
    LOGGER.debug(f"Outgoing response: {str(response)}")
    return response
Exemplo n.º 5
0
 def on_channel_open(self, channel):
     LOGGER.debug('Channel opened')
     self._channel = channel
     self.add_on_channel_close_callback()
     self.setup_exchange(self.exchange)
Exemplo n.º 6
0
 def add_on_connection_close_callback(self):
     LOGGER.debug('Adding connection close callback')
     self._connection.add_on_close_callback(self.on_connection_closed)
Exemplo n.º 7
0
 def close_channel(self):
     LOGGER.debug('Closing the channel')
     self._channel.close()
Exemplo n.º 8
0
 def acknowledge_message(self, delivery_tag):
     LOGGER.debug('Acknowledging message %s', delivery_tag)
     self._channel.basic_ack(delivery_tag)
Exemplo n.º 9
0
 def add_on_cancel_callback(self):
     LOGGER.debug('Adding consumer cancellation callback')
     self._channel.add_on_cancel_callback(self.on_consumer_cancelled)
Exemplo n.º 10
0
 def setup_queue(self, queue_name):
     LOGGER.debug(f"Declaring queue {queue_name}")
     self._channel.queue_declare(self.on_queue_declareok, queue_name)
Exemplo n.º 11
0
 def on_exchange_declareok(self, unused_frame):
     LOGGER.debug(f"Exchange declared: {unused_frame}")
     self.setup_queue(self.queue)
Exemplo n.º 12
0
    def process_request(self, body):
        LOGGER.debug(f"body: {json.dumps(body)}")
        reply = {}
        tokens = body['requestUri'].split('/')
        cluster_name = None
        node_name = None
        spec_request = False
        config_request = False
        template_request = False
        node_request = False
        cluster_info_request = False
        node_info_request = False
        system_request = False
        ovdc_request = False
        ovdc_id = None
        ovdc_info_request = False

        if len(tokens) > 3:
            if tokens[3] in ['swagger', 'swagger.json', 'swagger.yaml']:
                spec_request = True
            elif tokens[3] == 'template':
                template_request = True
            elif tokens[3] == 'system':
                system_request = True
            elif tokens[3] == 'ovdc':
                ovdc_request = True
            elif tokens[3] != '':
                cluster_name = tokens[3]
        if len(tokens) > 4:
            if cluster_name is not None:
                if tokens[4] == 'config':
                    config_request = True
                elif tokens[4] == 'info':
                    cluster_info_request = True
                elif tokens[4] == 'node':
                    node_request = True
                elif tokens[4] != '':
                    node_name = tokens[4]
            elif ovdc_request:
                ovdc_id = tokens[4]

        if len(tokens) > 5:
            if node_name is not None:
                if tokens[5] == 'info':
                    node_info_request = True
            elif ovdc_request:
                if tokens[5] == 'info':
                    ovdc_info_request = True
        if len(body['body']) > 0:
            try:
                request_body = json.loads(
                    base64.b64decode(body['body']).decode(
                        sys.getfilesystemencoding()))
            except Exception:
                LOGGER.error(traceback.format_exc())
                request_body = {}
        else:
            request_body = {}
        LOGGER.debug(f"request body: {json.dumps(request_body)}")

        query_params = {}
        if body['queryString']:
            query_params = dict(parse_qsl(body['queryString']))

        from container_service_extension.service import Service
        service = Service()
        if not system_request and not service.is_enabled:
            raise CseServerError('CSE service is disabled. '
                                 'Contact the System Administrator.')

        req_headers = deepcopy(body['headers'])
        req_query_params = deepcopy(query_params)
        req_spec = deepcopy(request_body)

        from container_service_extension.broker_manager import BrokerManager
        broker_manager = BrokerManager(req_headers, req_query_params, req_spec)
        from container_service_extension.broker_manager import Operation

        if body['method'] == 'GET':
            if ovdc_info_request:
                req_spec.update({'ovdc_id': ovdc_id})
                reply = broker_manager.invoke(Operation.INFO_OVDC)
            elif ovdc_request:
                reply = broker_manager.invoke(op=Operation.LIST_OVDCS)
            elif spec_request:
                reply = self.get_spec(tokens[3])
            elif config_request:
                req_spec.update({'cluster_name': cluster_name})
                reply = broker_manager.invoke(Operation.GET_CLUSTER_CONFIG)
            elif template_request:
                result = {}
                templates = []
                server_config = get_server_runtime_config()
                default_template_name = \
                    server_config['broker']['default_template']
                for t in server_config['broker']['templates']:
                    is_default = t['name'] == default_template_name
                    templates.append({
                        'name':
                        t['name'],
                        'is_default':
                        is_default,
                        'catalog':
                        server_config['broker']['catalog'],
                        'catalog_item':
                        t['catalog_item'],
                        'description':
                        t['description']
                    })
                result['body'] = templates
                result['status_code'] = 200
                reply = result
            elif cluster_info_request:
                req_spec.update({'cluster_name': cluster_name})
                reply = broker_manager.invoke(Operation.GET_CLUSTER)
            elif node_info_request:
                broker = broker_manager.get_broker_based_on_vdc()
                reply = broker.get_node_info(cluster_name, node_name)
            elif system_request:
                result = {}
                result['body'] = service.info(req_headers)
                result['status_code'] = OK
                reply = result
            elif cluster_name is None:
                reply = broker_manager.invoke(Operation.LIST_CLUSTERS)
        elif body['method'] == 'POST':
            if cluster_name is None:
                reply = broker_manager.invoke(Operation.CREATE_CLUSTER)
            else:
                if node_request:
                    broker = broker_manager.get_broker_based_on_vdc()
                    reply = broker.create_nodes()
        elif body['method'] == 'PUT':
            if ovdc_info_request:
                reply = broker_manager.invoke(Operation.ENABLE_OVDC)
            elif system_request:
                reply = service.update_status(req_headers, req_spec)
            else:
                req_spec.update({'cluster_name': cluster_name})
                reply = broker_manager.invoke(Operation.RESIZE_CLUSTER)
        elif body['method'] == 'DELETE':
            if node_request:
                broker = broker_manager.get_broker_based_on_vdc()
                reply = broker.delete_nodes()
            else:
                req_spec.update({'cluster_name': cluster_name})
                reply = broker_manager.invoke(Operation.DELETE_CLUSTER)

        LOGGER.debug(f"reply: {str(reply)}")
        return reply
def execute_script_in_nodes(vapp,
                            node_names,
                            script,
                            check_tools=True,
                            wait=True):
    all_results = []
    sys_admin_client = None
    try:
        sys_admin_client = vcd_utils.get_sys_admin_client()
        for node_name in node_names:
            LOGGER.debug(f"will try to execute script on {node_name}:\n"
                         f"{script}")

            vs = vs_utils.get_vsphere(sys_admin_client,
                                      vapp,
                                      vm_name=node_name,
                                      logger=LOGGER)
            vs.connect()
            moid = vapp.get_vm_moid(node_name)
            vm = vs.get_vm_by_moid(moid)
            password = vapp.get_admin_password(node_name)
            if check_tools:
                LOGGER.debug(f"waiting for tools on {node_name}")
                vs.wait_until_tools_ready(
                    vm, sleep=5, callback=_wait_for_tools_ready_callback)
                _wait_until_ready_to_exec(vs, vm, password)
            LOGGER.debug(f"about to execute script on {node_name} "
                         f"(vm={vm}), wait={wait}")
            if wait:
                result = \
                    vs.execute_script_in_guest(
                        vm, 'root', password, script,
                        target_file=None,
                        wait_for_completion=True,
                        wait_time=10,
                        get_output=True,
                        delete_script=True,
                        callback=_wait_for_guest_execution_callback)
                result_stdout = result[1].content.decode()
                result_stderr = result[2].content.decode()
            else:
                result = [
                    vs.execute_program_in_guest(vm,
                                                'root',
                                                password,
                                                script,
                                                wait_for_completion=False,
                                                get_output=False)
                ]
                result_stdout = ''
                result_stderr = ''
            LOGGER.debug(result[0])
            LOGGER.debug(result_stderr)
            LOGGER.debug(result_stdout)
            all_results.append(result)
    finally:
        if sys_admin_client:
            sys_admin_client.logout()

    return all_results
def _wait_for_guest_execution_callback(message, exception=None):
    LOGGER.debug(message)
    if exception is not None:
        LOGGER.error(f"exception: {str(exception)}")
def _wait_for_tools_ready_callback(message, exception=None):
    LOGGER.debug(f"waiting for guest tools, status: {message}")
    if exception is not None:
        LOGGER.error(f"exception: {str(exception)}")
Exemplo n.º 16
0
 def on_bindok(self, unused_frame):
     LOGGER.debug('Queue bound')
     self.start_consuming()
Exemplo n.º 17
0
 def start_consuming(self):
     LOGGER.debug('Issuing consumer related RPC commands')
     self.add_on_cancel_callback()
     self._consumer_tag = self._channel.basic_consume(
         self.on_message, self.queue)
Exemplo n.º 18
0
 def on_queue_declareok(self, method_frame):
     LOGGER.debug(f"Binding {self.exchange} to {self.queue} with "
                  f"{self.routing_key}")
     self._channel.queue_bind(self.on_bindok, self.queue, self.exchange,
                              self.routing_key)
Exemplo n.º 19
0
 def on_consumer_cancelled(self, method_frame):
     LOGGER.debug('Consumer was cancelled remotely, shutting down: %r',
                  method_frame)
     if self._channel:
         self._channel.close()
    def _process_template_compute_policy_compliance(self,
                                                    msg_update_callback=None):
        msg = "Processing compute policy for k8s templates."
        LOGGER.info(msg)
        if msg_update_callback:
            msg_update_callback.general_no_color(msg)

        log_filename = None
        log_wire = str_to_bool(self.config['service'].get('log_wire'))
        if log_wire:
            log_filename = SERVER_DEBUG_WIRELOG_FILEPATH

        org_name = self.config['broker']['org']
        catalog_name = self.config['broker']['catalog']
        api_version = self.config['vcd']['api_version']
        client = None
        try:
            if float(api_version) >= float(
                    ApiVersion.VERSION_32.value):  # noqa: E501
                # TODO this api version 32 client should be removed once
                # vcd can handle cp removal/replacement on version 33
                client = Client(self.config['vcd']['host'],
                                api_version=ApiVersion.VERSION_32.value,
                                verify_ssl_certs=self.config['vcd']['verify'],
                                log_file=log_filename,
                                log_requests=log_wire,
                                log_headers=log_wire,
                                log_bodies=log_wire)
            else:
                client = Client(self.config['vcd']['host'],
                                api_version=api_version,
                                verify_ssl_certs=self.config['vcd']['verify'],
                                log_file=log_filename,
                                log_requests=log_wire,
                                log_headers=log_wire,
                                log_bodies=log_wire)

            credentials = BasicLoginCredentials(self.config['vcd']['username'],
                                                SYSTEM_ORG_NAME,
                                                self.config['vcd']['password'])
            client.set_credentials(credentials)
            cpm = ComputePolicyManager(client)

            try:
                for template in self.config['broker']['templates']:
                    policy_name = template[LocalTemplateKey.COMPUTE_POLICY]
                    catalog_item_name = template[
                        LocalTemplateKey.CATALOG_ITEM_NAME]  # noqa: E501
                    # if policy name is not empty, stamp it on the template
                    if policy_name:
                        policy = cpm.get_policy(policy_name=policy_name)
                        # create the policy if not present in system
                        if not policy:
                            msg = "Creating missing compute policy " \
                                f"'{policy_name}'."
                            if msg_update_callback:
                                msg_update_callback.info(msg)
                            LOGGER.debug(msg)
                            policy = cpm.add_policy(policy_name=policy_name)

                        msg = f"Assigning compute policy '{policy_name}' to " \
                              f"template '{catalog_item_name}'."
                        if msg_update_callback:
                            msg_update_callback.general(msg)
                        LOGGER.debug(msg)
                        cpm.assign_compute_policy_to_vapp_template_vms(
                            compute_policy_href=policy['href'],
                            org_name=org_name,
                            catalog_name=catalog_name,
                            catalog_item_name=catalog_item_name)
                    else:
                        # empty policy name means we should remove policy from
                        # template
                        msg = f"Removing compute policy from template " \
                              f"'{catalog_item_name}'."
                        if msg_update_callback:
                            msg_update_callback.general(msg)
                        LOGGER.debug(msg)

                        cpm.remove_all_compute_policies_from_vapp_template_vms(
                            org_name=org_name,
                            catalog_name=catalog_name,
                            catalog_item_name=catalog_item_name)
            except OperationNotSupportedException:
                msg = "Compute policy not supported by vCD. Skipping " \
                    "assigning/removing it to/from templates."
                if msg_update_callback:
                    msg_update_callback.info(msg)
                LOGGER.debug(msg)
        finally:
            if client:
                client.logout()
Exemplo n.º 21
0
 def on_cancelok(self, unused_frame):
     LOGGER.debug('RabbitMQ acknowledged the cancellation'
                  'of the consumer')
     self.close_channel()
    def create_nodes_thread(self):
        LOGGER.debug(f"About to add nodes to cluster with name: "
                     f"{self.cluster_name}")
        try:
            server_config = get_server_runtime_config()
            org_resource = self.tenant_client.get_org()
            org = Org(self.tenant_client, resource=org_resource)
            vdc = VDC(self.tenant_client, href=self.cluster['vdc_href'])
            vapp = VApp(self.tenant_client, href=self.cluster['vapp_href'])
            template = self._get_template()
            self._update_task(
                TaskStatus.RUNNING,
                message=f"Creating {self.req_spec.get(RequestKey.NUM_WORKERS)}"
                        f" node(s) for {self.cluster_name}({self.cluster_id})")

            node_type = NodeType.WORKER
            if self.req_spec.get(RequestKey.ENABLE_NFS):
                node_type = NodeType.NFS

            new_nodes = add_nodes(self.req_spec.get(RequestKey.NUM_WORKERS),
                                  template, node_type, server_config,
                                  self.tenant_client, org, vdc, vapp,
                                  self.req_spec)
            if node_type == NodeType.NFS:
                self._update_task(
                    TaskStatus.SUCCESS,
                    message=f"Created "
                            f"{self.req_spec.get(RequestKey.NUM_WORKERS)} "
                            f"node(s) for "
                            f"{self.cluster_name}({self.cluster_id})")
            elif node_type == NodeType.WORKER:
                self._update_task(
                    TaskStatus.RUNNING,
                    message=f"Adding "
                            f"{self.req_spec.get(RequestKey.NUM_WORKERS)} "
                            f"node(s) to cluster "
                            f"{self.cluster_name}({self.cluster_id})")
                target_nodes = []
                for spec in new_nodes['specs']:
                    target_nodes.append(spec['target_vm_name'])
                vapp.reload()
                join_cluster(server_config, vapp, template, target_nodes)
                self._update_task(
                    TaskStatus.SUCCESS,
                    message=f"Added "
                            f"{self.req_spec.get(RequestKey.NUM_WORKERS)} "
                            f"node(s) to cluster "
                            f"{self.cluster_name}({self.cluster_id})")
        except NodeCreationError as e:
            error_obj = error_to_json(e)
            LOGGER.error(traceback.format_exc())
            stack_trace = \
                ''.join(error_obj[ERROR_MESSAGE_KEY][ERROR_STACKTRACE_KEY])
            self._update_task(
                TaskStatus.ERROR,
                error_message=error_obj[ERROR_MESSAGE_KEY][ERROR_DESCRIPTION_KEY], # noqa: E501
                stack_trace=stack_trace)
            raise
        except Exception as e:
            error_obj = error_to_json(e)
            LOGGER.error(traceback.format_exc())
            stack_trace = \
                ''.join(error_obj[ERROR_MESSAGE_KEY][ERROR_STACKTRACE_KEY])
            self._update_task(
                TaskStatus.ERROR,
                error_message=error_obj[ERROR_MESSAGE_KEY][ERROR_DESCRIPTION_KEY], # noqa: E501
                stack_trace=stack_trace)
        finally:
            self._disconnect_sys_admin()
Exemplo n.º 23
0
 def on_connection_open(self, unused_connection):
     LOGGER.debug('Connection opened')
     self.add_on_connection_close_callback()
     self.open_channel()
Exemplo n.º 24
0
 def add_on_channel_close_callback(self):
     LOGGER.debug('Adding channel close callback')
     self._channel.add_on_close_callback(self.on_channel_closed)
Exemplo n.º 25
0
 def open_channel(self):
     LOGGER.debug('Creating a new channel')
     self._connection.channel(on_open_callback=self.on_channel_open)
Exemplo n.º 26
0
 def on_exchange_declareok(self, unused_frame):
     LOGGER.debug('Exchange declared: %s' % unused_frame)
     self.setup_queue(self.queue)
    def process_request(self, body):
        LOGGER.debug('body: %s' % json.dumps(body))
        reply = {}
        tokens = body['requestUri'].split('/')
        cluster_name = None
        node_name = None
        spec_request = False
        config_request = False
        template_request = False
        node_request = False
        cluster_info_request = False
        node_info_request = False
        system_request = False
        ovdc_request = False
        ovdc_id = None
        ovdc_info_request = False

        if len(tokens) > 3:
            if tokens[3] in ['swagger', 'swagger.json', 'swagger.yaml']:
                spec_request = True
            elif tokens[3] == 'template':
                template_request = True
            elif tokens[3] == 'system':
                system_request = True
            elif tokens[3] == 'ovdc':
                ovdc_request = True
            elif tokens[3] != '':
                cluster_name = tokens[3]
        if len(tokens) > 4:
            if cluster_name is not None:
                if tokens[4] == 'config':
                    config_request = True
                elif tokens[4] == 'info':
                    cluster_info_request = True
                elif tokens[4] == 'node':
                    node_request = True
                elif tokens[4] != '':
                    node_name = tokens[4]
            elif ovdc_request:
                ovdc_id = tokens[4]

        if len(tokens) > 5:
            if node_name is not None:
                if tokens[5] == 'info':
                    node_info_request = True
            elif ovdc_request:
                if tokens[5] == 'info':
                    ovdc_info_request = True
        if len(body['body']) > 0:
            try:
                request_body = json.loads(
                    base64.b64decode(body['body']).decode(
                        sys.getfilesystemencoding()))
            except Exception:
                LOGGER.error(traceback.format_exc())
                request_body = None
        else:
            request_body = None
        LOGGER.debug('request body: %s' % json.dumps(request_body))

        from container_service_extension.service import Service
        service = Service()
        if not system_request and not service.is_enabled:
            raise CseServerError('CSE service is disabled. '
                                 'Contact the System Administrator.')

        if body['method'] == 'GET':
            if ovdc_info_request:
                on_the_fly_request_body = {'ovdc_id': ovdc_id}
                broker = get_new_broker(body['headers'],
                                        on_the_fly_request_body)
                reply = broker.ovdc_info_for_kubernetes()

            elif spec_request:
                reply = self.get_spec(tokens[3])
            elif config_request:
                broker = get_new_broker(body['headers'], request_body)
                reply = broker.get_cluster_config(cluster_name)
            elif template_request:
                result = {}
                templates = []
                server_config = get_server_runtime_config()
                default_template_name = \
                    server_config['broker']['default_template']
                for t in server_config['broker']['templates']:
                    is_default = t['name'] == default_template_name
                    templates.append({
                        'name':
                        t['name'],
                        'is_default':
                        is_default,
                        'catalog':
                        server_config['broker']['catalog'],
                        'catalog_item':
                        t['catalog_item'],
                        'description':
                        t['description']
                    })
                result['body'] = templates
                result['status_code'] = 200
                reply = result
            elif cluster_info_request:
                broker = get_new_broker(body['headers'], request_body)
                reply = broker.get_cluster_info(cluster_name)
            elif node_info_request:
                broker = get_new_broker(body['headers'], request_body)
                reply = broker.get_node_info(cluster_name, node_name)
            elif system_request:
                result = {}
                result['body'] = service.info(body['headers'])
                result['status_code'] = OK
                reply = result
            elif cluster_name is None:
                broker = get_new_broker(body['headers'], request_body)
                reply = broker.list_clusters()
        elif body['method'] == 'POST':
            if cluster_name is None:
                broker = get_new_broker(body['headers'], request_body)
                reply = broker.create_cluster()
            else:
                if node_request:
                    broker = get_new_broker(body['headers'], request_body)
                    reply = broker.create_nodes()
        elif body['method'] == 'PUT':
            if ovdc_info_request:
                broker = get_new_broker(body['headers'], request_body)
                reply = broker.enable_ovdc_for_kubernetes()
            elif system_request:
                reply = service.update_status(body['headers'], request_body)
        elif body['method'] == 'DELETE':
            if node_request:
                broker = get_new_broker(body['headers'], request_body)
                reply = broker.delete_nodes()
            else:
                on_the_fly_request_body = {'name': cluster_name}
                broker = get_new_broker(body['headers'],
                                        on_the_fly_request_body)
                reply = broker.delete_cluster()

        LOGGER.debug('reply: %s' % str(reply))
        return reply
Exemplo n.º 28
0
 def setup_queue(self, queue_name):
     LOGGER.debug('Declaring queue %s', queue_name)
     self._channel.queue_declare(self.on_queue_declareok, queue_name)
Exemplo n.º 29
0
def process_request(body):
    from container_service_extension.service import Service
    LOGGER.debug(f"Incoming request body: {json.dumps(body)}")

    url_data = _get_url_data(body['method'], body['requestUri'])
    operation = url_data[_OPERATION_KEY]

    # check if server is disabled
    if operation not in (CseOperation.SYSTEM_INFO, CseOperation.SYSTEM_UPDATE)\
            and not Service().is_running():
        raise e.BadRequestError(error_message='CSE service is disabled. '
                                'Contact the System Administrator.')

    # create request data dict from request body data
    request_data = {}
    request_body = None
    if len(body['body']) > 0:
        raw_body = base64.b64decode(body['body']).decode(
            sys.getfilesystemencoding())  # noqa: E501
        request_body = json.loads(raw_body)
        request_data.update(request_body)
        LOGGER.debug(f"request body: {request_data}")
    # update request data dict with query params data
    query_params = None
    if body['queryString']:
        query_params = dict(parse_qsl(body['queryString']))
        request_data.update(query_params)
        LOGGER.debug(f"query parameters: {query_params}")
    # update request spec with operation specific data in the url
    request_data.update(url_data)
    # remove None values from request payload
    data = {k: v for k, v in request_data.items() if v is not None}

    # extract out the authorization token
    tenant_auth_token = body['headers'].get('x-vcloud-authorization')
    is_jwt_token = False
    auth_header = body['headers'].get('Authorization')
    if auth_header:
        tokens = auth_header.split(" ")
        if len(tokens) == 2 and tokens[0].lower() == 'bearer':
            tenant_auth_token = tokens[1]
            is_jwt_token = True

    # process the request
    context = ctx.RequestContext(tenant_auth_token,
                                 is_jwt=is_jwt_token,
                                 request_body=request_body,
                                 request_url_data=url_data,
                                 request_query_params=query_params,
                                 request_id=body['id'])

    is_def_request = def_utils.is_def_supported_by_cse_server(
    ) and _is_def_endpoint(body['requestUri'])  # noqa: E501

    try:
        if is_def_request:
            body_content = def_handler.OPERATION_TO_METHOD[operation](
                context)  # noqa: E501
        else:
            body_content = OPERATION_TO_HANDLER[operation](data, context)
    finally:
        if not context.is_async:
            context.end()

    if not isinstance(body_content, (list, dict)):
        body_content = {RESPONSE_MESSAGE_KEY: str(body_content)}
    response = {
        'status_code': operation.ideal_response_code,
        'body': body_content,
    }
    LOGGER.debug(f"Outgoing response: {str(response)}")
    return response
Exemplo n.º 30
0
 def on_queue_declareok(self, method_frame):
     LOGGER.debug('Binding %s to %s with %s', self.exchange, self.queue,
                  self.routing_key)
     self._channel.queue_bind(self.on_bindok, self.queue, self.exchange,
                              self.routing_key)