示例#1
0
    def update_l7rule(self, original_l7rule, l7rule_updates):
        """Updates an L7 rule.

        :param l7rule: Origin dict of the l7rule to update
        :param l7rule_updates: Dict containing updated l7rule attributes
        :returns: None
        :raises L7RuleNotFound: The referenced l7rule was not found
        """
        db_l7policy = self._l7policy_repo.get(
            db_apis.get_session(), id=original_l7rule[constants.L7POLICY_ID])
        load_balancer = db_l7policy.listener.load_balancer

        listeners_dicts = (
            provider_utils.db_listeners_to_provider_dicts_list_of_dicts(
                [db_l7policy.listener]))
        l7policy_dict = provider_utils.db_l7policy_to_provider_l7policy(
            db_l7policy)

        update_l7rule_tf = self._taskflow_load(
            self._l7rule_flows.get_update_l7rule_flow(),
            store={
                constants.L7RULE: original_l7rule,
                constants.L7POLICY: l7policy_dict.to_dict(),
                constants.LISTENERS: listeners_dicts,
                constants.L7POLICY_ID: db_l7policy.id,
                constants.LOADBALANCER_ID: load_balancer.id,
                constants.UPDATE_DICT: l7rule_updates
            })
        with tf_logging.DynamicLoggingListener(update_l7rule_tf, log=LOG):
            update_l7rule_tf.run()
示例#2
0
    def create_l7rule(self, l7rule):
        """Creates an L7 Rule.

        :param l7rule: Provider dict l7rule
        :returns: None
        :raises NoResultFound: Unable to find the object
        """
        db_l7policy = self._l7policy_repo.get(db_apis.get_session(),
                                              id=l7rule[constants.L7POLICY_ID])

        load_balancer = db_l7policy.listener.load_balancer

        listeners_dicts = (
            provider_utils.db_listeners_to_provider_dicts_list_of_dicts(
                [db_l7policy.listener]))
        l7policy_dict = provider_utils.db_l7policy_to_provider_l7policy(
            db_l7policy)

        create_l7rule_tf = self._taskflow_load(
            self._l7rule_flows.get_create_l7rule_flow(),
            store={
                constants.L7RULE: l7rule,
                constants.L7POLICY: l7policy_dict.to_dict(),
                constants.LISTENERS: listeners_dicts,
                constants.L7POLICY_ID: db_l7policy.id,
                constants.LOADBALANCER_ID: load_balancer.id
            })
        with tf_logging.DynamicLoggingListener(create_l7rule_tf, log=LOG):
            create_l7rule_tf.run()
示例#3
0
    def delete_l7rule(self, l7rule):
        """Deletes an L7 rule.

        :param l7rule: Provider dict of the l7rule to delete
        :returns: None
        :raises L7RuleNotFound: The referenced l7rule was not found
        """
        db_l7policy = self._l7policy_repo.get(db_apis.get_session(),
                                              id=l7rule[constants.L7POLICY_ID])
        l7policy = provider_utils.db_l7policy_to_provider_l7policy(db_l7policy)
        load_balancer = db_l7policy.listener.load_balancer

        listeners_dicts = (
            provider_utils.db_listeners_to_provider_dicts_list_of_dicts(
                [db_l7policy.listener]))

        delete_l7rule_tf = self._taskflow_load(
            self._l7rule_flows.get_delete_l7rule_flow(),
            store={
                constants.L7RULE: l7rule,
                constants.L7POLICY: l7policy.to_dict(),
                constants.LISTENERS: listeners_dicts,
                constants.L7POLICY_ID: db_l7policy.id,
                constants.LOADBALANCER_ID: load_balancer.id
            })
        with tf_logging.DynamicLoggingListener(delete_l7rule_tf, log=LOG):
            delete_l7rule_tf.run()
示例#4
0
    def delete_l7rule(self, l7rule):
        """Deletes an L7 rule.

        :param l7rule: Provider dict of the l7rule to delete
        :returns: None
        :raises L7RuleNotFound: The referenced l7rule was not found
        """
        db_l7policy = self._l7policy_repo.get(db_apis.get_session(),
                                              id=l7rule[constants.L7POLICY_ID])
        l7policy = provider_utils.db_l7policy_to_provider_l7policy(db_l7policy)
        load_balancer = db_l7policy.listener.load_balancer

        listeners_dicts = (
            provider_utils.db_listeners_to_provider_dicts_list_of_dicts(
                [db_l7policy.listener]))

        store = {
            constants.L7RULE: l7rule,
            constants.L7POLICY: l7policy.to_dict(),
            constants.LISTENERS: listeners_dicts,
            constants.L7POLICY_ID: db_l7policy.id,
            constants.LOADBALANCER_ID: load_balancer.id
        }
        self.services_controller.run_poster(flow_utils.get_delete_l7rule_flow,
                                            store=store)
