def args2body(self, parsed_args):
     _security_group_id = quantumv20.find_resourceid_by_name_or_id(
         self.get_client(), 'security_group', parsed_args.security_group_id)
     body = {'security_group_rule': {
         'security_group_id': _security_group_id,
         'direction': parsed_args.direction,
         'ethertype': parsed_args.ethertype}}
     if parsed_args.protocol:
         body['security_group_rule'].update(
             {'protocol': parsed_args.protocol})
     if parsed_args.port_range_min:
         body['security_group_rule'].update(
             {'port_range_min': parsed_args.port_range_min})
     if parsed_args.port_range_max:
         body['security_group_rule'].update(
             {'port_range_max': parsed_args.port_range_max})
     if parsed_args.source_ip_prefix:
         body['security_group_rule'].update(
             {'source_ip_prefix': parsed_args.source_ip_prefix})
     if parsed_args.source_group_id:
         _source_group_id = quantumv20.find_resourceid_by_name_or_id(
             self.get_client(), 'security_group',
             parsed_args.source_group_id)
         body['security_group_rule'].update(
             {'source_group_id': _source_group_id})
     if parsed_args.tenant_id:
         body['security_group_rule'].update(
             {'tenant_id': parsed_args.tenant_id})
     return body
Exemplo n.º 2
0
 def args2body(self, parsed_args):
     _network_id = quantumv20.find_resourceid_by_name_or_id(
         self.get_client(), 'network', parsed_args.network_id)
     body = {'port': {'admin_state_up': parsed_args.admin_state_down,
                      'network_id': _network_id, }, }
     if parsed_args.mac_address:
         body['port'].update({'mac_address': parsed_args.mac_address})
     if parsed_args.device_id:
         body['port'].update({'device_id': parsed_args.device_id})
     if parsed_args.tenant_id:
         body['port'].update({'tenant_id': parsed_args.tenant_id})
     if parsed_args.name:
         body['port'].update({'name': parsed_args.name})
     ips = []
     if parsed_args.fixed_ip:
         for ip_spec in parsed_args.fixed_ip:
             ip_dict = utils.str2dict(ip_spec)
             if 'subnet_id' in ip_dict:
                 subnet_name_id = ip_dict['subnet_id']
                 _subnet_id = quantumv20.find_resourceid_by_name_or_id(
                     self.get_client(), 'subnet', subnet_name_id)
                 ip_dict['subnet_id'] = _subnet_id
             ips.append(ip_dict)
     if ips:
         body['port'].update({'fixed_ips': ips})
     return body
Exemplo n.º 3
0
 def run(self, parsed_args):
     self.log.debug("run(%s)" % parsed_args)
     quantum_client = self.get_client()
     quantum_client.format = parsed_args.request_format
     # TODO(danwent): handle passing in port-id
     _router_id = quantumv20.find_resourceid_by_name_or_id(quantum_client, self.resource, parsed_args.router_id)
     _subnet_id = quantumv20.find_resourceid_by_name_or_id(quantum_client, "subnet", parsed_args.subnet_id)
     quantum_client.remove_interface_router(_router_id, {"subnet_id": _subnet_id})
     print >>self.app.stdout, (_("Removed interface from router %s") % parsed_args.router_id)
Exemplo n.º 4
0
 def run(self, parsed_args):
     self.log.debug("run(%s)" % parsed_args)
     quantum_client = self.get_client()
     quantum_client.format = parsed_args.request_format
     _router_id = quantumv20.find_resourceid_by_name_or_id(quantum_client, self.resource, parsed_args.router_id)
     _ext_net_id = quantumv20.find_resourceid_by_name_or_id(
         quantum_client, "network", parsed_args.external_network_id
     )
     quantum_client.add_gateway_router(_router_id, {"network_id": _ext_net_id})
     print >>self.app.stdout, (_("Set gateway for router %s") % parsed_args.router_id)
