def test_create_tenant_filter(self):
     tenant = mocked.APIC_TENANT
     self.mock_responses_for_create('vzFilter')
     self.mock_responses_for_create('vzEntry')
     filter_id = self.mgr.create_tenant_filter(tenant)
     self.assert_responses_drained()
     self.assertTrue(uuidutils.is_uuid_like(str(filter_id)))
Esempio n. 2
0
def get_sg_ids_grouped_by_port(port_ids):
    sg_ids_grouped_by_port = {}
    session = db_api.get_session()
    sg_binding_port = sg_db.SecurityGroupPortBinding.port_id

    with session.begin(subtransactions=True):
        # partial UUIDs must be individually matched with startswith.
        # full UUIDs may be matched directly in an IN statement
        partial_uuids = set(port_id for port_id in port_ids
                            if not uuidutils.is_uuid_like(port_id))
        full_uuids = set(port_ids) - partial_uuids
        or_criteria = [models_v2.Port.id.startswith(port_id)
                       for port_id in partial_uuids]
        if full_uuids:
            or_criteria.append(models_v2.Port.id.in_(full_uuids))

        query = session.query(models_v2.Port,
                              sg_db.SecurityGroupPortBinding.security_group_id)
        query = query.outerjoin(sg_db.SecurityGroupPortBinding,
                                models_v2.Port.id == sg_binding_port)
        query = query.filter(or_(*or_criteria))

        for port, sg_id in query:
            if port not in sg_ids_grouped_by_port:
                sg_ids_grouped_by_port[port] = []
            if sg_id:
                sg_ids_grouped_by_port[port].append(sg_id)
    return sg_ids_grouped_by_port
Esempio n. 3
0
    def _handler(self, client_sock, client_addr):
        """Handle incoming lease relay stream connection.

        This method will only read the first 1024 bytes and then close the
        connection.  The limit exists to limit the impact of misbehaving
        clients.
        """
        try:
            msg = client_sock.recv(1024)
            data = jsonutils.loads(msg)
            client_sock.close()

            network_id = data['network_id']
            if not uuidutils.is_uuid_like(network_id):
                raise ValueError(
                    _("Network ID %s is not a valid UUID") % network_id)
            ip_address = str(netaddr.IPAddress(data['ip_address']))
            lease_remaining = int(data['lease_remaining'])
            self.callback(network_id, ip_address, lease_remaining)
        except ValueError as e:
            LOG.warn(_('Unable to parse lease relay msg to dict.'))
            LOG.warn(_('Exception value: %s'), e)
            LOG.warn(_('Message representation: %s'), repr(msg))
        except Exception as e:
            LOG.exception(_('Unable update lease. Exception'))
 def test_create_tenant_filter(self):
     tenant = mocked.APIC_TENANT
     self.mock_responses_for_create('vzFilter')
     self.mock_responses_for_create('vzEntry')
     filter_id = self.mgr.create_tenant_filter(tenant)
     self.assert_responses_drained()
     self.assertTrue(uuidutils.is_uuid_like(str(filter_id)))
    def _record_port_status_changed_helper(self, current_port_status,
                                           previous_port_status, port):

        if not (port.device_id and port.id and port.device_owner and
                port.device_owner.startswith('compute:') and
                uuidutils.is_uuid_like(port.device_id)):
            return

        if (previous_port_status == constants.PORT_STATUS_ACTIVE and
                current_port_status == constants.PORT_STATUS_DOWN):
            event_name = nova.VIF_UNPLUGGED

        elif (previous_port_status in [sql_attr.NO_VALUE,
                                       constants.PORT_STATUS_DOWN,
                                       constants.PORT_STATUS_BUILD]
              and current_port_status in [constants.PORT_STATUS_ACTIVE,
                                          constants.PORT_STATUS_ERROR]):
            event_name = nova.VIF_PLUGGED

        else:
            return

        status = nova.NEUTRON_NOVA_EVENT_STATUS_MAP.get(current_port_status)
        self.nova_notifier.record_port_status_changed(port,
                                                      current_port_status,
                                                      previous_port_status,
                                                      None)

        event = {'server_uuid': port.device_id, 'status': status,
                 'name': event_name, 'tag': 'port-uuid'}
        self.assertEqual(event, port._notify_event)