示例#5
0
    def delete(self, id):
        """Deletes a l7policy."""
        context = pecan_request.context.get('octavia_context')
        db_l7policy = self._get_db_l7policy(context.session,
                                            id,
                                            show_deleted=False)
        load_balancer_id, listener_id = self._get_listener_and_loadbalancer_id(
            db_l7policy)
        project_id, provider = self._get_lb_project_id_provider(
            context.session, load_balancer_id)

        self._auth_validate_action(context, project_id, constants.RBAC_DELETE)

        if db_l7policy.provisioning_status == constants.DELETED:
            return

        # Load the driver early as it also provides validation
        driver = driver_factory.get_driver(provider)

        with db_api.get_lock_session() as lock_session:

            self._test_lb_and_listener_statuses(lock_session,
                                                lb_id=load_balancer_id,
                                                listener_ids=[listener_id])
            self.repositories.l7policy.update(
                lock_session,
                db_l7policy.id,
                provisioning_status=constants.PENDING_DELETE)

            LOG.info("Sending delete L7 Policy %s to provider %s", id,
                     driver.name)
            provider_l7policy = driver_utils.db_l7policy_to_provider_l7policy(
                db_l7policy)
            driver_utils.call_provider(driver.name, driver.l7policy_delete,
                                       provider_l7policy)
示例#6
0
def process_get(get_data):
    session = db_api.get_session()

    if get_data[constants.OBJECT] == lib_consts.LOADBALANCERS:
        lb_repo = repositories.LoadBalancerRepository()
        db_lb = lb_repo.get(session, id=get_data[lib_consts.ID],
                            show_deleted=False)
        if db_lb:
            provider_lb = (
                driver_utils.db_loadbalancer_to_provider_loadbalancer(db_lb))
            return provider_lb.to_dict(recurse=True, render_unsets=True)
    elif get_data[constants.OBJECT] == lib_consts.LISTENERS:
        listener_repo = repositories.ListenerRepository()
        db_listener = listener_repo.get(
            session, id=get_data[lib_consts.ID], show_deleted=False)
        if db_listener:
            provider_listener = (
                driver_utils.db_listener_to_provider_listener(db_listener))
            return provider_listener.to_dict(recurse=True, render_unsets=True)
    elif get_data[constants.OBJECT] == lib_consts.POOLS:
        pool_repo = repositories.PoolRepository()
        db_pool = pool_repo.get(session, id=get_data[lib_consts.ID],
                                show_deleted=False)
        if db_pool:
            provider_pool = (
                driver_utils.db_pool_to_provider_pool(db_pool))
            return provider_pool.to_dict(recurse=True, render_unsets=True)
    elif get_data[constants.OBJECT] == lib_consts.MEMBERS:
        member_repo = repositories.MemberRepository()
        db_member = member_repo.get(session, id=get_data[lib_consts.ID],
                                    show_deleted=False)
        if db_member:
            provider_member = (
                driver_utils.db_member_to_provider_member(db_member))
            return provider_member.to_dict(recurse=True, render_unsets=True)
    elif get_data[constants.OBJECT] == lib_consts.HEALTHMONITORS:
        hm_repo = repositories.HealthMonitorRepository()
        db_hm = hm_repo.get(session, id=get_data[lib_consts.ID],
                            show_deleted=False)
        if db_hm:
            provider_hm = (
                driver_utils.db_HM_to_provider_HM(db_hm))
            return provider_hm.to_dict(recurse=True, render_unsets=True)
    elif get_data[constants.OBJECT] == lib_consts.L7POLICIES:
        l7policy_repo = repositories.L7PolicyRepository()
        db_l7policy = l7policy_repo.get(session, id=get_data[lib_consts.ID],
                                        show_deleted=False)
        if db_l7policy:
            provider_l7policy = (
                driver_utils.db_l7policy_to_provider_l7policy(db_l7policy))
            return provider_l7policy.to_dict(recurse=True, render_unsets=True)
    elif get_data[constants.OBJECT] == lib_consts.L7RULES:
        l7rule_repo = repositories.L7RuleRepository()
        db_l7rule = l7rule_repo.get(session, id=get_data[lib_consts.ID],
                                    show_deleted=False)
        if db_l7rule:
            provider_l7rule = (
                driver_utils.db_l7rule_to_provider_l7rule(db_l7rule))
            return provider_l7rule.to_dict(recurse=True, render_unsets=True)
    return {}