Exemplo n.º 5
0
 def run(self, parsed_args):
     self.log.debug('run(%s)' % parsed_args)
     quantum_client = self.get_client()
     quantum_client.format = parsed_args.request_format
     _router_id = quantumv20.find_resourceid_by_name_or_id(
         quantum_client, self.resource, parsed_args.router_id)
     _ext_net_id = quantumv20.find_resourceid_by_name_or_id(
         quantum_client, 'network', parsed_args.external_network_id)
     quantum_client.add_gateway_router(
         _router_id,
         {'network_id': _ext_net_id,
          'enable_snat': parsed_args.enable_snat})
     print >>self.app.stdout, (
         _('Set gateway for router %s') % parsed_args.router_id)
Exemplo n.º 6
0
 def run(self, parsed_args):
     self.log.debug('run(%s)' % parsed_args)
     quantum_client = self.get_client()
     quantum_client.format = parsed_args.request_format
     #TODO(danwent): handle passing in port-id
     _router_id = quantumv20.find_resourceid_by_name_or_id(
         quantum_client, self.resource, parsed_args.router_id)
     _subnet_id = quantumv20.find_resourceid_by_name_or_id(
         quantum_client, 'subnet', parsed_args.subnet_id)
     quantum_client.add_interface_router(_router_id,
                                         {'subnet_id': _subnet_id})
     #TODO(danwent): print port ID that is added
     print >>self.app.stdout, (
         _('Added interface to router %s') % parsed_args.router_id)
 def call_server(self, quantum_client, search_opts, parsed_args):
     _id = quantumV20.find_resourceid_by_name_or_id(quantum_client,
                                                    'network',
                                                    parsed_args.network)
     search_opts['network'] = _id
     data = quantum_client.list_dhcp_agent_hosting_networks(**search_opts)
     return data
 def call_server(self, quantum_client, search_opts, parsed_args):
     _id = quantumV20.find_resourceid_by_name_or_id(quantum_client,
                                                    'router',
                                                    parsed_args.router)
     search_opts['router'] = _id
     data = quantum_client.list_l3_agent_hosting_routers(**search_opts)
     return data
Exemplo n.º 9
0
    def args2body(self, parsed_args):
        _network_id = quantumv20.find_resourceid_by_name_or_id(
            self.get_client(), 'network', parsed_args.network_id)
        body = {'subnet': {'cidr': parsed_args.cidr,
                           'network_id': _network_id,
                           'ip_version': parsed_args.ip_version, }, }

        if parsed_args.gateway and parsed_args.no_gateway:
            raise exceptions.CommandError("--gateway option and "
                                          "--no-gateway option can "
                                          "not be used same time")
        if parsed_args.no_gateway:
            body['subnet'].update({'gateway_ip': None})
        if parsed_args.gateway:
            body['subnet'].update({'gateway_ip': parsed_args.gateway})
        if parsed_args.tenant_id:
            body['subnet'].update({'tenant_id': parsed_args.tenant_id})
        if parsed_args.name:
            body['subnet'].update({'name': parsed_args.name})
        if parsed_args.disable_dhcp:
            body['subnet'].update({'enable_dhcp': False})
        if parsed_args.allocation_pools:
            body['subnet']['allocation_pools'] = parsed_args.allocation_pools
        if parsed_args.host_routes:
            body['subnet']['host_routes'] = parsed_args.host_routes
        if parsed_args.dns_nameservers:
            body['subnet']['dns_nameservers'] = parsed_args.dns_nameservers

        return body
Exemplo n.º 10
0
 def run(self, parsed_args):
     self.log.debug("run(%s)" % parsed_args)
     quantum_client = self.get_client()
     quantum_client.format = parsed_args.request_format
     _router_id = quantumv20.find_resourceid_by_name_or_id(quantum_client, self.resource, parsed_args.router_id)
     quantum_client.remove_gateway_router(_router_id)
     print >>self.app.stdout, (_("Removed gateway from router %s") % parsed_args.router_id)