Esempio n. 6
0
    def _handler(self, client_sock, client_addr):
        """Handle incoming lease relay stream connection.

        This method will only read the first 1024 bytes and then close the
        connection.  The limit exists to limit the impact of misbehaving
        clients.
        """
        try:
            msg = client_sock.recv(1024)
            data = jsonutils.loads(msg)
            client_sock.close()

            network_id = data['network_id']
            if not uuidutils.is_uuid_like(network_id):
                raise ValueError(_("Network ID %s is not a valid UUID") %
                                 network_id)
            ip_address = str(netaddr.IPAddress(data['ip_address']))
            lease_remaining = int(data['lease_remaining'])
            self.callback(network_id, ip_address, lease_remaining)
        except ValueError as e:
            LOG.warn(_('Unable to parse lease relay msg to dict.'))
            LOG.warn(_('Exception value: %s'), e)
            LOG.warn(_('Message representation: %s'), repr(msg))
        except Exception as e:
            LOG.exception(_('Unable update lease. Exception'))
Esempio n. 7
0
    def _record_port_status_changed_helper(self, current_port_status,
                                           previous_port_status, port):

        if not (port.device_id and port.id and port.device_owner
                and port.device_owner.startswith('compute:')
                and uuidutils.is_uuid_like(port.device_id)):
            return

        if (previous_port_status == constants.PORT_STATUS_ACTIVE
                and current_port_status == constants.PORT_STATUS_DOWN):
            event_name = nova.VIF_UNPLUGGED

        elif (previous_port_status in [
                sql_attr.NO_VALUE, constants.PORT_STATUS_DOWN,
                constants.PORT_STATUS_BUILD
        ] and current_port_status
              in [constants.PORT_STATUS_ACTIVE, constants.PORT_STATUS_ERROR]):
            event_name = nova.VIF_PLUGGED

        else:
            return

        status = nova.NEUTRON_NOVA_EVENT_STATUS_MAP.get(current_port_status)
        self.nova_notifier.record_port_status_changed(port,
                                                      current_port_status,
                                                      previous_port_status,
                                                      None)

        event = {
            'server_uuid': port.device_id,
            'status': status,
            'name': event_name,
            'tag': 'port-uuid'
        }
        self.assertEqual(event, port._notify_event)
Esempio n. 8
0
def get_sg_ids_grouped_by_port(port_ids):
    sg_ids_grouped_by_port = {}
    session = db_api.get_session()
    sg_binding_port = sg_db.SecurityGroupPortBinding.port_id

    with session.begin(subtransactions=True):
        # partial UUIDs must be individually matched with startswith.
        # full UUIDs may be matched directly in an IN statement
        partial_uuids = set(port_id for port_id in port_ids
                            if not uuidutils.is_uuid_like(port_id))
        full_uuids = set(port_ids) - partial_uuids
        or_criteria = [
            models_v2.Port.id.startswith(port_id) for port_id in partial_uuids
        ]
        if full_uuids:
            or_criteria.append(models_v2.Port.id.in_(full_uuids))

        query = session.query(models_v2.Port,
                              sg_db.SecurityGroupPortBinding.security_group_id)
        query = query.outerjoin(sg_db.SecurityGroupPortBinding,
                                models_v2.Port.id == sg_binding_port)
        query = query.filter(or_(*or_criteria))

        for port, sg_id in query:
            if port not in sg_ids_grouped_by_port:
                sg_ids_grouped_by_port[port] = []
            if sg_id:
                sg_ids_grouped_by_port[port].append(sg_id)
    return sg_ids_grouped_by_port
Esempio n. 9
0
 def process_create_port(self, context, data, result):
     """Implementation of abstract method from ExtensionDriver class."""
     port_id = result.get('id')
     policy_profile_attr = data.get(constants.N1KV_PROFILE)
     if not attributes.is_attr_set(policy_profile_attr):
         policy_profile_attr = (cfg.CONF.ml2_cisco_n1kv.
                                default_policy_profile)
     with context.session.begin(subtransactions=True):
         try:
             n1kv_db.get_policy_binding(port_id, context.session)
         except n1kv_exc.PortBindingNotFound:
             if not uuidutils.is_uuid_like(policy_profile_attr):
                 policy_profile = n1kv_db.get_policy_profile_by_name(
                     policy_profile_attr,
                     context.session)
                 if policy_profile:
                     policy_profile_attr = policy_profile.id
                 else:
                     LOG.error(_LE("Policy Profile %(profile)s does "
                                   "not exist."),
                               {"profile": policy_profile_attr})
                     raise ml2_exc.MechanismDriverError()
             elif not (n1kv_db.get_policy_profile_by_uuid(
                          context.session,
                          policy_profile_attr)):
                 LOG.error(_LE("Policy Profile %(profile)s does not "
                               "exist."),
                           {"profile": policy_profile_attr})
                 raise ml2_exc.MechanismDriverError()
             n1kv_db.add_policy_binding(port_id,
                                        policy_profile_attr,
                                        context.session)
     result[constants.N1KV_PROFILE] = policy_profile_attr