示例#7
0
    def create_l7rule(self, l7rule):
        """Creates an L7 Rule.

        :param l7rule: Provider dict l7rule
        :returns: None
        :raises NoResultFound: Unable to find the object
        """
        db_l7policy = self._l7policy_repo.get(db_apis.get_session(),
                                              id=l7rule[constants.L7POLICY_ID])

        load_balancer = db_l7policy.listener.load_balancer

        listeners_dicts = (
            provider_utils.db_listeners_to_provider_dicts_list_of_dicts(
                [db_l7policy.listener]))
        l7policy_dict = provider_utils.db_l7policy_to_provider_l7policy(
            db_l7policy)

        store = {
            constants.L7RULE: l7rule,
            constants.L7POLICY: l7policy_dict.to_dict(),
            constants.L7POLICY_ID: db_l7policy.id,
            constants.LISTENERS: listeners_dicts,
            constants.LOADBALANCER_ID: load_balancer.id
        }
        self.services_controller.run_poster(flow_utils.get_create_l7rule_flow,
                                            store=store)
示例#8
0
    def delete(self, id):
        """Deletes a l7policy."""
        context = pecan.request.context.get('octavia_context')
        db_l7policy = self._get_db_l7policy(context.session, id,
                                            show_deleted=False)
        load_balancer_id, listener_id = self._get_listener_and_loadbalancer_id(
            db_l7policy)
        project_id, provider = self._get_lb_project_id_provider(
            context.session, load_balancer_id)

        self._auth_validate_action(context, project_id, constants.RBAC_DELETE)

        if db_l7policy.provisioning_status == constants.DELETED:
            return

        # Load the driver early as it also provides validation
        driver = driver_factory.get_driver(provider)

        with db_api.get_lock_session() as lock_session:

            self._test_lb_and_listener_statuses(lock_session,
                                                lb_id=load_balancer_id,
                                                listener_ids=[listener_id])
            self.repositories.l7policy.update(
                lock_session, db_l7policy.id,
                provisioning_status=constants.PENDING_DELETE)

            LOG.info("Sending delete L7 Policy %s to provider %s",
                     id, driver.name)
            provider_l7policy = driver_utils.db_l7policy_to_provider_l7policy(
                db_l7policy)
            driver_utils.call_provider(driver.name, driver.l7policy_delete,
                                       provider_l7policy)
示例#9
0
    def post(self, l7policy_):
        """Creates a l7policy on a listener."""
        l7policy = l7policy_.l7policy
        context = pecan.request.context.get('octavia_context')
        # Make sure any pool specified by redirect_pool_id exists
        if l7policy.redirect_pool_id:
            db_pool = self._get_db_pool(context.session,
                                        l7policy.redirect_pool_id)
            self._escape_l7policy_udp_pool_request(db_pool)
        # Verify the parent listener exists
        listener_id = l7policy.listener_id
        listener = self._get_db_listener(context.session, listener_id)
        load_balancer_id = listener.load_balancer_id
        l7policy.project_id, provider = self._get_lb_project_id_provider(
            context.session, load_balancer_id)

        self._auth_validate_action(context, l7policy.project_id,
                                   constants.RBAC_POST)

        # Load the driver early as it also provides validation
        driver = driver_factory.get_driver(provider)

        lock_session = db_api.get_session(autocommit=False)
        try:
            if self.repositories.check_quota_met(context.session, lock_session,
                                                 data_models.L7Policy,
                                                 l7policy.project_id):
                raise exceptions.QuotaException(
                    resource=data_models.L7Policy._name())

            l7policy_dict = db_prepare.create_l7policy(
                l7policy.to_dict(render_unsets=True), load_balancer_id,
                listener_id)

            self._test_lb_and_listener_statuses(lock_session,
                                                lb_id=load_balancer_id,
                                                listener_ids=[listener_id])
            db_l7policy = self._validate_create_l7policy(
                lock_session, l7policy_dict)

            # Prepare the data for the driver data model
            provider_l7policy = (
                driver_utils.db_l7policy_to_provider_l7policy(db_l7policy))

            # Dispatch to the driver
            LOG.info("Sending create L7 Policy %s to provider %s",
                     db_l7policy.id, driver.name)
            driver_utils.call_provider(driver.name, driver.l7policy_create,
                                       provider_l7policy)

            lock_session.commit()
        except Exception:
            with excutils.save_and_reraise_exception():
                lock_session.rollback()

        db_l7policy = self._get_db_l7policy(context.session, db_l7policy.id)
        result = self._convert_db_to_type(db_l7policy,
                                          l7policy_types.L7PolicyResponse)
        return l7policy_types.L7PolicyRootResponse(l7policy=result)