Exemplo n.º 11
0
 def get_data(self, parsed_args):
     quantum_client = self.get_client()
     quantum_client.format = parsed_args.request_format
     _id = quantumv20.find_resourceid_by_name_or_id(
         quantum_client, 'router', parsed_args.id)
     self.values_specs.append('--device_id=%s' % _id)
     return super(ListRouterPort, self).get_data(parsed_args)
Exemplo n.º 12
0
    def args2body(self, parsed_args):
        _network_id = quantumv20.find_resourceid_by_name_or_id(
            self.get_client(), 'network', parsed_args.network_id)
        body = {'subnet': {'cidr': parsed_args.cidr,
                           'network_id': _network_id,
                           'ip_version': parsed_args.ip_version, }, }

        if parsed_args.gateway and parsed_args.no_gateway:
            raise exceptions.CommandError("--gateway option and "
                                          "--no-gateway option can "
                                          "not be used same time")
        if parsed_args.no_gateway:
            body['subnet'].update({'gateway_ip': None})
        if parsed_args.gateway:
            body['subnet'].update({'gateway_ip': parsed_args.gateway})
        if parsed_args.tenant_id:
            body['subnet'].update({'tenant_id': parsed_args.tenant_id})
        if parsed_args.name:
            body['subnet'].update({'name': parsed_args.name})
        ips = []
        if parsed_args.allocation_pool:
            for ip_spec in parsed_args.allocation_pool:
                ips.append(utils.str2dict(ip_spec))
        if ips:
            body['subnet'].update({'allocation_pools': ips})

        return body
 def test_get_id_from_name_multiple(self):
     name = 'myname'
     reses = {'networks': [{'id': str(uuid.uuid4())},
                           {'id': str(uuid.uuid4())}]}
     resstr = self.client.serialize(reses)
     self.mox.StubOutWithMock(self.client.httpclient, "request")
     path = getattr(self.client, "networks_path")
     self.client.httpclient.request(
         test_cli20.end_url(path, "fields=id&name=" + name), 'GET',
         body=None,
         headers=mox.ContainsKeyValue('X-Auth-Token', test_cli20.TOKEN)
     ).AndReturn((test_cli20.MyResp(200), resstr))
     self.mox.ReplayAll()
     try:
         quantumv20.find_resourceid_by_name_or_id(
             self.client, 'network', name)
     except exceptions.QuantumClientException as ex:
         self.assertTrue('Multiple' in ex.message)
Exemplo n.º 14
0
 def run(self, parsed_args):
     self.log.debug('run(%s)' % parsed_args)
     quantum_client = self.get_client()
     quantum_client.format = parsed_args.request_format
     _router_id = quantumv20.find_resourceid_by_name_or_id(
         quantum_client, self.resource, parsed_args.router_id)
     quantum_client.remove_gateway_router(_router_id)
     print >> self.app.stdout, (_('Removed gateway from router %s') %
                                parsed_args.router_id)
 def run(self, parsed_args):
     quantum_client = self.get_client()
     quantum_client.format = parsed_args.request_format
     body = {'health_monitor': {'id': parsed_args.health_monitor_id}}
     pool_id = quantumv20.find_resourceid_by_name_or_id(
         quantum_client, 'pool', parsed_args.pool_id)
     quantum_client.associate_health_monitor(pool_id, body)
     print >>self.app.stdout, (_('Associated health monitor '
                                 '%s') % parsed_args.health_monitor_id)
