def test_chain_fails_if_no_drivers_available(self):
        self._add_node_driver('test')
        drivers = [
            x.obj for x in self.sc_plugin.driver_manager.ordered_drivers
        ]
        create_1 = drivers[0].validate_create = mock.Mock()
        create_1.side_effect = n_exc.NeutronException()
        create_2 = drivers[1].validate_create = mock.Mock()
        create_2.side_effect = n_exc.NeutronException()

        profile = self._create_service_profile(
            service_type="TYPE",
            vendor=self.SERVICE_PROFILE_VENDOR)['service_profile']
        node = self.create_servicechain_node(
            service_profile_id=profile['id'],
            config=self.DEFAULT_LB_CONFIG)['servicechain_node']
        spec = self.create_servicechain_spec(
            nodes=[node['id']])['servicechain_spec']
        provider = self.create_policy_target_group()['policy_target_group']
        classifier = self.create_policy_classifier()['policy_classifier']
        self.create_servicechain_instance(provider_ptg_id=provider['id'],
                                          consumer_ptg_id='N/A',
                                          servicechain_specs=[spec['id']],
                                          classifier_id=classifier['id'],
                                          expected_res_status=400)
Ejemplo n.º 2
0
def add_tunnel_endpoint(ip, max_retries=10):
    """Return the endpoint of the given IP address or generate a new one."""

    # NOTE(rpodolyaka): generation of a new tunnel endpoint must be put into a
    #                   repeatedly executed transactional block to ensure it
    #                   doesn't conflict with any other concurrently executed
    #                   DB transactions in spite of the specified transactions
    #                   isolation level value
    for i in xrange(max_retries):
        LOG.debug(_('Adding a tunnel endpoint for %s'), ip)
        try:
            session = db.get_session()
            with session.begin(subtransactions=True):
                tunnel = (session.query(
                    ovs_models_v2.TunnelEndpoint).filter_by(
                        ip_address=ip).with_lockmode('update').first())

                if tunnel is None:
                    tunnel_id = _generate_tunnel_id(session)
                    tunnel = ovs_models_v2.TunnelEndpoint(ip, tunnel_id)
                    session.add(tunnel)

                return tunnel
        except db_exc.DBDuplicateEntry:
            # a concurrent transaction has been committed, try again
            LOG.debug(
                _('Adding a tunnel endpoint failed due to a concurrent'
                  'transaction had been committed (%s attempts left)'),
                max_retries - (i + 1))

    raise q_exc.NeutronException(
        message=_('Unable to generate a new tunnel id'))
Ejemplo n.º 3
0
 def __init__(self,
              server='localhost',
              user=None,
              password=None,
              port=2189,
              ssl=True,
              timeout=5000,
              base_uri=''):
     self.server = server
     self.port = port
     self.ssl = ssl
     self.base_uri = base_uri
     self.timeout = timeout
     if user and password:
         self.auth = base64.encodestring('%s:%s' % (user, password))
         self.auth = self.auth.replace('\n', '')
     else:
         msg = _('User and password must be specified')
         raise q_exc.NeutronException(msg)
     debug_params = {'server': self.server,
                     'port': self.port,
                     'ssl': self.ssl}
     LOG.debug(_('vDirectRESTClient:init server=%(server)s, '
               'port=%(port)d, '
               'ssl=%(ssl)r'), debug_params)
Ejemplo n.º 4
0
    def _remove_workflow(self, wf_params, context):
        params = _translate_vip_object_graph(wf_params, self.plugin, context)
        ids = params.pop('__ids__', None)
        if not ids:
            raise q_exc.NeutronException(
                _('params must contain __ids__ field!')
            )

        wf_name = ids['pool']
        LOG.debug(_('Remove the workflow %s') % wf_name)
        resource = '/api/workflow/%s' % (wf_name)
        response = _rest_wrapper(self.rest_client.call('DELETE', resource,
                                 None, None),
                                 [204, 202, 404])
        msg = response.get('message', None)
        if msg == "Not Found":
            self.plugin._delete_db_vip(context, ids['vip'])
        else:
            oper = OperationAttributes(response['uri'],
                                       ids,
                                       lb_db.Vip,
                                       ids['vip'],
                                       delete=True)
            LOG.debug(_('Pushing operation %s to the queue'), oper)
            self.queue.put_nowait(oper)