示例#10
0
    def put(self, id, l7policy_):
        """Updates a l7policy."""
        l7policy = l7policy_.l7policy
        context = pecan_request.context.get('octavia_context')
        db_l7policy = self._get_db_l7policy(context.session,
                                            id,
                                            show_deleted=False)
        load_balancer_id, listener_id = self._get_listener_and_loadbalancer_id(
            db_l7policy)
        project_id, provider = self._get_lb_project_id_provider(
            context.session, load_balancer_id)

        self._auth_validate_action(context, project_id, constants.RBAC_PUT)

        l7policy_dict = validate.sanitize_l7policy_api_args(
            l7policy.to_dict(render_unsets=False))
        # Reset renamed attributes
        for attr, val in l7policy_types.L7PolicyPUT._type_to_model_map.items():
            if val in l7policy_dict:
                l7policy_dict[attr] = l7policy_dict.pop(val)
        sanitized_l7policy = l7policy_types.L7PolicyPUT(**l7policy_dict)

        listener = self._get_db_listener(context.session,
                                         db_l7policy.listener_id)
        # Make sure any specified redirect_pool_id exists
        if l7policy_dict.get('redirect_pool_id'):
            db_pool = self._get_db_pool(context.session,
                                        l7policy_dict['redirect_pool_id'])
            self._validate_protocol(listener.protocol, db_pool.protocol)

        # Load the driver early as it also provides validation
        driver = driver_factory.get_driver(provider)

        with db_api.get_lock_session() as lock_session:

            self._test_lb_and_listener_statuses(lock_session,
                                                lb_id=load_balancer_id,
                                                listener_ids=[listener_id])

            # Prepare the data for the driver data model
            l7policy_dict = sanitized_l7policy.to_dict(render_unsets=False)
            l7policy_dict['id'] = id
            provider_l7policy_dict = (
                driver_utils.l7policy_dict_to_provider_dict(l7policy_dict))

            # Also prepare the baseline object data
            old_provider_l7policy = (
                driver_utils.db_l7policy_to_provider_l7policy(db_l7policy))

            # Dispatch to the driver
            LOG.info("Sending update L7 Policy %s to provider %s", id,
                     driver.name)
            driver_utils.call_provider(
                driver.name, driver.l7policy_update, old_provider_l7policy,
                driver_dm.L7Policy.from_dict(provider_l7policy_dict))

            # Update the database to reflect what the driver just accepted
            sanitized_l7policy.provisioning_status = constants.PENDING_UPDATE
            db_l7policy_dict = sanitized_l7policy.to_dict(render_unsets=False)
            self.repositories.l7policy.update(lock_session, id,
                                              **db_l7policy_dict)

        # Force SQL alchemy to query the DB, otherwise we get inconsistent
        # results
        context.session.expire_all()
        db_l7policy = self._get_db_l7policy(context.session, id)
        result = self._convert_db_to_type(db_l7policy,
                                          l7policy_types.L7PolicyResponse)
        return l7policy_types.L7PolicyRootResponse(l7policy=result)