Exemplo n.º 16
0
    def remove_from_instance(self, context, instance, security_group_name):
        """Remove the security group associated with the instance."""
        quantum = quantumv2.get_client(context)
        try:
            security_group_id = quantumv20.find_resourceid_by_name_or_id(
                quantum, 'security_group', security_group_name)
        except q_exc.QuantumClientException as e:
            exc_info = sys.exc_info()
            if e.status_code == 404:
                msg = ("Security group %s is not found for project %s" %
                       (security_group_name, context.project_id))
                self.raise_not_found(msg)
            else:
                LOG.exception(_("Quantum Error:"))
                raise exc_info[0], exc_info[1], exc_info[2]
        params = {'device_id': instance['uuid']}
        try:
            ports = quantum.list_ports(**params).get('ports')
        except q_exc.QuantumClientException:
            with excutils.save_and_reraise_exception():
                LOG.exception(_("Quantum Error:"))

        if not ports:
            msg = ("instance_id %s could not be found as device id on"
                   " any ports" % instance['uuid'])
            self.raise_not_found(msg)

        found_security_group = False
        for port in ports:
            try:
                port.get('security_groups', []).remove(security_group_id)
            except ValueError:
                # When removing a security group from an instance the security
                # group should be on both ports since it was added this way if
                # done through the nova api. In case it is not a 404 is only
                # raised if the security group is not found on any of the
                # ports on the instance.
                continue

            updated_port = {'security_groups': port['security_groups']}
            try:
                LOG.info(_("Adding security group %(security_group_id)s to "
                           "port %(port_id)s"),
                         {'security_group_id': security_group_id,
                          'port_id': port['id']})
                quantum.update_port(port['id'], {'port': updated_port})
                found_security_group = True
            except Exception:
                with excutils.save_and_reraise_exception():
                    LOG.exception(_("Quantum Error:"))
        if not found_security_group:
            msg = (_("Security group %(security_group_name)s not assocaited "
                     "with the instance %(instance)s"),
                   {'security_group_name': security_group_name,
                    'instance': instance['uuid']})
            self.raise_not_found(msg)
 def run(self, parsed_args):
     self.log.debug('run(%s)' % parsed_args)
     quantum_client = self.get_client()
     quantum_client.format = parsed_args.request_format
     _id = quantumV20.find_resourceid_by_name_or_id(
         quantum_client, 'router', parsed_args.router)
     quantum_client.add_router_to_l3_agent(parsed_args.l3_agent,
                                           {'router_id': _id})
     print >>self.app.stdout, (
         _('Added router %s to L3 agent') % parsed_args.router)
 def run(self, parsed_args):
     self.log.debug('run(%s)' % parsed_args)
     quantum_client = self.get_client()
     quantum_client.format = parsed_args.request_format
     _net_id = quantumV20.find_resourceid_by_name_or_id(
         quantum_client, 'network', parsed_args.network)
     quantum_client.remove_network_from_dhcp_agent(
         parsed_args.dhcp_agent, _net_id)
     print >>self.app.stdout, (
         _('Removed network %s to DHCP agent') % parsed_args.network)
 def run(self, parsed_args):
     self.log.debug('run(%s)' % parsed_args)
     quantum_client = self.get_client()
     quantum_client.format = parsed_args.request_format
     _id = quantumV20.find_resourceid_by_name_or_id(
         quantum_client, 'router', parsed_args.router)
     quantum_client.remove_router_from_l3_agent(
         parsed_args.l3_agent, _id)
     print >>self.app.stdout, (
         _('Removed Router %s to L3 agent') % parsed_args.router)
Exemplo n.º 20
0
 def test_get_id_from_name_notfound(self):
     name = 'myname'
     reses = {'networks': []}
     resstr = self.client.serialize(reses)
     self.mox.StubOutWithMock(self.client.httpclient, "request")
     path = getattr(self.client, "networks_path")
     self.client.httpclient.request(
         test_cli20.end_url(path, "fields=id&name=" + name),
         'GET',
         body=None,
         headers=ContainsKeyValue('X-Auth-Token',
                                  test_cli20.TOKEN)).AndReturn(
                                      (test_cli20.MyResp(200), resstr))
     self.mox.ReplayAll()
     try:
         quantumv20.find_resourceid_by_name_or_id(self.client, 'network',
                                                  name)
     except exceptions.QuantumClientException as ex:
         self.assertTrue('Unable to find' in ex.message)
         self.assertEqual(404, ex.status_code)
Exemplo n.º 21
0
 def args2body(self, parsed_args):
     _network_id = quantumv20.find_resourceid_by_name_or_id(
         self.get_client(), 'network', parsed_args.floating_network_id)
     body = {self.resource: {'floating_network_id': _network_id}}
     if parsed_args.port_id:
         body[self.resource].update({'port_id': parsed_args.port_id})
     if parsed_args.tenant_id:
         body[self.resource].update({'tenant_id': parsed_args.tenant_id})
     if parsed_args.fixed_ip_address:
         body[self.resource].update({'fixed_ip_address':
                                     parsed_args.fixed_ip_address})
     return body