Ejemplo n.º 5
0
def update_security_group_rules(cluster, spid, rules):
    path = "/ws.v1/security-profile/%s" % spid

    # Allow all dhcp responses in
    rules['logical_port_egress_rules'].append({
        'ethertype': 'IPv4',
        'protocol': constants.PROTO_NUM_UDP,
        'port_range_min': constants.DHCP_RESPONSE_PORT,
        'port_range_max': constants.DHCP_RESPONSE_PORT,
        'ip_prefix': '0.0.0.0/0'
    })
    # If there are no ingress rules add bunk rule to drop all ingress traffic
    if not rules['logical_port_ingress_rules']:
        rules['logical_port_ingress_rules'].append({
            'ethertype': 'IPv4',
            'ip_prefix': '127.0.0.1/32'
        })
    try:
        body = mk_body(
            logical_port_ingress_rules=rules['logical_port_ingress_rules'],
            logical_port_egress_rules=rules['logical_port_egress_rules'])
        rsp = nsxlib.do_request(HTTP_PUT, path, body, cluster=cluster)
    except exceptions.NotFound as e:
        LOG.error(nsxlib.format_exception("Unknown", e, locals()))
        #FIXME(salvatore-orlando): This should not raise NeutronException
        raise exceptions.NeutronException()
    LOG.debug(_("Updated Security Profile: %s"), rsp)
    return rsp
Ejemplo n.º 6
0
def create_lqueue(cluster, queue_data):
    params = {
        'name': 'display_name',
        'qos_marking': 'qos_marking',
        'min': 'min_bandwidth_rate',
        'max': 'max_bandwidth_rate',
        'dscp': 'dscp'
    }
    queue_obj = dict((nvp_name, queue_data.get(api_name))
                     for api_name, nvp_name in params.iteritems()
                     if attr.is_attr_set(queue_data.get(api_name)))
    if 'display_name' in queue_obj:
        queue_obj['display_name'] = utils.check_and_truncate(
            queue_obj['display_name'])

    queue_obj['tags'] = utils.get_tags()
    try:
        return do_request(HTTP_POST,
                          _build_uri_path(LQUEUE_RESOURCE),
                          jsonutils.dumps(queue_obj),
                          cluster=cluster)['uuid']
    except NvpApiClient.NvpApiException:
        # FIXME(salv-orlando): This should not raise NeutronException
        with excutils.save_and_reraise_exception():
            raise exception.NeutronException()
Ejemplo n.º 7
0
def delete_port(cluster, switch, port):
    uri = "/ws.v1/lswitch/" + switch + "/lport/" + port
    try:
        do_request(HTTP_DELETE, uri, cluster=cluster)
    except exception.NotFound:
        LOG.exception(_("Port or Network not found"))
        raise exception.PortNotFoundOnNetwork(net_id=switch, port_id=port)
    except api_exc.NsxApiException:
        raise exception.NeutronException()
Ejemplo n.º 8
0
def delete_lqueue(cluster, queue_id):
    try:
        do_request(HTTP_DELETE,
                   _build_uri_path(LQUEUE_RESOURCE, resource_id=queue_id),
                   cluster=cluster)
    except Exception:
        # FIXME(salv-orlando): This should not raise NeutronException
        with excutils.save_and_reraise_exception():
            raise exception.NeutronException()
Ejemplo n.º 9
0
def _rest_wrapper(response, success_codes=[202]):
    """Wrap a REST call and make sure a valid status is returned."""
    if response[RESP_STATUS] not in success_codes:
        raise q_exc.NeutronException(str(response[RESP_STATUS]) + ':' +
                                     response[RESP_REASON] +
                                     '. Error description: ' +
                                     response[RESP_STR])
    else:
        return response[RESP_DATA]