示例#11
0
    def obj_to_dict(self, obj, is_update=False, project_id=None):
        obj_type = obj.__class__.__name__
        # create a dictionary out of the object
        render_unsets = False if is_update else True
        obj_dict = obj.to_dict(recurse=True, render_unsets=render_unsets)

        # Update the dictionary to match what the nsx driver expects
        if not project_id:
            project_id = self.get_obj_project_id(obj_type, obj_dict)
        obj_dict['tenant_id'] = obj_dict['project_id'] = project_id

        if 'id' not in obj_dict:
            obj_dict['id'] = obj_dict.get('%s_id' % obj_type.lower())

        if not obj_dict.get('name') and not is_update:
            obj_dict['name'] = ""

        self._remove_unsupported_keys(obj_type, obj_dict)

        if obj_type == 'LoadBalancer':
            # clean listeners and pools for update case:
            if 'listeners' in obj_dict:
                if is_update and not obj_dict['listeners']:
                    del obj_dict['listeners']
                else:
                    if obj_dict['listeners'] is None:
                        obj_dict['listeners'] = []
                    for listener in obj_dict['listeners']:
                        listener['id'] = listener['listener_id']
            if 'pools' in obj_dict:
                if is_update and not obj_dict['pools']:
                    del obj_dict['pools']
                else:
                    if obj_dict['pools'] is None:
                        obj_dict['pools'] = []
                    for pool in obj_dict['pools']:
                        pool['id'] = pool['pool_id']

        elif obj_type == 'Listener':
            if 'l7policies' in obj_dict:
                obj_dict['l7_policies'] = obj_dict['l7policies']
            if obj_dict.get('loadbalancer_id'):
                # Generate a loadbalancer object
                obj_dict['loadbalancer'] = self._get_load_balancer_dict(
                    obj_dict['loadbalancer_id'])
            # TODO(asarfaty): add default_tls_container_id

        elif obj_type == 'Pool':
            if 'listener' not in obj_dict:
                self._get_listener_in_pool_dict(obj_dict)

        elif obj_type == 'Member':
            # Get the pool object
            if obj_dict.get('pool_id'):
                obj_dict['pool'] = self._get_pool_dict(obj_dict['pool_id'])
                obj_dict['loadbalancer'] = None
                if 'loadbalancer' in obj_dict['pool']:
                    obj_dict['loadbalancer'] = obj_dict['pool']['loadbalancer']
                    if not obj_dict.get('subnet_id'):
                        # Use the parent vip_subnet_id instead
                        obj_dict['subnet_id'] = obj_dict['loadbalancer'][
                            'vip_subnet_id']
            else:
                obj_dict['pool'] = None
                obj_dict['loadbalancer'] = None

        elif obj_type == 'HealthMonitor':
            # Get the pool object
            if obj_dict.get('pool_id'):
                obj_dict['pool'] = self._get_pool_dict(obj_dict['pool_id'])

        elif obj_type == 'L7Policy':
            self.update_policy_dict(obj_dict, obj, is_update=is_update)

        elif obj_type == 'L7Rule':
            # Get the L7 policy object
            if obj_dict.get('l7policy_id'):
                db_policy = self.repositories.l7policy.get(
                    db_apis.get_session(), id=obj_dict['l7policy_id'])
                policy_obj = oct_utils.db_l7policy_to_provider_l7policy(
                    db_policy)
                policy_dict = policy_obj.to_dict(
                    recurse=True, render_unsets=True)
                policy_dict['id'] = obj_dict['l7policy_id']
                self.update_policy_dict(
                    policy_dict, policy_obj, is_update=is_update)
                obj_dict['policy'] = policy_dict

        LOG.debug("Translated %(type)s to dictionary: %(obj)s",
                  {'type': obj_type, 'obj': obj_dict})
        return obj_dict