Exemplo n.º 22
0
 def args2body(self, parsed_args):
     _pool_id = quantumv20.find_resourceid_by_name_or_id(
         self.get_client(), 'pool', parsed_args.pool_id)
     body = {
         self.resource: {
             'pool_id': _pool_id,
             'admin_state_up': parsed_args.admin_state_down,
         },
     }
     quantumv20.update_dict(parsed_args, body[self.resource],
                            ['address', 'port', 'weight', 'tenant_id'])
     return body
Exemplo n.º 23
0
 def args2body(self, parsed_args):
     _network_id = quantumv20.find_resourceid_by_name_or_id(
         self.get_client(), 'network', parsed_args.floating_network_id)
     body = {self.resource: {'floating_network_id': _network_id}}
     if parsed_args.port_id:
         body[self.resource].update({'port_id': parsed_args.port_id})
     if parsed_args.tenant_id:
         body[self.resource].update({'tenant_id': parsed_args.tenant_id})
     if parsed_args.fixed_ip_address:
         body[self.resource].update(
             {'fixed_ip_address': parsed_args.fixed_ip_address})
     return body
Exemplo n.º 24
0
    def add_to_instance(self, context, instance, security_group_name):
        """Add security group to the instance."""

        quantum = quantumv2.get_client(context)
        try:
            security_group_id = quantumv20.find_resourceid_by_name_or_id(
                quantum, 'security_group', security_group_name)
        except q_exc.QuantumClientException as e:
            if e.status_code == 404:
                msg = ("Security group %s is not found for project %s" %
                       (security_group_name, context.project_id))
                self.raise_not_found(msg)
            else:
                LOG.exception(_("Quantum Error:"))
                raise e
        params = {'device_id': instance['uuid']}
        try:
            ports = quantum.list_ports(**params).get('ports')
        except q_exc.QuantumClientException as e:
            LOG.exception(_("Quantum Error:"))
            raise e

        if not ports:
            msg = ("instance_id %s could not be found as device id on"
                   " any ports" % instance['uuid'])
            self.raise_not_found(msg)

        for port in ports:
            if not self._has_security_group_requirements(port):
                LOG.warn(
                    _("Cannot add security group %(name)s to %(instance)s"
                      " since the port %(port_id)s does not meet security"
                      " requirements"), {
                          'name': security_group_name,
                          'instance': instance['uuid'],
                          'port_id': port['id']
                      })
                raise exception.SecurityGroupCannotBeApplied()
            if 'security_groups' not in port:
                port['security_groups'] = []
            port['security_groups'].append(security_group_id)
            updated_port = {'security_groups': port['security_groups']}
            try:
                LOG.info(
                    _("Adding security group %(security_group_id)s to "
                      "port %(port_id)s"), {
                          'security_group_id': security_group_id,
                          'port_id': port['id']
                      })
                quantum.update_port(port['id'], {'port': updated_port})
            except Exception:
                with excutils.save_and_reraise_exception():
                    LOG.exception(_("Quantum Error:"))