Ejemplo n.º 10
0
def handle_port_dhcp_access(plugin, context, port, action):
    LOG.info(
        _("Performing DHCP %(action)s for resource: %(resource)s") % {
            "action": action,
            "resource": port
        })
    if port["device_owner"] == const.DEVICE_OWNER_DHCP:
        network_id = port["network_id"]
        if action == "create_port":
            # at this point the port must have a subnet and a fixed ip
            subnet_id = port["fixed_ips"][0]['subnet_id']
            subnet = plugin.get_subnet(context, subnet_id)
            subnet_data = {
                "mac_address": port["mac_address"],
                "ip_address": subnet['cidr'],
                "subnet_id": subnet['id']
            }
            try:
                plugin.lsn_manager.lsn_port_dhcp_setup(context, network_id,
                                                       port['id'], subnet_data,
                                                       subnet)
            except p_exc.PortConfigurationError:
                err_msg = (_("Error while configuring DHCP for "
                             "port %s"), port['id'])
                LOG.error(err_msg)
                raise n_exc.NeutronException()
        elif action == "delete_port":
            plugin.lsn_manager.lsn_port_dispose(context, network_id,
                                                port['mac_address'])
    elif port["device_owner"] != const.DEVICE_OWNER_DHCP:
        if port.get("fixed_ips"):
            # do something only if there are IP's and dhcp is enabled
            subnet_id = port["fixed_ips"][0]['subnet_id']
            if not plugin.get_subnet(context, subnet_id)['enable_dhcp']:
                LOG.info(_("DHCP is disabled for subnet %s: nothing "
                           "to do"), subnet_id)
                return
            host_data = {
                "mac_address": port["mac_address"],
                "ip_address": port["fixed_ips"][0]['ip_address']
            }
            network_id = port["network_id"]
            if action == "create_port":
                handler = plugin.lsn_manager.lsn_port_dhcp_host_add
            elif action == "delete_port":
                handler = plugin.lsn_manager.lsn_port_dhcp_host_remove
            try:
                handler(context, network_id, subnet_id, host_data)
            except p_exc.PortConfigurationError:
                with excutils.save_and_reraise_exception():
                    if action == 'create_port':
                        db_base_plugin_v2.NeutronDbPluginV2.delete_port(
                            plugin, context, port['id'])
    LOG.info(_("DHCP for port %s configured successfully"), port['id'])
Ejemplo n.º 11
0
    def _parse_ip_ranges(self, cfg_ranges, current_range):
        if not cfg_ranges:
            return
        for entry in cfg_ranges:
            entry = entry.strip()
            try:
                cidr = netaddr.IPNetwork(entry)
            except ValueError as ex:
                raise exc.NeutronException(error=ex)

            current_range.append(entry)
        LOG.info(_("ranges: %(range)s"), {'range': current_range})
def _raise_contrail_error(info, obj_name):
        exc_name = info.get('exception')
        if exc_name:
            if exc_name == 'BadRequest' and 'resource' not in info:
                info['resource'] = obj_name
            if hasattr(exc, exc_name):
                raise getattr(exc, exc_name)(**info)
            if hasattr(l3, exc_name):
                raise getattr(l3, exc_name)(**info)
            if hasattr(securitygroup, exc_name):
                raise getattr(securitygroup, exc_name)(**info)
            if hasattr(allowedaddresspairs, exc_name):
                raise getattr(allowedaddresspairs, exc_name)(**info)
        raise exc.NeutronException(**info)
Ejemplo n.º 13
0
def create_profile_binding(tenant_id, profile_id, profile_type):
    """Create Network/Policy Profile association with a tenant."""
    if profile_type not in ["network", "policy"]:
        raise q_exc.NeutronException("Invalid profile type")

    if _profile_binding_exists(tenant_id, profile_id, profile_type):
        return get_profile_binding(tenant_id, profile_id)

    db_session = db.get_session()
    with db_session.begin(subtransactions=True):
        binding = n1kv_models_v2.ProfileBinding(profile_type=profile_type,
                                                profile_id=profile_id,
                                                tenant_id=tenant_id)
        db_session.add(binding)
        return binding
Ejemplo n.º 14
0
 def test_create_pool_with_snatportcreate_failure(self):
     with contextlib.nested(
         self.subnet(),
         mock.patch.object(self.driver.plugin._core_plugin, 'get_subnet'),
         mock.patch.object(self.driver.plugin._core_plugin, 'get_ports'),
         mock.patch.object(self.driver.plugin._core_plugin, 'create_port')
     ) as (subnet, mock_get_subnet, mock_get_ports, mock_create_port):
         mock_get_subnet.return_value = subnet['subnet']
         mock_get_ports.return_value = None
         mock_create_port.side_effect = exceptions.NeutronException()
         testpool = self._build_testpool_contents(subnet['subnet'])
         #reset the create_resource() mock
         self.create_resource_mock.reset_mock()
         # execute the method under test.
         self.assertRaises(exceptions.NeutronException,
                           self.driver.create_pool,
                           self.context, testpool)
