def create(self, req, body): if not body: raise exc.HTTPUnprocessableEntity() context = req.environ["nova.context"] authorize(context) network = body["network"] keys = ["cidr", "cidr_v6", "ipam", "vlan_start", "network_size", "num_networks"] kwargs = {k: network.get(k) for k in keys} if not network.get("label"): msg = _("Network label is required") raise exc.HTTPBadRequest(explanation=msg) label = network["label"] if not (kwargs["cidr"] or kwargs["cidr_v6"]): msg = _("No CIDR requested") raise exc.HTTPBadRequest(explanation=msg) if kwargs["cidr"]: try: net = netaddr.IPNetwork(kwargs["cidr"]) if net.size < 4: msg = _("Requested network does not contain " "enough (2+) usable hosts") raise exc.HTTPBadRequest(explanation=msg) except netexc.AddrFormatError: msg = _("CIDR is malformed.") raise exc.HTTPBadRequest(explanation=msg) except netexc.AddrConversionError: msg = _("Address could not be converted.") raise exc.HTTPBadRequest(explanation=msg) networks = [] try: if CONF.enable_network_quota: reservation = QUOTAS.reserve(context, networks=1) except exception.OverQuota: msg = _("Quota exceeded, too many networks.") raise exc.HTTPBadRequest(explanation=msg) kwargs['project_id'] = context.project_id try: networks = self.network_api.create(context, label=label, **kwargs) if CONF.enable_network_quota: QUOTAS.commit(context, reservation) except exception.PolicyNotAuthorized as e: raise exc.HTTPForbidden(explanation=six.text_type(e)) except exception.CidrConflict as e: raise exc.HTTPConflict(explanation=e.format_message()) except Exception: if CONF.enable_network_quota: QUOTAS.rollback(context, reservation) msg = _("Create networks failed") LOG.exception(msg, extra=network) raise exc.HTTPServiceUnavailable(explanation=msg) return {"network": network_dict(networks[0])}
def network_dict(network): # NOTE(danms): Here, network should be an object, which could have come # from neutron and thus be missing most of the attributes. Providing a # default to get() avoids trying to lazy-load missing attributes. return {"id": network.get("uuid", None) or network.get("id", None), "cidr": str(network.get("cidr", None)), "label": network.get("label", None)}
def _get_requested_networks(self, requested_networks): """Create a list of requested networks from the networks attribute.""" networks = [] network_uuids = [] for network in requested_networks: request = objects.NetworkRequest() try: try: request.port_id = network.get('port', None) except ValueError: msg = _("Bad port format: port uuid is " "not in proper format " "(%s)") % network.get('port') raise exc.HTTPBadRequest(explanation=msg) if request.port_id: request.network_id = None if not utils.is_neutron(): # port parameter is only for neutron v2.0 msg = _("Unknown argument : port") raise exc.HTTPBadRequest(explanation=msg) else: request.network_id = network['uuid'] if (not request.port_id and not uuidutils.is_uuid_like(request.network_id)): br_uuid = request.network_id.split('-', 1)[-1] if not uuidutils.is_uuid_like(br_uuid): msg = _("Bad networks format: network uuid is " "not in proper format " "(%s)") % request.network_id raise exc.HTTPBadRequest(explanation=msg) # fixed IP address is optional # if the fixed IP address is not provided then # it will use one of the available IP address from the network try: request.address = network.get('fixed_ip', None) except ValueError: msg = _("Invalid fixed IP address (%s)") % request.address raise exc.HTTPBadRequest(explanation=msg) if (request.network_id and request.network_id in network_uuids): expl = (_("Duplicate networks" " (%s) are not allowed") % request.network_id) raise exc.HTTPBadRequest(explanation=expl) network_uuids.append(request.network_id) networks.append(request) except KeyError as key: expl = _('Bad network format: missing %s') % key raise exc.HTTPBadRequest(explanation=expl) except TypeError: expl = _('Bad networks format') raise exc.HTTPBadRequest(explanation=expl) return objects.NetworkRequestList(objects=networks)
def get_networks_for_instance(context, instance): """Returns a prepared nw_info list for passing into the view builders We end up with a data structure like: {'public': {'ips': [{'addr': '10.0.0.1', 'version': 4}, {'addr': '2001::1', 'version': 6}], 'floating_ips': [{'addr': '172.16.0.1', 'version': 4}, {'addr': '172.16.2.1', 'version': 4}]}, ...} """ def _emit_addr(ip, version): return {'addr': ip, 'version': version} networks = {} fixed_ips = instance['fixed_ips'] ipv6_addrs_seen = {} for fixed_ip in fixed_ips: fixed_addr = fixed_ip['address'] network = fixed_ip['network'] vif = fixed_ip.get('virtual_interface') if not network or not vif: name = instance['name'] ip = fixed_ip['address'] LOG.warn(_("Instance %(name)s has stale IP " "address: %(ip)s (no network or vif)") % locals()) continue label = network.get('label', None) if label is None: continue if label not in networks: networks[label] = {'ips': [], 'floating_ips': []} nw_dict = networks[label] cidr_v6 = network.get('cidr_v6') if FLAGS.use_ipv6 and cidr_v6: ipv6_addr = ipv6.to_global(cidr_v6, vif['address'], network['project_id']) # Only add same IPv6 address once. It's possible we've # seen it before if there was a previous fixed_ip with # same network and vif as this one if not ipv6_addrs_seen.get(ipv6_addr): nw_dict['ips'].append(_emit_addr(ipv6_addr, 6)) ipv6_addrs_seen[ipv6_addr] = True nw_dict['ips'].append(_emit_addr(fixed_addr, 4)) for floating_ip in fixed_ip.get('floating_ips', []): float_addr = floating_ip['address'] nw_dict['floating_ips'].append(_emit_addr(float_addr, 4)) return networks
def create(self, req, body): context = req.environ["nova.context"] context.can(tn_policies.BASE_POLICY_NAME) network = body["network"] keys = [ "cidr", "cidr_v6", "ipam", "vlan_start", "network_size", "num_networks" ] kwargs = {k: network.get(k) for k in keys} label = network["label"] if kwargs["cidr"]: try: net = netaddr.IPNetwork(kwargs["cidr"]) if net.size < 4: msg = _("Requested network does not contain " "enough (2+) usable hosts") raise exc.HTTPBadRequest(explanation=msg) except netexc.AddrConversionError: msg = _("Address could not be converted.") raise exc.HTTPBadRequest(explanation=msg) try: if CONF.enable_network_quota: objects.Quotas.check_deltas(context, {'networks': 1}, context.project_id) except exception.OverQuota: msg = _("Quota exceeded, too many networks.") raise exc.HTTPForbidden(explanation=msg) kwargs['project_id'] = context.project_id try: networks = self.network_api.create(context, label=label, **kwargs) except exception.PolicyNotAuthorized as e: raise exc.HTTPForbidden(explanation=six.text_type(e)) except exception.CidrConflict as e: raise exc.HTTPConflict(explanation=e.format_message()) except Exception: msg = _("Create networks failed") LOG.exception(msg, extra=network) raise exc.HTTPServiceUnavailable(explanation=msg) # NOTE(melwitt): We recheck the quota after creating the object to # prevent users from allocating more resources than their allowed quota # in the event of a race. This is configurable because it can be # expensive if strict quota limits are not required in a deployment. if CONF.quota.recheck_quota and CONF.enable_network_quota: try: objects.Quotas.check_deltas(context, {'networks': 0}, context.project_id) except exception.OverQuota: self.network_api.delete(context, network_dict(networks[0])['id']) msg = _("Quota exceeded, too many networks.") raise exc.HTTPForbidden(explanation=msg) return {"network": network_dict(networks[0])}
def create(self, req, body): context = req.environ["nova.context"] context.can(tn_policies.BASE_POLICY_NAME) network = body["network"] keys = ["cidr", "cidr_v6", "ipam", "vlan_start", "network_size", "num_networks"] kwargs = {k: network.get(k) for k in keys} label = network["label"] if kwargs["cidr"]: try: net = netaddr.IPNetwork(kwargs["cidr"]) if net.size < 4: msg = _("Requested network does not contain " "enough (2+) usable hosts") raise exc.HTTPBadRequest(explanation=msg) except netexc.AddrConversionError: msg = _("Address could not be converted.") raise exc.HTTPBadRequest(explanation=msg) try: if CONF.enable_network_quota: objects.Quotas.check_deltas(context, {'networks': 1}, context.project_id) except exception.OverQuota: msg = _("Quota exceeded, too many networks.") raise exc.HTTPForbidden(explanation=msg) kwargs['project_id'] = context.project_id try: networks = self.network_api.create(context, label=label, **kwargs) except exception.PolicyNotAuthorized as e: raise exc.HTTPForbidden(explanation=six.text_type(e)) except exception.CidrConflict as e: raise exc.HTTPConflict(explanation=e.format_message()) except Exception: msg = _("Create networks failed") LOG.exception(msg, extra=network) raise exc.HTTPServiceUnavailable(explanation=msg) # NOTE(melwitt): We recheck the quota after creating the object to # prevent users from allocating more resources than their allowed quota # in the event of a race. This is configurable because it can be # expensive if strict quota limits are not required in a deployment. if CONF.quota.recheck_quota and CONF.enable_network_quota: try: objects.Quotas.check_deltas(context, {'networks': 0}, context.project_id) except exception.OverQuota: self.network_api.delete(context, network_dict(networks[0])['id']) msg = _("Quota exceeded, too many networks.") raise exc.HTTPForbidden(explanation=msg) return {"network": network_dict(networks[0])}
def network_dict(context, network, extended): fields = ('id', 'cidr', 'netmask', 'gateway', 'broadcast', 'dns1', 'dns2', 'cidr_v6', 'gateway_v6', 'label', 'netmask_v6', 'description', 'range_start', 'range_end') admin_fields = ('created_at', 'updated_at', 'deleted_at', 'deleted', 'injected', 'bridge', 'vlan', 'vpn_public_address', 'vpn_public_port', 'vpn_private_address', 'dhcp_start', 'project_id', 'host', 'bridge_interface', 'multi_host', 'priority', 'rxtx_base') if network: # NOTE(mnaser): We display a limited set of fields so users can know # what networks are available, extra system-only fields # are only visible if they are an admin. if context.is_admin: fields += admin_fields if extended: fields += extended_fields # TODO(mriedem): Remove the NovaObject type check once the # network.create API is returning objects. is_obj = isinstance(network, base_obj.NovaObject) result = {} for field in fields: # NOTE(mriedem): If network is an object, IPAddress fields need to # be cast to a string so they look the same in the response as # before the objects conversion. if is_obj and isinstance(network.fields[field].AUTO_TYPE, obj_fields.IPAddress): # NOTE(danms): Here, network should be an object, which could # have come from neutron and thus be missing most of the # attributes. Providing a default to get() avoids trying to # lazy-load missing attributes. val = network.get(field, None) if val is not None: result[field] = str(val) else: result[field] = val else: # It's either not an object or it's not an IPAddress field. result[field] = network.get(field, None) uuid = network.get('uuid') if uuid: result['id'] = uuid return result else: return {}
def network_dict(context, network, extended): fields = ('id', 'cidr', 'netmask', 'gateway', 'broadcast', 'dns1', 'dns2', 'cidr_v6', 'gateway_v6', 'label', 'netmask_v6') admin_fields = ('created_at', 'updated_at', 'deleted_at', 'deleted', 'injected', 'bridge', 'vlan', 'vpn_public_address', 'vpn_public_port', 'vpn_private_address', 'dhcp_start', 'project_id', 'host', 'bridge_interface', 'multi_host', 'priority', 'rxtx_base') if network: # NOTE(mnaser): We display a limited set of fields so users can know # what networks are available, extra system-only fields # are only visible if they are an admin. if context.is_admin: fields += admin_fields if extended: fields += extended_fields # TODO(mriedem): Remove the NovaObject type check once the # network.create API is returning objects. is_obj = isinstance(network, base_obj.NovaObject) result = {} for field in fields: # NOTE(mriedem): If network is an object, IPAddress fields need to # be cast to a string so they look the same in the response as # before the objects conversion. if is_obj and isinstance(network.fields[field].AUTO_TYPE, obj_fields.IPAddress): # NOTE(danms): Here, network should be an object, which could # have come from neutron and thus be missing most of the # attributes. Providing a default to get() avoids trying to # lazy-load missing attributes. val = network.get(field, None) if val is not None: result[field] = str(val) else: result[field] = val else: # It's either not an object or it's not an IPAddress field. result[field] = network.get(field, None) uuid = network.get('uuid') if uuid: result['id'] = uuid return result else: return {}
def network_dict(context, network): fields = ('id', 'cidr', 'netmask', 'gateway', 'broadcast', 'dns1', 'dns2', 'cidr_v6', 'gateway_v6', 'label', 'netmask_v6') admin_fields = ('created_at', 'updated_at', 'deleted_at', 'deleted', 'injected', 'bridge', 'vlan', 'vpn_public_address', 'vpn_public_port', 'vpn_private_address', 'dhcp_start', 'project_id', 'host', 'bridge_interface', 'multi_host', 'priority', 'rxtx_base') if network: # NOTE(mnaser): We display a limited set of fields so users can know # what networks are available, extra system-only fields # are only visible if they are an admin. if context.is_admin: fields += admin_fields result = dict((field, network.get(field)) for field in fields) uuid = network.get('uuid') if uuid: result['id'] = uuid return result else: return {}
def network_dict(context, network, extended): fields = ('id', 'cidr', 'netmask', 'gateway', 'broadcast', 'dns1', 'dns2', 'cidr_v6', 'gateway_v6', 'label', 'netmask_v6') admin_fields = ('created_at', 'updated_at', 'deleted_at', 'deleted', 'injected', 'bridge', 'vlan', 'vpn_public_address', 'vpn_public_port', 'vpn_private_address', 'dhcp_start', 'project_id', 'host', 'bridge_interface', 'multi_host', 'priority', 'rxtx_base') if network: # NOTE(mnaser): We display a limited set of fields so users can know # what networks are available, extra system-only fields # are only visible if they are an admin. if context.is_admin: fields += admin_fields if extended: fields += extended_fields # TODO(mriedem): Remove the NovaObject type check once the # neutronv2 API is returning Network objects from get/get_all. is_obj = isinstance(network, base_obj.NovaObject) result = {} for field in fields: # NOTE(mriedem): If network is an object, IPAddress fields need to # be cast to a string so they look the same in the response as # before the objects conversion. if is_obj and isinstance(network.fields[field].AUTO_TYPE, obj_fields.IPAddress): val = network.get(field) if val is not None: result[field] = str(network.get(field)) else: result[field] = val else: # It's either not an object or it's not an IPAddress field. result[field] = network.get(field) uuid = network.get('uuid') if uuid: result['id'] = uuid return result else: return {}
def network_dict(context, network): fields = ('id', 'cidr', 'netmask', 'gateway', 'broadcast', 'dns1', 'dns2', 'cidr_v6', 'gateway_v6', 'label', 'netmask_v6') admin_fields = ('created_at', 'updated_at', 'deleted_at', 'deleted', 'injected', 'bridge', 'vlan', 'vpn_public_address', 'vpn_public_port', 'vpn_private_address', 'dhcp_start', 'project_id', 'host', 'bridge_interface', 'multi_host', 'priority', 'rxtx_base', 'mtu', 'dhcp_server', 'enable_dhcp', 'share_address') if network: # NOTE(mnaser): We display a limited set of fields so users can know # what networks are available, extra system-only fields # are only visible if they are an admin. if context.is_admin: fields += admin_fields # TODO(mriedem): Remove the NovaObject type check once the # neutronv2 API is returning Network objects from get/get_all. is_obj = isinstance(network, base_obj.NovaObject) result = {} for field in fields: # NOTE(mriedem): If network is an object, IPAddress fields need to # be cast to a string so they look the same in the response as # before the objects conversion. if is_obj and isinstance(network.fields[field].AUTO_TYPE, obj_fields.IPAddress): val = network.get(field) if val is not None: result[field] = str(network.get(field)) else: result[field] = val else: # It's either not an object or it's not an IPAddress field. result[field] = network.get(field) uuid = network.get('uuid') if uuid: result['id'] = uuid return result else: return {}
def _get_requested_networks(self, requested_networks): """ Create a list of requested networks from the networks attribute """ networks = [] for network in requested_networks: try: network_uuid = network['uuid'] if not utils.is_uuid_like(network_uuid): msg = _("Bad networks format: network uuid is not in" " proper format (%s)") % network_uuid raise exc.HTTPBadRequest(explanation=msg) #fixed IP address is optional #if the fixed IP address is not provided then #it will use one of the available IP address from the network address = network.get('fixed_ip', None) if address is not None and not utils.is_valid_ipv4(address): msg = _("Invalid fixed IP address (%s)") % address raise exc.HTTPBadRequest(explanation=msg) # check if the network id is already present in the list, # we don't want duplicate networks to be passed # at the boot time for id, ip in networks: if id == network_uuid: expl = _("Duplicate networks (%s) are not allowed")\ % network_uuid raise exc.HTTPBadRequest(explanation=expl) networks.append((network_uuid, address)) except KeyError as key: expl = _('Bad network format: missing %s') % key raise exc.HTTPBadRequest(explanation=expl) except TypeError: expl = _('Bad networks format') raise exc.HTTPBadRequest(explanation=expl) return networks
def network_dict(context, network): fields = ( "id", "cidr", "netmask", "gateway", "broadcast", "dns1", "dns2", "cidr_v6", "gateway_v6", "label", "netmask_v6", ) admin_fields = ( "created_at", "updated_at", "deleted_at", "deleted", "injected", "bridge", "vlan", "vpn_public_address", "vpn_public_port", "vpn_private_address", "dhcp_start", "project_id", "host", "bridge_interface", "multi_host", "priority", "rxtx_base", "mtu", "dhcp_server", "enable_dhcp", "share_address", ) if network: # NOTE(mnaser): We display a limited set of fields so users can know # what networks are available, extra system-only fields # are only visible if they are an admin. if context.is_admin: fields += admin_fields # TODO(mriedem): Remove the NovaObject type check once the # network.create API is returning objects. is_obj = isinstance(network, base_obj.NovaObject) result = {} for field in fields: # NOTE(mriedem): If network is an object, IPAddress fields need to # be cast to a string so they look the same in the response as # before the objects conversion. if is_obj and isinstance(network.fields[field].AUTO_TYPE, obj_fields.IPAddress): # NOTE(danms): Here, network should be an object, which could # have come from neutron and thus be missing most of the # attributes. Providing a default to get() avoids trying to # lazy-load missing attributes. val = network.get(field, None) if val is not None: result[field] = str(val) else: result[field] = val else: # It's either not an object or it's not an IPAddress field. result[field] = network.get(field, None) uuid = network.get("uuid") if uuid: result["id"] = uuid return result else: return {}
def network_dict(network): return { "id": network.get("uuid") or network.get("id"), "cidr": network.get("cidr"), "label": network.get("label") }
def network_dict(network): return {"id": network.get("uuid") or network.get("id"), "cidr": network.get("cidr"), "label": network.get("label")}
def network_dict(network): return { "id": network.get("uuid") or network["id"], "cidr": network["cidr"], "label": network["label"] }
def network_dict(network): return {"id": network.get("uuid") or network["id"], "cidr": network["cidr"], "label": network["label"]}