def _stubs(self, network, subnets): self.ipam = quark.ipam.QuarkIpamANY() with self.context.session.begin(): net_mod = db_api.network_create(self.context, **network) for subnet in subnets: subnet["network"] = net_mod db_api.subnet_create(self.context, **subnet) yield net_mod
def test_get_subnets_cidr_set(self): network = db_api.network_create(self.context) db_api.subnet_create( self.context, network=network, cidr=self.cidr) self.context.session.flush() ipset = null_routes.get_subnets_cidr_set(self.context, [network.id]) self.assertEqual(ipset, netaddr.IPSet(netaddr.IPNetwork(self.cidr)))
def _stubs(self, network, subnet): self.ipam = quark.ipam.QuarkIpamANY() with self.context.session.begin(): net_mod = db_api.network_create(self.context, **network) subnet["network"] = net_mod sub1 = db_api.subnet_create(self.context, **subnet) subnet["id"] = 2 sub2 = db_api.subnet_create(self.context, do_not_use=True, **subnet) yield net_mod, sub1, sub2
def _stubs(self, network, subnet, dealloc=True): self.plugin = quark.plugin.Plugin() self.ipam = quark.ipam.QuarkIpamANY() with self.context.session.begin(): net_mod = db_api.network_create(self.context, **network) subnet["network"] = net_mod db_api.subnet_create(self.context, **subnet) ip_addr = self.ipam.allocate_ip_address(self.context, net_mod["id"], 0, 0) if dealloc: self.ipam._deallocate_ip_address(self.context, ip_addr[0]) yield net_mod
def _fixtures(self, models): self.ipam = quark.ipam.QuarkIpamANY() net = dict(name="public", tenant_id='fake') net_mod = db_api.network_create(self.context, **net) with self.context.session.begin(): for model in models: policy_mod = db_api.ip_policy_create( self.context, **model['ip_policy']) model['subnet']["network"] = net_mod model['subnet']["ip_policy"] = policy_mod db_api.subnet_create(self.context, **model['subnet']) yield net_mod
def _fixtures(self, models): self.ipam = quark.ipam.QuarkIpamANY() net = dict(name="public", tenant_id='fake') net_mod = db_api.network_create(self.context, **net) with self.context.session.begin(): for model in models: policy_mod = db_api.ip_policy_create(self.context, **model['ip_policy']) model['subnet']["network"] = net_mod model['subnet']["ip_policy"] = policy_mod db_api.subnet_create(self.context, **model['subnet']) yield net_mod
def _stubs(self): with mock.patch("neutron.common.rpc.get_notifier"), \ mock.patch("neutron.quota.QUOTAS.limit_check"): mac = {'mac_address_range': dict(cidr="AA:BB:CC")} self.context.is_admin = True macrng_api.create_mac_address_range(self.context, mac) self.context.is_admin = False network_info = dict(name="public", tenant_id="fake", network_plugin="BASE", ipam_strategy="ANY") network_info = {"network": network_info} network = network_api.create_network(self.context, network_info) subnet = db_api.subnet_create(self.context, tenant_id="fake", cidr="192.168.10.0/24", network_id=network['id']) fixed_ips = [dict(subnet_id=subnet['id'], enabled=True, ip_address=self.addr)] port = dict(port=dict(network_id=network['id'], tenant_id=self.context.tenant_id, device_id=2, fixed_ips=fixed_ips)) port_api.create_port(self.context, port) self.context.is_admin = True filters = {"deallocated": "both"} ip = ip_addr.get_ip_addresses(self.context, **filters) self.context.is_admin = False yield ip[0]
def test_subnet_update_set_alloc_pool_cache_concurrency(self): subnet = {"cidr": "192.168.10.0/24"} subnet_db = db_api.subnet_create(self.context, **subnet) self.context.session.flush() # establish second session old_session = self.context.session self.context._session = None subnet_to_delete = db_api.subnet_find( self.context, id=subnet_db.id, scope=db_api.ONE) db_api.subnet_delete(self.context, subnet_to_delete) self.context.session.flush() # restore first session self.context._session = old_session try: db_api.subnet_update_set_alloc_pool_cache( self.context, subnet_db, {"foo": "bar"}) self.context.session.flush() except exc.StaleDataError as e: self.fail("Did not expect StaleDataError exception: {0}".format(e)) self.assertEqual(subnet_db["_allocation_pool_cache"], "{\"foo\": \"bar\"}")
def _stubs(self): with self.context.session.begin(): subnet = db_api.subnet_create(self.context, cidr="192.168.0.0/24") ip = db_api.ip_address_create(self.context, address=self.addr, subnet_id=subnet["id"]) yield ip
def _stubs(self): with mock.patch("neutron.common.rpc.get_notifier"), \ mock.patch("neutron.quota.QUOTAS.limit_check"): mac = {'mac_address_range': dict(cidr="AA:BB:CC")} self.context.is_admin = True macrng_api.create_mac_address_range(self.context, mac) self.context.is_admin = False network_info = dict(name="public", tenant_id="fake", network_plugin="BASE", ipam_strategy="ANY") network_info = {"network": network_info} network = network_api.create_network(self.context, network_info) subnet = db_api.subnet_create(self.context, tenant_id="fake", cidr="192.168.10.0/24", network_id=network['id']) fixed_ips = [ dict(subnet_id=subnet['id'], enabled=True, ip_address=self.addr) ] port = dict(port=dict(network_id=network['id'], tenant_id=self.context.tenant_id, device_id=2, fixed_ips=fixed_ips)) port_api.create_port(self.context, port) self.context.is_admin = True filters = {"deallocated": "both"} ip = ip_addr.get_ip_addresses(self.context, **filters) self.context.is_admin = False yield ip[0]
def _stubs(self, network, subnet, address, lock=False): self.ipam = quark.ipam.QuarkIpamANY() with self.context.session.begin(): next_ip = subnet.pop("next_auto_assign_ip", 0) net_mod = db_api.network_create(self.context, **network) subnet["network"] = net_mod sub_mod = db_api.subnet_create(self.context, **subnet) address["network_id"] = net_mod["id"] address["subnet_id"] = sub_mod["id"] ip = db_api.ip_address_create(self.context, **address) address.pop("address") ip = db_api.ip_address_update(self.context, ip, **address) # NOTE(asadoughi): update after cidr constructor has been invoked db_api.subnet_update(self.context, sub_mod, next_auto_assign_ip=next_ip) if lock: db_api.lock_holder_create(self.context, ip, name="testlock", type="ip_address") yield net_mod
def create_subnet(context, subnet): """Create a subnet. Create a subnet which represents a range of IP addresses that can be allocated to devices : param context: neutron api request context : param subnet: dictionary describing the subnet, with keys as listed in the RESOURCE_ATTRIBUTE_MAP object in neutron/api/v2/attributes.py. All keys will be populated. """ LOG.info("create_subnet for tenant %s" % context.tenant_id) net_id = subnet["subnet"]["network_id"] net = db_api.network_find(context, id=net_id, scope=db_api.ONE) if not net: raise exceptions.NetworkNotFound(net_id=net_id) sub_attrs = subnet["subnet"] _validate_subnet_cidr(context, net_id, sub_attrs["cidr"]) cidr = netaddr.IPNetwork(sub_attrs["cidr"]) gateway_ip = utils.pop_param(sub_attrs, "gateway_ip", str(cidr[1])) dns_ips = utils.pop_param(sub_attrs, "dns_nameservers", []) host_routes = utils.pop_param(sub_attrs, "host_routes", []) allocation_pools = utils.pop_param(sub_attrs, "allocation_pools", []) sub_attrs["network"] = net new_subnet = db_api.subnet_create(context, **sub_attrs) default_route = None for route in host_routes: netaddr_route = netaddr.IPNetwork(route["destination"]) if netaddr_route.value == routes.DEFAULT_ROUTE.value: default_route = route gateway_ip = default_route["nexthop"] new_subnet["routes"].append(db_api.route_create( context, cidr=route["destination"], gateway=route["nexthop"])) if default_route is None: new_subnet["routes"].append(db_api.route_create( context, cidr=str(routes.DEFAULT_ROUTE), gateway=gateway_ip)) for dns_ip in dns_ips: new_subnet["dns_nameservers"].append(db_api.dns_create( context, ip=netaddr.IPAddress(dns_ip))) if allocation_pools: exclude = netaddr.IPSet([cidr]) for p in allocation_pools: x = netaddr.IPSet(netaddr.IPRange(p["start"], p["end"])) exclude = exclude - x new_subnet["ip_policy"] = db_api.ip_policy_create(context, exclude=exclude) subnet_dict = v._make_subnet_dict(new_subnet, default_route=routes.DEFAULT_ROUTE) subnet_dict["gateway_ip"] = gateway_ip return subnet_dict
def _stubs(self): with self.context.session.begin(): subnet = db_api.subnet_create(self.context, cidr="192.168.0.0/24") db_api.ip_address_create(self.context, address=self.addr, subnet_id=subnet["id"]) yield
def insert_subnet(self, network_db, cidr, do_not_use=False): subnet = {"network": network_db, "cidr": cidr, "ip_version": netaddr.IPNetwork(cidr).version, "do_not_use": do_not_use} subnet_db = db_api.subnet_create(self.context, **subnet) self.context.session.flush() return subnet_db
def _stubs(self, network, subnet): self.ipam = quark.ipam.QuarkIpamANY() with self.context.session.begin(): net_mod = db_api.network_create(self.context, **network) subnet["network"] = net_mod sub_mod = db_api.subnet_create(self.context, **subnet) yield net_mod with self.context.session.begin(): db_api.subnet_delete(self.context, sub_mod) db_api.network_delete(self.context, net_mod)
def _stubs(self, network, subnet): self.ipam = quark.ipam.QuarkIpamANY() with self.context.session.begin(): next_ip = subnet.pop("next_auto_assign_ip", 0) net_mod = db_api.network_create(self.context, **network) subnet["network"] = net_mod sub_mod = db_api.subnet_create(self.context, **subnet) # NOTE(asadoughi): update after cidr constructor has been invoked db_api.subnet_update(self.context, sub_mod, next_auto_assign_ip=next_ip) yield net_mod
def test_create_locks_address_doesnt_exist(self): network = db_api.network_create(self.context) subnet = db_api.subnet_create( self.context, network=network, cidr=self.cidr, ip_version=4) self.context.session.flush() addresses = netaddr.IPSet(netaddr.IPNetwork(self.sub_cidr)) null_routes.create_locks(self.context, [network.id], addresses) address = db_api.ip_address_find( self.context, subnet_id=subnet.id, scope=db_api.ONE) self.assertIsNotNone(address) self.assertIsNotNone(address.lock_id)
def _stubs(self, network, subnet, dealloc=True): self.plugin = quark.plugin.Plugin() self.ipam = quark.ipam.QuarkIpamANY() with self.context.session.begin(): net_mod = db_api.network_create(self.context, **network) subnet["network"] = net_mod next_auto = subnet.pop("next_auto_assign_ip", 0) sub_mod = db_api.subnet_create(self.context, **subnet) db_api.subnet_update(self.context, sub_mod, next_auto_assign_ip=next_auto) ip_addr = [] self.ipam.allocate_ip_address(self.context, ip_addr, net_mod["id"], 0, 0) if dealloc: self.ipam.deallocate_ip_address(self.context, ip_addr[0]) yield net_mod
def create_network(context, network): """Create a network. Create a network which represents an L2 network segment which can have a set of subnets and ports associated with it. : param context: neutron api request context : param network: dictionary describing the network, with keys as listed in the RESOURCE_ATTRIBUTE_MAP object in neutron/api/v2/attributes.py. All keys will be populated. """ LOG.info("create_network for tenant %s" % context.tenant_id) # Generate a uuid that we're going to hand to the backend and db net_uuid = uuidutils.generate_uuid() #TODO(mdietz) this will be the first component registry hook, but # lets make it work first pnet_type, phys_net, seg_id = _adapt_provider_nets(context, network) net_attrs = network["network"] # NOTE(mdietz) I think ideally we would create the providernet # elsewhere as a separate driver step that could be # kept in a plugin and completely removed if desired. We could # have a pre-callback/observer on the netdriver create_network # that gathers any additional parameters from the network dict net_driver.create_network(context, net_attrs["name"], network_id=net_uuid, phys_type=pnet_type, phys_net=phys_net, segment_id=seg_id) subs = net_attrs.pop("subnets", []) net_attrs["id"] = net_uuid net_attrs["tenant_id"] = context.tenant_id new_net = db_api.network_create(context, **net_attrs) new_subnets = [] for sub in subs: sub["subnet"]["network_id"] = new_net["id"] sub["subnet"]["tenant_id"] = context.tenant_id s = db_api.subnet_create(context, **sub["subnet"]) new_subnets.append(s) new_net["subnets"] = new_subnets if not security_groups.get_security_groups( context, filters={"id": security_groups.DEFAULT_SG_UUID}): security_groups._create_default_security_group(context) return v._make_network_dict(new_net)
def setUp(self): super(BaseFloatingIPTest, self).setUp() self.public_net_id = "00000000-0000-0000-0000-000000000000" net_stat = '{"%s": {}}' % self.public_net_id cfg.CONF.set_override('default_net_strategy', net_stat, group='QUARK') old_strat = db_api.STRATEGY def reset_strategy(): db_api.STRATEGY = old_strat db_api.STRATEGY = network_strategy.JSONStrategy() self.addCleanup(reset_strategy) admin_ctx = context.get_admin_context() self._setup_mock_requests() self.plugin = quark.plugin.Plugin() mac = {'mac_address_range': dict(cidr="AA:BB:CC")} macrng_api.create_mac_address_range(admin_ctx, mac) with admin_ctx.session.begin(): tenant = 'rackspace' floating_net = dict(name='publicnet', tenant_id=tenant, id=self.public_net_id) self.floating_network = db_api.network_create( self.context, **floating_net) self.pub_net_cidr = "10.1.1.0/24" floating_subnet = dict(id=self.public_net_id, cidr=self.pub_net_cidr, ip_policy=None, tenant_id=tenant, segment_id='floating_ip', network_id=self.floating_network.id) self.floating_subnet = db_api.subnet_create( self.context, **floating_subnet) user_net = dict(name='user_network', tenant_id='fake') self.user_network = self.plugin.create_network( self.context, {'network': user_net}) user_subnet = dict(cidr="192.168.1.0/24", ip_policy=None, tenant_id="fake", network_id=self.user_network['id']) self.user_subnet = self.plugin.create_subnet( self.context, {'subnet': user_subnet}) user_port1 = dict(name='user_port1', network_id=self.user_network['id']) self.user_port1 = self.plugin.create_port( self.context, {'port': user_port1}) user_port2 = dict(name='user_port2', network_id=self.user_network['id']) self.user_port2 = self.plugin.create_port( self.context, {'port': user_port2})
def create_network(context, network): """Create a network. Create a network which represents an L2 network segment which can have a set of subnets and ports associated with it. : param context: neutron api request context : param network: dictionary describing the network, with keys as listed in the RESOURCE_ATTRIBUTE_MAP object in neutron/api/v2/attributes.py. All keys will be populated. """ LOG.info("create_network for tenant %s" % context.tenant_id) # Generate a uuid that we're going to hand to the backend and db net_uuid = uuidutils.generate_uuid() # TODO(mdietz) this will be the first component registry hook, but # lets make it work first pnet_type, phys_net, seg_id = _adapt_provider_nets(context, network) net_attrs = network["network"] # NOTE(mdietz) I think ideally we would create the providernet # elsewhere as a separate driver step that could be # kept in a plugin and completely removed if desired. We could # have a pre-callback/observer on the netdriver create_network # that gathers any additional parameters from the network dict net_driver.create_network( context, net_attrs["name"], network_id=net_uuid, phys_type=pnet_type, phys_net=phys_net, segment_id=seg_id ) subs = net_attrs.pop("subnets", []) net_attrs["id"] = net_uuid net_attrs["tenant_id"] = context.tenant_id new_net = db_api.network_create(context, **net_attrs) new_subnets = [] for sub in subs: sub["subnet"]["network_id"] = new_net["id"] sub["subnet"]["tenant_id"] = context.tenant_id s = db_api.subnet_create(context, **sub["subnet"]) new_subnets.append(s) new_net["subnets"] = new_subnets if not security_groups.get_security_groups(context, filters={"id": security_groups.DEFAULT_SG_UUID}): security_groups._create_default_security_group(context) return v._make_network_dict(new_net)
def _fixtures(self, models): self.ipam = quark.ipam.QuarkIpamANY() net = dict(name="public", tenant_id='fake') net_mod = db_api.network_create(self.context, **net) with self.context.session.begin(): for model in models: policy_mod = db_api.ip_policy_create( self.context, **model['ip_policy']) model['subnet']["network"] = net_mod model['subnet']["ip_policy"] = policy_mod next_ip = model['subnet'].pop("next_auto_assign_ip", 0) sub_mod = db_api.subnet_create(self.context, **model['subnet']) # NOTE(amir): update after cidr constructor has been invoked db_api.subnet_update(self.context, sub_mod, next_auto_assign_ip=next_ip) yield net_mod
def _fixtures(self, models): self.ipam = quark.ipam.QuarkIpamANY() net = dict(name="public", tenant_id='fake') net_mod = db_api.network_create(self.context, **net) with self.context.session.begin(): for model in models: policy_mod = db_api.ip_policy_create(self.context, **model['ip_policy']) model['subnet']["network"] = net_mod model['subnet']["ip_policy"] = policy_mod next_ip = model['subnet'].pop("next_auto_assign_ip", 0) sub_mod = db_api.subnet_create(self.context, **model['subnet']) # NOTE(amir): update after cidr constructor has been invoked db_api.subnet_update(self.context, sub_mod, next_auto_assign_ip=next_ip) yield net_mod
def _stubs(self, network, subnets, ipam_strategy): self.ipam = ipam_strategy with self.context.session.begin(): net_mod = db_api.network_create(self.context, **network) next_ip = [] sub_mod = [] for sub in subnets: next_ip.append(sub.pop("next_auto_assign_ip", 0)) sub["network"] = net_mod sub_mod.append(db_api.subnet_create(self.context, **sub)) for sub, ip_next in zip(sub_mod, next_ip): # NOTE(asadoughi): update after cidr constructor has been # invoked db_api.subnet_update(self.context, sub, next_auto_assign_ip=ip_next) yield net_mod, sub_mod with self.context.session.begin(): for sub in sub_mod: db_api.subnet_delete(self.context, sub) db_api.network_delete(self.context, net_mod)
def create_network(self, context, network): """Create a network. Create a network which represents an L2 network segment which can have a set of subnets and ports associated with it. : param context: quantum api request context : param network: dictionary describing the network, with keys as listed in the RESOURCE_ATTRIBUTE_MAP object in quantum/api/v2/attributes.py. All keys will be populated. """ LOG.info("create_network for tenant %s" % context.tenant_id) # Generate a uuid that we're going to hand to the backend and db net_uuid = uuidutils.generate_uuid() #NOTE(mdietz): probably want to abstract this out as we're getting # too tied to the implementation here self.net_driver.create_network(context, network["network"]["name"], network_id=net_uuid) subnets = [] if network["network"].get("subnets"): subnets = network["network"].pop("subnets") network["network"]["id"] = net_uuid network["network"]["tenant_id"] = context.tenant_id new_net = db_api.network_create(context, **network["network"]) new_subnets = [] for sub in subnets: sub["subnet"]["network_id"] = new_net["id"] sub["subnet"]["tenant_id"] = context.tenant_id s = db_api.subnet_create(context, **sub["subnet"]) new_subnets.append(s) new_net["subnets"] = new_subnets return self._make_network_dict(new_net)
def _stubs(self, network, subnet, ip_address1, ip_address2, ip_address3): with self.context.session.begin(): net_mod = db_api.network_create(self.context, **network) subnet["network"] = net_mod sub_mod = db_api.subnet_create(self.context, **subnet) # set tenant id to "123" ip_address1['network_id'] = net_mod.id ip_address1['subnet_id'] = sub_mod.id self.context.tenant_id = 123 ip_address1 = db_api.ip_address_create(self.context, **ip_address1) # set tenant_id=456 ip_address2['network_id'] = net_mod.id ip_address2['subnet_id'] = sub_mod.id self.context.tenant_id = 456 ip_address2 = db_api.ip_address_create(self.context, **ip_address2) # set tenant id = "123" to test the list of IPs ip_address3['network_id'] = net_mod.id ip_address3['subnet_id'] = sub_mod.id self.context.tenant_id = 123 ip_address3 = db_api.ip_address_create(self.context, **ip_address3) yield net_mod with self.context.session.begin(): db_api.subnet_delete(self.context, sub_mod) db_api.network_delete(self.context, net_mod)
def create_subnet(self, context, subnet): """Create a subnet. Create a subnet which represents a range of IP addresses that can be allocated to devices : param context: quantum api request context : param subnet: dictionary describing the subnet, with keys as listed in the RESOURCE_ATTRIBUTE_MAP object in quantum/api/v2/attributes.py. All keys will be populated. """ LOG.info("create_subnet for tenant %s" % context.tenant_id) net_id = subnet["subnet"]["network_id"] net = db_api.network_find(context, net_id, scope=db_api.ONE) if not net: raise exceptions.NetworkNotFound(net_id=net_id) s = subnet["subnet"] self._validate_subnet_cidr(context, net, s["cidr"]) cidr = netaddr.IPNetwork(s["cidr"]) gateway_ip = s.pop("gateway_ip") if gateway_ip is attributes.ATTR_NOT_SPECIFIED: gateway_ip = str(netaddr.IPAddress(cidr.first + 1)) dns_ips = [] if s["dns_nameservers"] is attributes.ATTR_NOT_SPECIFIED: s.pop("dns_nameservers") else: dns_ips = s.pop("dns_nameservers", []) routes = [] if s.get("host_routes"): if s["host_routes"] is attributes.ATTR_NOT_SPECIFIED: s.pop("host_routes") else: routes = s.pop("host_routes") default_route = None for route in routes: if netaddr.IPNetwork(route["destination"]) == DEFAULT_ROUTE: default_route = route break if default_route is None: routes.append(dict(destination=str(DEFAULT_ROUTE), nexthop=gateway_ip)) else: gateway_ip = default_route["nexthop"] new_subnet = db_api.subnet_create(context, **s) subnet_dict = self._make_subnet_dict(new_subnet) for dns_ip in dns_ips: db_api.dns_create(context, ip=netaddr.IPAddress(dns_ip), subnet_id=new_subnet["id"]) subnet_dict["dns_nameservers"].append(dns_ip) for route in routes: db_api.route_create(context, cidr=route["destination"], gateway=route["nexthop"], subnet_id=new_subnet["id"]) subnet_dict["host_routes"].append(route) subnet_dict["gateway_ip"] = gateway_ip return subnet_dict
def create_subnet(context, subnet): """Create a subnet. Create a subnet which represents a range of IP addresses that can be allocated to devices : param context: neutron api request context : param subnet: dictionary describing the subnet, with keys as listed in the RESOURCE_ATTRIBUTE_MAP object in neutron/api/v2/attributes.py. All keys will be populated. """ LOG.info("create_subnet for tenant %s" % context.tenant_id) net_id = subnet["subnet"]["network_id"] with context.session.begin(): net = db_api.network_find(context, id=net_id, scope=db_api.ONE) if not net: raise exceptions.NetworkNotFound(net_id=net_id) sub_attrs = subnet["subnet"] _validate_subnet_cidr(context, net_id, sub_attrs["cidr"]) cidr = netaddr.IPNetwork(sub_attrs["cidr"]) err_vals = {'cidr': sub_attrs["cidr"], 'network_id': net_id} err = _("Requested subnet with cidr: %(cidr)s for " "network: %(network_id)s. Prefix is too small, must be a " "larger subnet. A prefix less than /%(prefix)s is required.") if cidr.version == 6 and cidr.prefixlen > 64: err_vals["prefix"] = 65 err_msg = err % err_vals raise exceptions.InvalidInput(error_message=err_msg) elif cidr.version == 4 and cidr.prefixlen > 30: err_vals["prefix"] = 31 err_msg = err % err_vals raise exceptions.InvalidInput(error_message=err_msg) gateway_ip = utils.pop_param(sub_attrs, "gateway_ip", str(cidr[1])) dns_ips = utils.pop_param(sub_attrs, "dns_nameservers", []) host_routes = utils.pop_param(sub_attrs, "host_routes", []) allocation_pools = utils.pop_param(sub_attrs, "allocation_pools", None) if not context.is_admin and "segment_id" in sub_attrs: sub_attrs.pop("segment_id") sub_attrs["network"] = net new_subnet = db_api.subnet_create(context, **sub_attrs) default_route = None for route in host_routes: netaddr_route = netaddr.IPNetwork(route["destination"]) if netaddr_route.value == routes.DEFAULT_ROUTE.value: if default_route: raise q_exc.DuplicateRouteConflict( subnet_id=new_subnet["id"]) default_route = route gateway_ip = default_route["nexthop"] new_subnet["routes"].append(db_api.route_create( context, cidr=route["destination"], gateway=route["nexthop"])) if gateway_ip and default_route is None: new_subnet["routes"].append(db_api.route_create( context, cidr=str(routes.DEFAULT_ROUTE), gateway=gateway_ip)) for dns_ip in dns_ips: new_subnet["dns_nameservers"].append(db_api.dns_create( context, ip=netaddr.IPAddress(dns_ip))) if isinstance(allocation_pools, list) and allocation_pools: subnet_net = netaddr.IPNetwork(new_subnet["cidr"]) cidrset = netaddr.IPSet( netaddr.IPRange( netaddr.IPAddress(subnet_net.first), netaddr.IPAddress(subnet_net.last)).cidrs()) for p in allocation_pools: start = netaddr.IPAddress(p["start"]) end = netaddr.IPAddress(p["end"]) cidrset -= netaddr.IPSet(netaddr.IPRange( netaddr.IPAddress(start), netaddr.IPAddress(end)).cidrs()) default_cidrset = models.IPPolicy.get_ip_policy_cidrs(new_subnet) cidrset.update(default_cidrset) cidrs = [str(x.cidr) for x in cidrset.iter_cidrs()] new_subnet["ip_policy"] = db_api.ip_policy_create(context, exclude=cidrs) subnet_dict = v._make_subnet_dict(new_subnet) subnet_dict["gateway_ip"] = gateway_ip notifier_api.notify(context, notifier_api.publisher_id("network"), "ip_block.create", notifier_api.CONF.default_notification_level, dict(tenant_id=subnet_dict["tenant_id"], ip_block_id=subnet_dict["id"], created_at=new_subnet["created_at"])) return subnet_dict
def create_subnet(context, subnet): """Create a subnet. Create a subnet which represents a range of IP addresses that can be allocated to devices : param context: neutron api request context : param subnet: dictionary describing the subnet, with keys as listed in the RESOURCE_ATTRIBUTE_MAP object in neutron/api/v2/attributes.py. All keys will be populated. """ LOG.info("create_subnet for tenant %s" % context.tenant_id) net_id = subnet["subnet"]["network_id"] with context.session.begin(): net = db_api.network_find(context, None, None, None, False, id=net_id, scope=db_api.ONE) if not net: raise exceptions.NetworkNotFound(net_id=net_id) sub_attrs = subnet["subnet"] always_pop = ["enable_dhcp", "ip_version", "first_ip", "last_ip", "_cidr"] admin_only = ["segment_id", "do_not_use", "created_at", "next_auto_assign_ip"] utils.filter_body(context, sub_attrs, admin_only, always_pop) _validate_subnet_cidr(context, net_id, sub_attrs["cidr"]) cidr = netaddr.IPNetwork(sub_attrs["cidr"]) err_vals = {'cidr': sub_attrs["cidr"], 'network_id': net_id} err = _("Requested subnet with cidr: %(cidr)s for " "network: %(network_id)s. Prefix is too small, must be a " "larger subnet. A prefix less than /%(prefix)s is required.") if cidr.version == 6 and cidr.prefixlen > 64: err_vals["prefix"] = 65 err_msg = err % err_vals raise exceptions.InvalidInput(error_message=err_msg) elif cidr.version == 4 and cidr.prefixlen > 30: err_vals["prefix"] = 31 err_msg = err % err_vals raise exceptions.InvalidInput(error_message=err_msg) # Enforce subnet quotas net_subnets = get_subnets(context, filters=dict(network_id=net_id)) if not context.is_admin: v4_count, v6_count = 0, 0 for subnet in net_subnets: if netaddr.IPNetwork(subnet['cidr']).version == 6: v6_count += 1 else: v4_count += 1 if cidr.version == 6: tenant_quota_v6 = context.session.query(qdv.Quota).filter_by( tenant_id=context.tenant_id, resource='v6_subnets_per_network').first() if tenant_quota_v6 != -1: quota.QUOTAS.limit_check( context, context.tenant_id, v6_subnets_per_network=v6_count + 1) else: tenant_quota_v4 = context.session.query(qdv.Quota).filter_by( tenant_id=context.tenant_id, resource='v4_subnets_per_network').first() if tenant_quota_v4 != -1: quota.QUOTAS.limit_check( context, context.tenant_id, v4_subnets_per_network=v4_count + 1) # See RM981. The default behavior of setting a gateway unless # explicitly asked to not is no longer desirable. gateway_ip = utils.pop_param(sub_attrs, "gateway_ip") dns_ips = utils.pop_param(sub_attrs, "dns_nameservers", []) host_routes = utils.pop_param(sub_attrs, "host_routes", []) allocation_pools = utils.pop_param(sub_attrs, "allocation_pools", None) sub_attrs["network"] = net new_subnet = db_api.subnet_create(context, **sub_attrs) cidrs = [] alloc_pools = allocation_pool.AllocationPools(sub_attrs["cidr"], allocation_pools) if isinstance(allocation_pools, list): cidrs = alloc_pools.get_policy_cidrs() quota.QUOTAS.limit_check( context, context.tenant_id, alloc_pools_per_subnet=len(alloc_pools)) ip_policies.ensure_default_policy(cidrs, [new_subnet]) new_subnet["ip_policy"] = db_api.ip_policy_create(context, exclude=cidrs) quota.QUOTAS.limit_check(context, context.tenant_id, routes_per_subnet=len(host_routes)) default_route = None for route in host_routes: netaddr_route = netaddr.IPNetwork(route["destination"]) if netaddr_route.value == routes.DEFAULT_ROUTE.value: if default_route: raise q_exc.DuplicateRouteConflict( subnet_id=new_subnet["id"]) default_route = route gateway_ip = default_route["nexthop"] alloc_pools.validate_gateway_excluded(gateway_ip) new_subnet["routes"].append(db_api.route_create( context, cidr=route["destination"], gateway=route["nexthop"])) quota.QUOTAS.limit_check(context, context.tenant_id, dns_nameservers_per_subnet=len(dns_ips)) for dns_ip in dns_ips: new_subnet["dns_nameservers"].append(db_api.dns_create( context, ip=netaddr.IPAddress(dns_ip))) # if the gateway_ip is IN the cidr for the subnet and NOT excluded by # policies, we should raise a 409 conflict if gateway_ip and default_route is None: alloc_pools.validate_gateway_excluded(gateway_ip) new_subnet["routes"].append(db_api.route_create( context, cidr=str(routes.DEFAULT_ROUTE), gateway=gateway_ip)) subnet_dict = v._make_subnet_dict(new_subnet) subnet_dict["gateway_ip"] = gateway_ip n_rpc.get_notifier("network").info( context, "ip_block.create", dict(tenant_id=subnet_dict["tenant_id"], ip_block_id=subnet_dict["id"], created_at=new_subnet["created_at"])) return subnet_dict
def create_subnet(context, subnet): """Create a subnet. Create a subnet which represents a range of IP addresses that can be allocated to devices : param context: neutron api request context : param subnet: dictionary describing the subnet, with keys as listed in the RESOURCE_ATTRIBUTE_MAP object in neutron/api/v2/attributes.py. All keys will be populated. """ LOG.info("create_subnet for tenant %s" % context.tenant_id) net_id = subnet["subnet"]["network_id"] net = db_api.network_find(context, id=net_id, scope=db_api.ONE) if not net: raise exceptions.NetworkNotFound(net_id=net_id) sub_attrs = subnet["subnet"] _validate_subnet_cidr(context, net_id, sub_attrs["cidr"]) cidr = netaddr.IPNetwork(sub_attrs["cidr"]) gateway_ip = utils.pop_param(sub_attrs, "gateway_ip", str(cidr[1])) dns_ips = utils.pop_param(sub_attrs, "dns_nameservers", []) host_routes = utils.pop_param(sub_attrs, "host_routes", []) allocation_pools = utils.pop_param(sub_attrs, "allocation_pools", []) sub_attrs["network"] = net new_subnet = db_api.subnet_create(context, **sub_attrs) default_route = None for route in host_routes: netaddr_route = netaddr.IPNetwork(route["destination"]) if netaddr_route.value == routes.DEFAULT_ROUTE.value: default_route = route gateway_ip = default_route["nexthop"] new_subnet["routes"].append( db_api.route_create(context, cidr=route["destination"], gateway=route["nexthop"])) if default_route is None: new_subnet["routes"].append( db_api.route_create(context, cidr=str(routes.DEFAULT_ROUTE), gateway=gateway_ip)) for dns_ip in dns_ips: new_subnet["dns_nameservers"].append( db_api.dns_create(context, ip=netaddr.IPAddress(dns_ip))) if allocation_pools: exclude = netaddr.IPSet([cidr]) for p in allocation_pools: x = netaddr.IPSet(netaddr.IPRange(p["start"], p["end"])) exclude = exclude - x new_subnet["ip_policy"] = db_api.ip_policy_create(context, exclude=exclude) subnet_dict = v._make_subnet_dict(new_subnet, default_route=routes.DEFAULT_ROUTE) subnet_dict["gateway_ip"] = gateway_ip return subnet_dict
def create_network(context, network): """Create a network. Create a network which represents an L2 network segment which can have a set of subnets and ports associated with it. : param context: neutron api request context : param network: dictionary describing the network, with keys as listed in the RESOURCE_ATTRIBUTE_MAP object in neutron/api/v2/attributes.py. All keys will be populated. """ LOG.info("create_network for tenant %s" % context.tenant_id) with context.session.begin(): net_attrs = network["network"] subs = net_attrs.pop("subnets", []) # Enforce subnet quotas if not context.is_admin: if len(subs) > 0: v4_count, v6_count = 0, 0 for s in subs: version = netaddr.IPNetwork(s['subnet']['cidr']).version if version == 6: v6_count += 1 else: v4_count += 1 if v4_count > 0: tenant_q_v4 = context.session.query(qdv.Quota).filter_by( tenant_id=context.tenant_id, resource='v4_subnets_per_network').first() if tenant_q_v4 != -1: quota.QUOTAS.limit_check( context, context.tenant_id, v4_subnets_per_network=v4_count) if v6_count > 0: tenant_q_v6 = context.session.query(qdv.Quota).filter_by( tenant_id=context.tenant_id, resource='v6_subnets_per_network').first() if tenant_q_v6 != -1: quota.QUOTAS.limit_check( context, context.tenant_id, v6_subnets_per_network=v6_count) # Generate a uuid that we're going to hand to the backend and db net_uuid = utils.pop_param(net_attrs, "id", None) net_type = None if net_uuid and context.is_admin: net = db_api.network_find(context=context, limit=None, sorts=['id'], marker=None, page_reverse=False, id=net_uuid, scope=db_api.ONE) net_type = utils.pop_param(net_attrs, "network_plugin", None) if net: raise q_exc.NetworkAlreadyExists(id=net_uuid) else: net_uuid = uuidutils.generate_uuid() # TODO(mdietz) this will be the first component registry hook, but # lets make it work first pnet_type, phys_net, seg_id = _adapt_provider_nets(context, network) ipam_strategy = utils.pop_param(net_attrs, "ipam_strategy", None) if not ipam_strategy or not context.is_admin: ipam_strategy = CONF.QUARK.default_ipam_strategy if not ipam.IPAM_REGISTRY.is_valid_strategy(ipam_strategy): raise q_exc.InvalidIpamStrategy(strat=ipam_strategy) net_attrs["ipam_strategy"] = ipam_strategy # NOTE(mdietz) I think ideally we would create the providernet # elsewhere as a separate driver step that could be # kept in a plugin and completely removed if desired. We could # have a pre-callback/observer on the netdriver create_network # that gathers any additional parameters from the network dict default_net_type = net_type or CONF.QUARK.default_network_type net_driver = registry.DRIVER_REGISTRY.get_driver(default_net_type) net_driver.create_network(context, net_attrs["name"], network_id=net_uuid, phys_type=pnet_type, phys_net=phys_net, segment_id=seg_id) net_attrs["id"] = net_uuid net_attrs["tenant_id"] = context.tenant_id net_attrs["network_plugin"] = default_net_type new_net = db_api.network_create(context, **net_attrs) new_subnets = [] for sub in subs: sub["subnet"]["network_id"] = new_net["id"] sub["subnet"]["tenant_id"] = context.tenant_id s = db_api.subnet_create(context, **sub["subnet"]) new_subnets.append(s) new_net["subnets"] = new_subnets # if not security_groups.get_security_groups( # context, # filters={"id": security_groups.DEFAULT_SG_UUID}): # security_groups._create_default_security_group(context) return v._make_network_dict(new_net)
def create_network(context, network): """Create a network. Create a network which represents an L2 network segment which can have a set of subnets and ports associated with it. : param context: neutron api request context : param network: dictionary describing the network, with keys as listed in the RESOURCE_ATTRIBUTE_MAP object in neutron/api/v2/attributes.py. All keys will be populated. """ LOG.info("create_network for tenant %s" % context.tenant_id) with context.session.begin(): net_attrs = network["network"] subs = net_attrs.pop("subnets", []) # Enforce subnet quotas if not context.is_admin: if len(subs) > 0: v4_count, v6_count = 0, 0 for s in subs: version = netaddr.IPNetwork(s['subnet']['cidr']).version if version == 6: v6_count += 1 else: v4_count += 1 if v4_count > 0: tenant_q_v4 = context.session.query(qdb.Quota).filter_by( tenant_id=context.tenant_id, resource='v4_subnets_per_network').first() if tenant_q_v4 != -1: quota.QUOTAS.limit_check( context, context.tenant_id, v4_subnets_per_network=v4_count) if v6_count > 0: tenant_q_v6 = context.session.query(qdb.Quota).filter_by( tenant_id=context.tenant_id, resource='v6_subnets_per_network').first() if tenant_q_v6 != -1: quota.QUOTAS.limit_check( context, context.tenant_id, v6_subnets_per_network=v6_count) # Generate a uuid that we're going to hand to the backend and db net_uuid = utils.pop_param(net_attrs, "id", None) net_type = None if net_uuid and context.is_admin: net = db_api.network_find(context, id=net_uuid, scope=db_api.ONE) net_type = utils.pop_param(net_attrs, "network_plugin", None) if net: raise q_exc.NetworkAlreadyExists(id=net_uuid) else: net_uuid = uuidutils.generate_uuid() # TODO(mdietz) this will be the first component registry hook, but # lets make it work first pnet_type, phys_net, seg_id = _adapt_provider_nets(context, network) ipam_strategy = utils.pop_param(net_attrs, "ipam_strategy", None) if not ipam_strategy or not context.is_admin: ipam_strategy = CONF.QUARK.default_ipam_strategy if not ipam.IPAM_REGISTRY.is_valid_strategy(ipam_strategy): raise q_exc.InvalidIpamStrategy(strat=ipam_strategy) net_attrs["ipam_strategy"] = ipam_strategy # NOTE(mdietz) I think ideally we would create the providernet # elsewhere as a separate driver step that could be # kept in a plugin and completely removed if desired. We could # have a pre-callback/observer on the netdriver create_network # that gathers any additional parameters from the network dict default_net_type = net_type or CONF.QUARK.default_network_type net_driver = registry.DRIVER_REGISTRY.get_driver(default_net_type) net_driver.create_network(context, net_attrs["name"], network_id=net_uuid, phys_type=pnet_type, phys_net=phys_net, segment_id=seg_id) net_attrs["id"] = net_uuid net_attrs["tenant_id"] = context.tenant_id net_attrs["network_plugin"] = default_net_type new_net = db_api.network_create(context, **net_attrs) new_subnets = [] for sub in subs: sub["subnet"]["network_id"] = new_net["id"] sub["subnet"]["tenant_id"] = context.tenant_id s = db_api.subnet_create(context, **sub["subnet"]) new_subnets.append(s) new_net["subnets"] = new_subnets # if not security_groups.get_security_groups( # context, # filters={"id": security_groups.DEFAULT_SG_UUID}): # security_groups._create_default_security_group(context) return v._make_network_dict(new_net)
def create_subnet(context, subnet): """Create a subnet. Create a subnet which represents a range of IP addresses that can be allocated to devices : param context: neutron api request context : param subnet: dictionary describing the subnet, with keys as listed in the RESOURCE_ATTRIBUTE_MAP object in neutron/api/v2/attributes.py. All keys will be populated. """ LOG.info("create_subnet for tenant %s" % context.tenant_id) net_id = subnet["subnet"]["network_id"] with context.session.begin(): net = db_api.network_find(context, id=net_id, scope=db_api.ONE) if not net: raise exceptions.NetworkNotFound(net_id=net_id) sub_attrs = subnet["subnet"] _validate_subnet_cidr(context, net_id, sub_attrs["cidr"]) cidr = netaddr.IPNetwork(sub_attrs["cidr"]) gateway_ip = utils.pop_param(sub_attrs, "gateway_ip", str(cidr[1])) dns_ips = utils.pop_param(sub_attrs, "dns_nameservers", []) host_routes = utils.pop_param(sub_attrs, "host_routes", []) allocation_pools = utils.pop_param(sub_attrs, "allocation_pools", None) sub_attrs["network"] = net new_subnet = db_api.subnet_create(context, **sub_attrs) default_route = None for route in host_routes: netaddr_route = netaddr.IPNetwork(route["destination"]) if netaddr_route.value == routes.DEFAULT_ROUTE.value: default_route = route gateway_ip = default_route["nexthop"] new_subnet["routes"].append(db_api.route_create( context, cidr=route["destination"], gateway=route["nexthop"])) if default_route is None: new_subnet["routes"].append(db_api.route_create( context, cidr=str(routes.DEFAULT_ROUTE), gateway=gateway_ip)) for dns_ip in dns_ips: new_subnet["dns_nameservers"].append(db_api.dns_create( context, ip=netaddr.IPAddress(dns_ip))) if isinstance(allocation_pools, list): ranges = [] cidrset = netaddr.IPSet([netaddr.IPNetwork(new_subnet["cidr"])]) for p in allocation_pools: cidrset -= netaddr.IPSet(netaddr.IPRange(p["start"], p["end"])) non_allocation_pools = v._pools_from_cidr(cidrset) for p in non_allocation_pools: r = netaddr.IPRange(p["start"], p["end"]) ranges.append(dict( length=len(r), offset=int(r[0]) - int(cidr[0]))) new_subnet["ip_policy"] = db_api.ip_policy_create(context, exclude=ranges) subnet_dict = v._make_subnet_dict(new_subnet, default_route=routes.DEFAULT_ROUTE) subnet_dict["gateway_ip"] = gateway_ip notifier_api.notify(context, notifier_api.publisher_id("network"), "ip_block.create", notifier_api.CONF.default_notification_level, dict(tenant_id=subnet_dict["tenant_id"], ip_block_id=subnet_dict["id"], created_at=new_subnet["created_at"])) return subnet_dict
def create_subnet(context, subnet): """Create a subnet. Create a subnet which represents a range of IP addresses that can be allocated to devices : param context: neutron api request context : param subnet: dictionary describing the subnet, with keys as listed in the RESOURCE_ATTRIBUTE_MAP object in neutron/api/v2/attributes.py. All keys will be populated. """ LOG.info("create_subnet for tenant %s" % context.tenant_id) net_id = subnet["subnet"]["network_id"] with context.session.begin(): net = db_api.network_find(context, None, None, None, False, id=net_id, scope=db_api.ONE) if not net: raise exceptions.NetworkNotFound(net_id=net_id) sub_attrs = subnet["subnet"] always_pop = [ "enable_dhcp", "ip_version", "first_ip", "last_ip", "_cidr" ] admin_only = [ "segment_id", "do_not_use", "created_at", "next_auto_assign_ip" ] utils.filter_body(context, sub_attrs, admin_only, always_pop) _validate_subnet_cidr(context, net_id, sub_attrs["cidr"]) cidr = netaddr.IPNetwork(sub_attrs["cidr"]) err_vals = {'cidr': sub_attrs["cidr"], 'network_id': net_id} err = _("Requested subnet with cidr: %(cidr)s for " "network: %(network_id)s. Prefix is too small, must be a " "larger subnet. A prefix less than /%(prefix)s is required.") if cidr.version == 6 and cidr.prefixlen > 64: err_vals["prefix"] = 65 err_msg = err % err_vals raise exceptions.InvalidInput(error_message=err_msg) elif cidr.version == 4 and cidr.prefixlen > 30: err_vals["prefix"] = 31 err_msg = err % err_vals raise exceptions.InvalidInput(error_message=err_msg) # Enforce subnet quotas net_subnets = get_subnets(context, filters=dict(network_id=net_id)) if not context.is_admin: v4_count, v6_count = 0, 0 for subnet in net_subnets: if netaddr.IPNetwork(subnet['cidr']).version == 6: v6_count += 1 else: v4_count += 1 if cidr.version == 6: tenant_quota_v6 = context.session.query(qdv.Quota).filter_by( tenant_id=context.tenant_id, resource='v6_subnets_per_network').first() if tenant_quota_v6 != -1: quota.QUOTAS.limit_check(context, context.tenant_id, v6_subnets_per_network=v6_count + 1) else: tenant_quota_v4 = context.session.query(qdv.Quota).filter_by( tenant_id=context.tenant_id, resource='v4_subnets_per_network').first() if tenant_quota_v4 != -1: quota.QUOTAS.limit_check(context, context.tenant_id, v4_subnets_per_network=v4_count + 1) # See RM981. The default behavior of setting a gateway unless # explicitly asked to not is no longer desirable. gateway_ip = utils.pop_param(sub_attrs, "gateway_ip") dns_ips = utils.pop_param(sub_attrs, "dns_nameservers", []) host_routes = utils.pop_param(sub_attrs, "host_routes", []) allocation_pools = utils.pop_param(sub_attrs, "allocation_pools", None) sub_attrs["network"] = net new_subnet = db_api.subnet_create(context, **sub_attrs) cidrs = [] alloc_pools = allocation_pool.AllocationPools(sub_attrs["cidr"], allocation_pools) if isinstance(allocation_pools, list): cidrs = alloc_pools.get_policy_cidrs() quota.QUOTAS.limit_check(context, context.tenant_id, alloc_pools_per_subnet=len(alloc_pools)) ip_policies.ensure_default_policy(cidrs, [new_subnet]) new_subnet["ip_policy"] = db_api.ip_policy_create(context, exclude=cidrs) quota.QUOTAS.limit_check(context, context.tenant_id, routes_per_subnet=len(host_routes)) default_route = None for route in host_routes: netaddr_route = netaddr.IPNetwork(route["destination"]) if netaddr_route.value == routes.DEFAULT_ROUTE.value: if default_route: raise q_exc.DuplicateRouteConflict( subnet_id=new_subnet["id"]) default_route = route gateway_ip = default_route["nexthop"] alloc_pools.validate_gateway_excluded(gateway_ip) new_subnet["routes"].append( db_api.route_create(context, cidr=route["destination"], gateway=route["nexthop"])) quota.QUOTAS.limit_check(context, context.tenant_id, dns_nameservers_per_subnet=len(dns_ips)) for dns_ip in dns_ips: new_subnet["dns_nameservers"].append( db_api.dns_create(context, ip=netaddr.IPAddress(dns_ip))) # if the gateway_ip is IN the cidr for the subnet and NOT excluded by # policies, we should raise a 409 conflict if gateway_ip and default_route is None: alloc_pools.validate_gateway_excluded(gateway_ip) new_subnet["routes"].append( db_api.route_create(context, cidr=str(routes.DEFAULT_ROUTE), gateway=gateway_ip)) subnet_dict = v._make_subnet_dict(new_subnet) subnet_dict["gateway_ip"] = gateway_ip n_rpc.get_notifier("network").info( context, "ip_block.create", dict(tenant_id=subnet_dict["tenant_id"], ip_block_id=subnet_dict["id"], created_at=new_subnet["created_at"])) return subnet_dict