Ejemplo n.º 15
0
    def _parse_ranges(self, cfg_ranges, current_range):
        if not cfg_ranges:
            return
        for entry in cfg_ranges:
            entry = entry.strip()
            try:
                tun_min, tun_max = entry.split(':')
                tun_min = int(tun_min)
                tun_max = int(tun_max)
                if tun_min > tun_max:
                    tunnel_range = tun_max, tun_min
                else:
                    tunnel_range = tun_min, tun_max
            except ValueError as ex:
                raise exc.NeutronException(error=ex)

            current_range.append(tunnel_range)
        LOG.info(_("ranges: %(range)s"), {'range': current_range})
Ejemplo n.º 16
0
def _remove_object_from_db(plugin, context, oper):
    """Remove a specific entity from db."""
    LOG.debug(_('_remove_object_from_db %s'), str(oper))
    if oper.lbaas_entity == lb_db.PoolMonitorAssociation:
        plugin._delete_db_pool_health_monitor(context,
                                              oper.entity_id,
                                              oper.object_graph['pool'])
    elif oper.lbaas_entity == lb_db.Member:
        plugin._delete_db_member(context, oper.entity_id)
    elif oper.lbaas_entity == lb_db.Vip:
        plugin._delete_db_vip(context, oper.entity_id)
    elif oper.lbaas_entity == lb_db.Pool:
        plugin._delete_db_pool(context, oper.entity_id)
    else:
        raise q_exc.NeutronException(
            _('Tried to remove unsupported lbaas entity %s!'),
            str(oper.lbaas_entity)
        )
Ejemplo n.º 17
0
 def _verify_workflow_templates(self):
     """Verify the existance of workflows on vDirect server."""
     workflows = {self.l2_l3_wf_name:
                  False, self.l4_wf_name: False}
     resource = '/api/workflowTemplate'
     response = _rest_wrapper(self.rest_client.call('GET',
                                                    resource,
                                                    None,
                                                    None), [200])
     for wf in workflows.keys():
         for wf_template in response:
             if wf == wf_template['name']:
                 workflows[wf] = True
                 break
     for wf, found in workflows.items():
         if not found:
             msg = _('The workflow %s does not exist on vDirect.') % wf
             raise q_exc.NeutronException(msg)
     self.workflow_templates_exists = True
Ejemplo n.º 18
0
    def test_second_driver_scheduled_if_first_fails(self):
        self._add_node_driver('test')
        drivers = [
            x.obj for x in self.sc_plugin.driver_manager.ordered_drivers
        ]
        create_1 = drivers[0].validate_create = mock.Mock()
        create_1.side_effect = n_exc.NeutronException()

        # This happens without error
        profile = self.create_service_profile(
            service_type="TYPE")['service_profile']
        node = self.create_servicechain_node(service_profile_id=profile['id'],
                                             config='{}')['servicechain_node']
        spec = self.create_servicechain_spec(
            nodes=[node['id']])['servicechain_spec']
        provider = self.create_policy_target_group()['policy_target_group']
        consumer = self.create_policy_target_group()['policy_target_group']
        self.create_servicechain_instance(provider_ptg_id=provider['id'],
                                          consumer_ptg_id=consumer['id'],
                                          servicechain_specs=[spec['id']],
                                          expected_res_status=201)
Ejemplo n.º 19
0
    def _update_workflow(self, wf_name, action,
                         wf_params, context,
                         delete=False,
                         lbaas_entity=None, entity_id=None):
        """Update the WF state. Push the result to a queue for processing."""

        if not self.workflow_templates_exists:
            self._verify_workflow_templates()

        if action not in self.actions_to_skip:
            params = _translate_vip_object_graph(wf_params,
                                                 self.plugin,
                                                 context)
        else:
            params = wf_params

        resource = '/api/workflow/%s/action/%s' % (wf_name, action)
        response = _rest_wrapper(self.rest_client.call('POST', resource,
                                 {'parameters': params},
                                 TEMPLATE_HEADER))
        LOG.debug(_('_update_workflow response: %s '), response)

        if action not in self.actions_to_skip:
            ids = params.pop('__ids__', None)
            if not ids:
                raise q_exc.NeutronException(
                    _('params must contain __ids__ field!')
                )

            oper = OperationAttributes(response['uri'],
                                       ids,
                                       lbaas_entity,
                                       entity_id,
                                       delete=delete)
            LOG.debug(_('Pushing operation %s to the queue'), oper)
            self.queue.put_nowait(oper)