Exemplo n.º 25
0
    def remove_from_instance(self, context, instance, security_group_name):
        """Remove the security group associated with the instance."""
        quantum = quantumv2.get_client(context)
        try:
            security_group_id = quantumv20.find_resourceid_by_name_or_id(quantum, "security_group", security_group_name)
        except q_exc.QuantumClientException as e:
            if e.status_code == 404:
                msg = "Security group %s is not found for project %s" % (security_group_name, context.project_id)
                self.raise_not_found(msg)
            else:
                LOG.exception(_("Quantum Error:"))
                raise e
        params = {"device_id": instance["uuid"]}
        try:
            ports = quantum.list_ports(**params).get("ports")
        except q_exc.QuantumClientException as e:
            LOG.exception(_("Quantum Error:"))
            raise e

        if not ports:
            msg = "instance_id %s could not be found as device id on" " any ports" % instance["uuid"]
            self.raise_not_found(msg)

        found_security_group = False
        for port in ports:
            try:
                port.get("security_groups", []).remove(security_group_id)
            except ValueError:
                # When removing a security group from an instance the security
                # group should be on both ports since it was added this way if
                # done through the nova api. In case it is not a 404 is only
                # raised if the security group is not found on any of the
                # ports on the instance.
                continue

            updated_port = {"security_groups": port["security_groups"]}
            try:
                LOG.info(
                    _("Adding security group %(security_group_id)s to " "port %(port_id)s"),
                    {"security_group_id": security_group_id, "port_id": port["id"]},
                )
                quantum.update_port(port["id"], {"port": updated_port})
                found_security_group = True
            except Exception:
                LOG.exception(_("Quantum Error:"))
                raise e
        if not found_security_group:
            msg = (
                _("Security group %(security_group_name)s not assocaited " "with the instance %(instance)s"),
                {"security_group_name": security_group_name, "instance": instance["uuid"]},
            )
            self.raise_not_found(msg)
Exemplo n.º 26
0
 def args2body(self, parsed_args):
     _subnet_id = quantumv20.find_resourceid_by_name_or_id(
         self.get_client(), 'subnet', parsed_args.subnet_id)
     body = {
         self.resource: {
             'admin_state_up': parsed_args.admin_state,
             'subnet_id': _subnet_id,
         },
     }
     quantumv20.update_dict(parsed_args, body[self.resource],
                            ['description', 'lb_method', 'name',
                             'protocol', 'tenant_id'])
     return body
Exemplo n.º 27
0
 def args2body(self, parsed_args):
     _pool_id = quantumv20.find_resourceid_by_name_or_id(
         self.get_client(), 'pool', parsed_args.pool_id)
     body = {
         self.resource: {
             'pool_id': _pool_id,
             'admin_state_up': parsed_args.admin_state_down,
         },
     }
     quantumv20.update_dict(parsed_args, body[self.resource],
                            ['address', 'connection_limit', 'description',
                             'name', 'port', 'protocol', 'subnet_id',
                             'tenant_id'])
     return body
Exemplo n.º 28
0
    def get(self, context, name=None, id=None, map_exception=False):
        quantum = quantumv2.get_client(context)
        try:
            if not id and name:
                id = quantumv20.find_resourceid_by_name_or_id(quantum, "security_group", name)
            group = quantum.show_security_group(id).get("security_group")
        except q_exc.QuantumClientException as e:
            if e.status_code == 404:
                LOG.debug(_("Quantum security group %s not found"), name)
                self.raise_not_found(e.message)
            else:
                LOG.error(_("Quantum Error: %s"), e)
                raise e

        return self._convert_to_nova_security_group_format(group)
Exemplo n.º 29
0
    def run(self, parsed_args):
        self.log.debug('run(%s)' % parsed_args)
        quantum_client = self.get_client()
        quantum_client.format = parsed_args.request_format

        if '=' in parsed_args.interface:
            resource, value = parsed_args.interface.split('=', 1)
            if resource not in ['subnet', 'port']:
                exceptions.CommandError('You must specify either subnet or '
                                        'port for INTERFACE parameter.')
        else:
            resource = 'subnet'
            value = parsed_args.interface

        _router_id = quantumv20.find_resourceid_by_name_or_id(
            quantum_client, self.resource, parsed_args.router_id)

        _interface_id = quantumv20.find_resourceid_by_name_or_id(
            quantum_client, resource, value)
        body = {'%s_id' % resource: _interface_id}

        portinfo = self.call_api(quantum_client, _router_id, body)
        print >>self.app.stdout, self.success_message(parsed_args.router_id,
                                                      portinfo)
 def test_get_id_from_id(self):
     _id = str(uuid.uuid4())
     reses = {'networks': [{'id': _id, }, ], }
     resstr = self.client.serialize(reses)
     self.mox.StubOutWithMock(self.client.httpclient, "request")
     path = getattr(self.client, "networks_path")
     self.client.httpclient.request(
         test_cli20.end_url(path, "fields=id&id=" + _id), 'GET',
         body=None,
         headers=mox.ContainsKeyValue('X-Auth-Token', test_cli20.TOKEN)
     ).AndReturn((test_cli20.MyResp(200), resstr))
     self.mox.ReplayAll()
     returned_id = quantumv20.find_resourceid_by_name_or_id(
         self.client, 'network', _id)
     self.assertEqual(_id, returned_id)