Esempio n. 10
0
def convert_to_uuid_list_or_none(value_list):
    if value_list is None:
        return
    for sg_id in value_list:
        if not uuidutils.is_uuid_like(sg_id):
            msg = _("'%s' is not an integer or uuid") % sg_id
            raise qexception.InvalidInput(error_message=msg)
    return value_list
Esempio n. 11
0
 def _is_compute_port(self, port):
     try:
         if (port['device_id'] and uuidutils.is_uuid_like(port['device_id'])
                 and port['device_owner'].startswith('compute:')):
             return True
     except (KeyError, AttributeError):
         pass
     return False
Esempio n. 12
0
def convert_to_uuid_list_or_none(value_list):
    if value_list is None:
        return
    for sg_id in value_list:
        if not uuidutils.is_uuid_like(sg_id):
            msg = _("'%s' is not an integer or uuid") % sg_id
            raise qexception.InvalidInput(error_message=msg)
    return value_list
Esempio n. 13
0
 def _is_compute_port(self, port):
     try:
         if (port['device_id'] and uuidutils.is_uuid_like(port['device_id'])
                 and port['device_owner'].startswith('compute:')):
             return True
     except (KeyError, AttributeError):
         pass
     return False
Esempio n. 14
0
    def existing_dhcp_networks(cls, conf, root_helper):
        """Return a list of existing networks ids that we have configs for."""

        confs_dir = os.path.abspath(os.path.normpath(conf.dhcp_confs))

        return [
            c for c in os.listdir(confs_dir)
            if uuidutils.is_uuid_like(c)
        ]
    def test_get_router(self):
        router_data = {
            'router': {'name': 'test_router1', 'admin_state_up': True}}
        router = self.plugin.create_router(self.context, router_data)
        router = self.plugin.get_router(self.context, router['id'])
        self.assertTrue(uuidutils.is_uuid_like(router.get('id')))

        self.assertRaises(l3.RouterNotFound, self.plugin.get_router,
                          self.context, uuidutils.generate_uuid())
Esempio n. 16
0
 def existing_dhcp_networks(cls, conf):
     """Return a list of existing networks ids that we have configs for."""
     confs_dir = cls.get_confs_dir(conf)
     try:
         return [
             c for c in os.listdir(confs_dir) if uuidutils.is_uuid_like(c)
         ]
     except OSError:
         return []
Esempio n. 17
0
    def existing_dhcp_networks(cls, conf, root_helper):
        """Return a list of existing networks ids that we have configs for."""

        confs_dir = os.path.abspath(os.path.normpath(conf.dhcp_confs))

        return [
            c for c in os.listdir(confs_dir)
            if uuidutils.is_uuid_like(c)
        ]
Esempio n. 18
0
def _validate_instance_members(data, valid_values=None):
    if not isinstance(data, list):
        msg = _("'%s' is not a list") % data
        LOG.debug(msg)
        return msg

    instance_set = set()
    expected_keys = ['instance_id', 'weight']

    for instance in data:
        for port_key in instance:
            if port_key not in expected_keys:
                msg = (_("'%(data)s' is not in %(valid_values)s") % {
                    'data': port_key,
                    'valid_values': expected_keys
                })
                LOG.debug(msg)
                return msg

        if not isinstance(instance, dict):
            msg = _("'%s' is not a dict") % instance
            LOG.debug(msg)
            return msg

        if not instance.has_key('instance_id'):
            msg = _("'%s' must has key instance_id") % instance
            LOG.debug(msg)
            return msg
        else:
            if not uuidutils.is_uuid_like(instance['instance_id']):
                msg = _("'%s' is not a valid UUID") % instance['instance_id']
                LOG.debug(msg)
                return msg

        if not instance.has_key('weight'):
            msg = _("you must input weight and his value")
            LOG.debug(msg)
            return msg
        else:
            msg = attr._validate_non_negative(instance['weight'])
            if msg:
                msg = _("the value of weight must be int")
                LOG.debug(msg)
                return msg

            weight = int(instance['weight'])
            if weight <= 0:
                msg = _("the value of weight must be int and big than 0")
                LOG.debug(msg)
                return msg

        if instance['instance_id'] in instance_set:
            msg = _("'%s' has duplicate key instance_id") % instance
            return msg

        instance_set.add(instance['instance_id'])
 def test_create_router(self):
     router_data = {
         'router': {
             'name': 'test_router1',
             'admin_state_up': True
         }
     }
     result = self.plugin.create_router(self.context, router_data)
     self.assertTrue(uuidutils.is_uuid_like(result.get('id')))
     self.driver.create_router.assert_called_once_with(mock.ANY)