示例#12
0
    def put(self, id, l7policy_):
        """Updates a l7policy."""
        l7policy = l7policy_.l7policy
        l7policy_dict = validate.sanitize_l7policy_api_args(
            l7policy.to_dict(render_unsets=False))
        # Reset renamed attributes
        for attr, val in l7policy_types.L7PolicyPUT._type_to_model_map.items():
            if val in l7policy_dict:
                l7policy_dict[attr] = l7policy_dict.pop(val)
        sanitized_l7policy = l7policy_types.L7PolicyPUT(**l7policy_dict)
        context = pecan.request.context.get('octavia_context')
        # Make sure any specified redirect_pool_id exists
        if l7policy_dict.get('redirect_pool_id'):
            db_pool = self._get_db_pool(
                context.session, l7policy_dict['redirect_pool_id'])
            self._escape_l7policy_udp_pool_request(db_pool)
        db_l7policy = self._get_db_l7policy(context.session, id,
                                            show_deleted=False)
        load_balancer_id, listener_id = self._get_listener_and_loadbalancer_id(
            db_l7policy)
        project_id, provider = self._get_lb_project_id_provider(
            context.session, load_balancer_id)

        self._auth_validate_action(context, project_id, constants.RBAC_PUT)

        # Load the driver early as it also provides validation
        driver = driver_factory.get_driver(provider)

        with db_api.get_lock_session() as lock_session:

            self._test_lb_and_listener_statuses(lock_session,
                                                lb_id=load_balancer_id,
                                                listener_ids=[listener_id])

            # Prepare the data for the driver data model
            l7policy_dict = sanitized_l7policy.to_dict(render_unsets=False)
            l7policy_dict['id'] = id
            provider_l7policy_dict = (
                driver_utils.l7policy_dict_to_provider_dict(l7policy_dict))

            # Also prepare the baseline object data
            old_provider_l7policy = (
                driver_utils.db_l7policy_to_provider_l7policy(db_l7policy))

            # Dispatch to the driver
            LOG.info("Sending update L7 Policy %s to provider %s",
                     id, driver.name)
            driver_utils.call_provider(
                driver.name, driver.l7policy_update,
                old_provider_l7policy,
                driver_dm.L7Policy.from_dict(provider_l7policy_dict))

            # Update the database to reflect what the driver just accepted
            sanitized_l7policy.provisioning_status = constants.PENDING_UPDATE
            db_l7policy_dict = sanitized_l7policy.to_dict(render_unsets=False)
            self.repositories.l7policy.update(lock_session, id,
                                              **db_l7policy_dict)

        # Force SQL alchemy to query the DB, otherwise we get inconsistent
        # results
        context.session.expire_all()
        db_l7policy = self._get_db_l7policy(context.session, id)
        result = self._convert_db_to_type(db_l7policy,
                                          l7policy_types.L7PolicyResponse)
        return l7policy_types.L7PolicyRootResponse(l7policy=result)
示例#13
0
    def post(self, l7policy_):
        """Creates a l7policy on a listener."""
        l7policy = l7policy_.l7policy
        context = pecan.request.context.get('octavia_context')
        # Make sure any pool specified by redirect_pool_id exists
        if l7policy.redirect_pool_id:
            db_pool = self._get_db_pool(
                context.session, l7policy.redirect_pool_id)
            self._escape_l7policy_udp_pool_request(db_pool)
        # Verify the parent listener exists
        listener_id = l7policy.listener_id
        listener = self._get_db_listener(
            context.session, listener_id)
        load_balancer_id = listener.load_balancer_id
        l7policy.project_id, provider = self._get_lb_project_id_provider(
            context.session, load_balancer_id)

        self._auth_validate_action(context, l7policy.project_id,
                                   constants.RBAC_POST)

        # Load the driver early as it also provides validation
        driver = driver_factory.get_driver(provider)

        lock_session = db_api.get_session(autocommit=False)
        try:
            if self.repositories.check_quota_met(
                    context.session,
                    lock_session,
                    data_models.L7Policy,
                    l7policy.project_id):
                raise exceptions.QuotaException(
                    resource=data_models.L7Policy._name())

            l7policy_dict = db_prepare.create_l7policy(
                l7policy.to_dict(render_unsets=True),
                load_balancer_id, listener_id)

            self._test_lb_and_listener_statuses(
                lock_session, lb_id=load_balancer_id,
                listener_ids=[listener_id])
            db_l7policy = self._validate_create_l7policy(
                lock_session, l7policy_dict)

            # Prepare the data for the driver data model
            provider_l7policy = (
                driver_utils.db_l7policy_to_provider_l7policy(db_l7policy))

            # Dispatch to the driver
            LOG.info("Sending create L7 Policy %s to provider %s",
                     db_l7policy.id, driver.name)
            driver_utils.call_provider(
                driver.name, driver.l7policy_create, provider_l7policy)

            lock_session.commit()
        except Exception:
            with excutils.save_and_reraise_exception():
                lock_session.rollback()

        db_l7policy = self._get_db_l7policy(context.session, db_l7policy.id)
        result = self._convert_db_to_type(db_l7policy,
                                          l7policy_types.L7PolicyResponse)
        return l7policy_types.L7PolicyRootResponse(l7policy=result)