Exemplo n.º 31
0
    def add_to_instance(self, context, instance, security_group_name):
        """Add security group to the instance."""

        quantum = quantumv2.get_client(context)
        try:
            security_group_id = quantumv20.find_resourceid_by_name_or_id(quantum, "security_group", security_group_name)
        except q_exc.QuantumClientException as e:
            if e.status_code == 404:
                msg = "Security group %s is not found for project %s" % (security_group_name, context.project_id)
                self.raise_not_found(msg)
            else:
                LOG.exception(_("Quantum Error:"))
                raise e
        params = {"device_id": instance["uuid"]}
        try:
            ports = quantum.list_ports(**params).get("ports")
        except q_exc.QuantumClientException as e:
            LOG.exception(_("Quantum Error:"))
            raise e

        if not ports:
            msg = "instance_id %s could not be found as device id on" " any ports" % instance["uuid"]
            self.raise_not_found(msg)

        for port in ports:
            if not self._has_security_group_requirements(port):
                LOG.warn(
                    _(
                        "Cannot add security group %(name)s to %(instance)s"
                        " since the port %(port_id)s does not meet security"
                        " requirements"
                    ),
                    {"name": security_group_name, "instance": instance["uuid"], "port_id": port["id"]},
                )
                raise exception.SecurityGroupCannotBeApplied()
            if "security_groups" not in port:
                port["security_groups"] = []
            port["security_groups"].append(security_group_id)
            updated_port = {"security_groups": port["security_groups"]}
            try:
                LOG.info(
                    _("Adding security group %(security_group_id)s to " "port %(port_id)s"),
                    {"security_group_id": security_group_id, "port_id": port["id"]},
                )
                quantum.update_port(port["id"], {"port": updated_port})
            except Exception:
                with excutils.save_and_reraise_exception():
                    LOG.exception(_("Quantum Error:"))
Exemplo n.º 32
0
    def add_to_instance(self, context, instance, security_group_name):
        """Add security group to the instance."""

        quantum = quantumv2.get_client(context)
        try:
            security_group_id = quantumv20.find_resourceid_by_name_or_id(
                quantum, 'security_group', security_group_name)
        except q_exc.QuantumClientException as e:
            exc_info = sys.exc_info()
            if e.status_code == 404:
                msg = ("Security group %s is not found for project %s" %
                       (security_group_name, context.project_id))
                self.raise_not_found(msg)
            else:
                LOG.exception(_("Quantum Error:"))
                raise exc_info[0], exc_info[1], exc_info[2]
        params = {'device_id': instance['uuid']}
        try:
            ports = quantum.list_ports(**params).get('ports')
        except q_exc.QuantumClientException:
            with excutils.save_and_reraise_exception():
                LOG.exception(_("Quantum Error:"))

        if not ports:
            msg = ("instance_id %s could not be found as device id on"
                   " any ports" % instance['uuid'])
            self.raise_not_found(msg)

        for port in ports:
            if not self._has_security_group_requirements(port):
                LOG.warn(_("Cannot add security group %(name)s to %(instance)s"
                           " since the port %(port_id)s does not meet security"
                           " requirements"), {'name': security_group_name,
                         'instance': instance['uuid'], 'port_id': port['id']})
                raise exception.SecurityGroupCannotBeApplied()
            if 'security_groups' not in port:
                port['security_groups'] = []
            port['security_groups'].append(security_group_id)
            updated_port = {'security_groups': port['security_groups']}
            try:
                LOG.info(_("Adding security group %(security_group_id)s to "
                           "port %(port_id)s"),
                         {'security_group_id': security_group_id,
                          'port_id': port['id']})
                quantum.update_port(port['id'], {'port': updated_port})
            except Exception:
                with excutils.save_and_reraise_exception():
                    LOG.exception(_("Quantum Error:"))