Esempio n. 20
0
 def existing_dhcp_networks(cls, conf):
     """Return a list of existing networks ids that we have configs for."""
     confs_dir = cls.get_confs_dir(conf)
     try:
         return [
             c for c in os.listdir(confs_dir)
             if uuidutils.is_uuid_like(c)
         ]
     except OSError:
         return []
Esempio n. 21
0
def convert_to_uuid_or_none(value):
    if value is None:
        return

    if value == "":
        return

    if not uuidutils.is_uuid_like(value):
        msg = _("'%s' is not an integer or uuid") % value
        raise qexception.InvalidInput(error_message=msg)
    return value
Esempio n. 22
0
def convert_to_uuid_or_none(value):
    if value is None:
        return

    if value == "":
        return

    if not uuidutils.is_uuid_like(value):
        msg = _("'%s' is not an integer or uuid") % value
        raise qexception.InvalidInput(error_message=msg)
    return value
    def test_get_router(self):
        router_data = {
            'router': {
                'name': 'test_router1',
                'admin_state_up': True
            }
        }
        router = self.plugin.create_router(self.context, router_data)
        router = self.plugin.get_router(self.context, router['id'])
        self.assertTrue(uuidutils.is_uuid_like(router.get('id')))

        self.assertRaises(l3.RouterNotFound, self.plugin.get_router,
                          self.context, uuidutils.generate_uuid())
Esempio n. 24
0
    def existing_dhcp_networks(cls, conf, root_helper):
        """Return a list of existing networks ids that we have configs for."""

        confs_dir = os.path.abspath(os.path.normpath(conf.dhcp_confs))

        class FakeNetwork:
            def __init__(self, net_id):
                self.id = net_id

        return [
            c for c in os.listdir(confs_dir)
            if (uuidutils.is_uuid_like(c) and
                cls(conf, FakeNetwork(c), root_helper).active)
        ]
Esempio n. 25
0
 def _device_to_port_id(cls, device):
     # REVISIT(rkukura): Consider calling into MechanismDrivers to
     # process device names, or having MechanismDrivers supply list
     # of device prefixes to strip.
     if device.startswith(TAP_DEVICE_PREFIX):
         return device[TAP_DEVICE_PREFIX_LENGTH:]
     else:
         # REVISIT(irenab): Consider calling into bound MD to
         # handle the get_device_details RPC, then remove the 'else' clause
         if not uuidutils.is_uuid_like(device):
             port = db.get_port_from_device_mac(device)
             if port:
                 return port.id
     return device
Esempio n. 26
0
 def _device_to_port_id(cls, device):
     # REVISIT(rkukura): Consider calling into MechanismDrivers to
     # process device names, or having MechanismDrivers supply list
     # of device prefixes to strip.
     if device.startswith(TAP_DEVICE_PREFIX):
         return device[TAP_DEVICE_PREFIX_LENGTH:]
     else:
         # REVISIT(irenab): Consider calling into bound MD to
         # handle the get_device_details RPC, then remove the 'else' clause
         if not uuidutils.is_uuid_like(device):
             port = db.get_port_from_device_mac(device)
             if port:
                 return port.id
     return device
Esempio n. 27
0
    def existing_dhcp_networks(cls, conf, root_helper):
        """Return a list of existing networks ids that we have configs for."""

        confs_dir = os.path.abspath(os.path.normpath(conf.dhcp_confs))

        class FakeNetwork:
            def __init__(self, net_id):
                self.id = net_id

        return [
            c for c in os.listdir(confs_dir)
            if (uuidutils.is_uuid_like(c) and
                cls(conf, FakeNetwork(c), root_helper).active)
        ]
Esempio n. 28
0
def _validate_external_dict(data, key_specs=None):
    if data is None:
        return
    if not isinstance(data, dict):
        msg = _("'%s' is not a dictionary") % data
        LOG.debug(msg)
        return msg
    for d in data:
        if not uuidutils.is_uuid_like(d):
            msg = _("'%s' is not a valid UUID") % d
            LOG.debug(msg)
            return msg
        if not isinstance(data[d], list):
            msg = _("'%s' is not a list") % data[d]
            LOG.debug(msg)
            return msg