示例#14
0
    def obj_to_dict(self, obj, is_update=False, project_id=None):
        obj_type = obj.__class__.__name__
        # create a dictionary out of the object
        render_unsets = False if is_update else True
        obj_dict = obj.to_dict(recurse=True, render_unsets=render_unsets)

        # Update the dictionary to match what the nsx driver expects
        if not project_id:
            project_id = self.get_obj_project_id(obj_type, obj_dict)
        obj_dict['tenant_id'] = obj_dict['project_id'] = project_id

        if 'id' not in obj_dict:
            obj_dict['id'] = obj_dict.get('%s_id' % obj_type.lower())

        if not obj_dict.get('name') and not is_update:
            obj_dict['name'] = ""

        self._remove_unsupported_keys(obj_type, obj_dict)

        if obj_type == 'LoadBalancer':
            # clean listeners and pools for update case:
            if 'listeners' in obj_dict:
                if is_update and not obj_dict['listeners']:
                    del obj_dict['listeners']
                else:
                    if obj_dict['listeners'] is None:
                        obj_dict['listeners'] = []
                    for listener in obj_dict['listeners']:
                        listener['id'] = listener['listener_id']
                        for policy in listener.get('l7policies', []):
                            policy['id'] = policy['l7policy_id']
                            for rule in policy.get('rules', []):
                                rule['id'] = rule['l7rule_id']
            if 'pools' in obj_dict:
                if is_update and not obj_dict['pools']:
                    del obj_dict['pools']
                else:
                    if obj_dict['pools'] is None:
                        obj_dict['pools'] = []
                    for pool in obj_dict['pools']:
                        pool['id'] = pool['pool_id']
                        for member in pool.get('members', []):
                            member['id'] = member['member_id']
                        if pool.get('healthmonitor'):
                            pool['healthmonitor'] = self._get_hm_dict(
                                pool['healthmonitor']['healthmonitor_id'],
                                is_update)

        elif obj_type == 'Listener':
            if 'l7policies' in obj_dict:
                obj_dict['l7_policies'] = obj_dict['l7policies']
            if obj_dict.get('loadbalancer_id'):
                # Generate a loadbalancer object
                obj_dict['loadbalancer'] = self._get_load_balancer_dict(
                    obj_dict['loadbalancer_id'])
            # TODO(asarfaty): add default_tls_container_id

        elif obj_type == 'Pool':
            if 'listener' not in obj_dict:
                self._get_listener_in_pool_dict(obj_dict, is_update)

        elif obj_type == 'Member':
            # Get the pool object
            if obj_dict.get('pool_id'):
                obj_dict['pool'] = self._get_pool_dict(
                    obj_dict['pool_id'], is_update)
                obj_dict['loadbalancer'] = None
                if 'loadbalancer' in obj_dict['pool']:
                    obj_dict['loadbalancer'] = obj_dict['pool']['loadbalancer']
                    if not obj_dict.get('subnet_id'):
                        # Use the parent vip_subnet_id instead
                        obj_dict['subnet_id'] = obj_dict['loadbalancer'][
                            'vip_subnet_id']
            else:
                obj_dict['pool'] = None
                obj_dict['loadbalancer'] = None

        elif obj_type == 'HealthMonitor':
            # Get the pool object
            if obj_dict.get('pool_id'):
                obj_dict['pool'] = self._get_pool_dict(
                    obj_dict['pool_id'], is_update)

        elif obj_type == 'L7Policy':
            self.update_policy_dict(obj_dict, obj, is_update=is_update)

        elif obj_type == 'L7Rule':
            # Get the L7 policy object
            if obj_dict.get('l7policy_id'):
                db_policy = self.repositories.l7policy.get(
                    db_apis.get_session(), id=obj_dict['l7policy_id'])
                policy_obj = oct_utils.db_l7policy_to_provider_l7policy(
                    db_policy)
                policy_dict = policy_obj.to_dict(
                    recurse=True, render_unsets=True)
                policy_dict['id'] = obj_dict['l7policy_id']
                self.update_policy_dict(
                    policy_dict, policy_obj, is_update=is_update)
                obj_dict['policy'] = policy_dict

        LOG.debug("Translated %(type)s to dictionary: %(obj)s",
                  {'type': obj_type, 'obj': obj_dict})
        return obj_dict