Exemplo n.º 33
0
    def get(self, context, name=None, id=None, map_exception=False):
        quantum = quantumv2.get_client(context)
        try:
            if not id and name:
                id = quantumv20.find_resourceid_by_name_or_id(
                    quantum, 'security_group', name)
            group = quantum.show_security_group(id).get('security_group')
        except q_exc.QuantumClientException as e:
            if e.status_code == 404:
                LOG.debug(_("Quantum security group %s not found"), name)
                self.raise_not_found(e.message)
            else:
                LOG.error(_("Quantum Error: %s"), e)
                raise e

        return self._convert_to_nova_security_group_format(group)
Exemplo n.º 34
0
    def args2body(self, parsed_args):
        _network_id = quantumv20.find_resourceid_by_name_or_id(self.get_client(), "network", parsed_args.network_id)
        body = {"subnet": {"cidr": parsed_args.cidr, "network_id": _network_id, "ip_version": parsed_args.ip_version}}
        if parsed_args.gateway:
            body["subnet"].update({"gateway_ip": parsed_args.gateway})
        if parsed_args.tenant_id:
            body["subnet"].update({"tenant_id": parsed_args.tenant_id})
        if parsed_args.name:
            body["subnet"].update({"name": parsed_args.name})
        ips = []
        if parsed_args.allocation_pool:
            for ip_spec in parsed_args.allocation_pool:
                ips.append(utils.str2dict(ip_spec))
        if ips:
            body["subnet"].update({"allocation_pools": ips})

        return body
Exemplo n.º 35
0
 def test_get_id_from_id(self):
     _id = str(uuid.uuid4())
     reses = {
         'networks': [
             {
                 'id': _id,
             },
         ],
     }
     resstr = self.client.serialize(reses)
     self.mox.StubOutWithMock(self.client.httpclient, "request")
     path = getattr(self.client, "networks_path")
     self.client.httpclient.request(
         test_cli20.end_url(path, "fields=id&id=" + _id),
         'GET',
         body=None,
         headers=ContainsKeyValue('X-Auth-Token',
                                  test_cli20.TOKEN)).AndReturn(
                                      (test_cli20.MyResp(200), resstr))
     self.mox.ReplayAll()
     returned_id = quantumv20.find_resourceid_by_name_or_id(
         self.client, 'network', _id)
     self.assertEqual(_id, returned_id)
Exemplo n.º 36
0
                    c.security_group_rules.create(secgroup.id, "TCP", 22, 22, "10.0.0.0/8")
                except:
                    pass
                try:
                    c.security_group_rules.create(secgroup.id, "UDP", 4789, 4789, "10.0.0.0/8")
                except:
                    pass
                try:
                    c.security_group_rules.create(secgroup.id, "ICMP", -1, 255, "10.0.0.0/8")
                except:
                    pass

                #create quantum client for floating ip address creation/association and VM network
                quantum=qclient.Client(username=user, password=password, tenant_name=tenant_name, auth_url=auth_url, region_name=region_name)
                #look for network id of the external network
                _network_id = quantumv20.find_resourceid_by_name_or_id(quantum, 'network', tenant_name+'-net')
                v_nics=[]
                v_nic={}

                x = PrettyTable(["Property", "Value"])
                x.add_row(["VM name", instance_name])
                x.add_row(["VM number", i+1])
                x.add_row(["Network ID",_network_id])
                v_nic['net-id']=_network_id
                v_nic['v4-fixed-ip']=None
                v_nics.append(v_nic)
                hints={}
                if server_name:
                    hints['force_hosts']=server_name
                servers=c.servers.list()
                s1=None