Esempio n. 29
0
def _validate_external_dict(data, key_specs=None):
    if data is None:
        return
    if not isinstance(data, dict):
        msg = _("'%s' is not a dictionary") % data
        LOG.debug(msg)
        return msg
    for d in data:
        if not uuidutils.is_uuid_like(d):
            msg = _("'%s' is not a valid UUID") % d
            LOG.debug(msg)
            return msg
        if not isinstance(data[d], list):
            msg = _("'%s' is not a list") % data[d]
            LOG.debug(msg)
            return msg
Esempio n. 30
0
def _validate_uuid(data, valid_values=None):
    if not uuidutils.is_uuid_like(data):
        msg = _("'%s' is not a valid UUID") % data
        LOG.debug(msg)
        return msg
Esempio n. 31
0
def _validate_uuid(data, valid_values=None):
    if not uuidutils.is_uuid_like(data):
        msg = _("'%s' is not a valid UUID") % data
        LOG.debug(msg)
        return msg
 def test_create_router(self):
     router_data = {
         'router': {'name': 'test_router1', 'admin_state_up': True}}
     result = self.plugin.create_router(self.context, router_data)
     self.assertTrue(uuidutils.is_uuid_like(result.get('id')))
     self.driver.create_router.assert_called_once_with(mock.ANY)
Esempio n. 33
0
def _validate_instance_ctx(instance_ctx, valid_values=None):
    expected_keys = [
        'user_side_port', 'network_side_port', 'classification_type',
        'user_side_action', 'network_side_action'
    ]

    action_choose = ["vlan", "dmac"]

    type_choose = ['dl_src', '5tuple']

    for port_key in instance_ctx:
        if port_key not in expected_keys:
            msg = (_("'%(data)s' is not in %(valid_values)s") % {
                'data': port_key,
                'valid_values': expected_keys
            })
            LOG.debug(msg)
            return msg

    for port_key in ['user_side_port', 'network_side_port']:
        if instance_ctx.has_key(port_key) and \
                not uuidutils.is_uuid_like(instance_ctx[port_key]):
            msg = _("'%s' is not a valid UUID") % port_key
            LOG.debug(msg)
            return msg
    for port_key in ['user_side_action', 'network_side_action']:
        if instance_ctx.has_key(port_key):
            if not isinstance(instance_ctx[port_key], dict):
                msg = _("'%s' is not a  dictionary") % (instance_ctx[port_key])
                LOG.debug(msg)
                return msg
            else:
                for key in instance_ctx[port_key]:
                    if key not in action_choose:
                        msg = (_("'%(data)s' is not in %(valid_values)s") % {
                            'data': key,
                            'valid_values': action_choose
                        })
                        LOG.debug(msg)
                        return msg
                    elif key == 'dmac':
                        msg = attr._validate_mac_address(
                            instance_ctx[port_key][key])
                        if msg:
                            msg = _("'%s' is not a valid MAC address"
                                    ) % instance_ctx[port_key][key]
                            LOG.debug(msg)
                            return msg
                    elif key == 'vlan':
                        try:
                            if int(instance_ctx[port_key][key]) < 0 or int(
                                    instance_ctx[port_key][key]) > 4095:
                                msg = (_(
                                    "vlan tag '%(data)s' is not a valid num in %(valid_values)s"
                                ) % {
                                    'data': instance_ctx[port_key][key],
                                    'valid_values': '[0-4095]'
                                })
                                LOG.debug(msg)
                                return msg
                        except:
                            msg = (_("vlan tag should be number"))
                            LOG.debug(msg)
                            return msg
    for port_key in ['classification_type']:
        if instance_ctx.has_key(
                port_key) and instance_ctx[port_key] not in type_choose:
            msg = (_(
                "classification type '%(data)s' is not a valid type ,it should in %(valid_values)s"
            ) % {
                'data': instance_ctx[port_key],
                'valid_values': type_choose
            })
            LOG.debug(msg)
            return msg
 def test_l3_create_router(self):
     router = self.interceptor.create_router(self.context, {'router': {}})
     self.assertTrue(uuidutils.is_uuid_like(router.get('id')))
     self.l3.create_router.assert_called_with(self.context,
                                              {'router': {'metadata': {}}})