desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Notify all the agents that are hosting the routers'
def _notification(self, context, method, routers, operation, data):
plugin = manager.QuantumManager.get_plugin() if utils.is_extension_supported(plugin, constants.AGENT_SCHEDULER_EXT_ALIAS): adminContext = ((context.is_admin and context) or context.elevated()) plugin.schedule_routers(adminContext, routers) self._agent_notification(context, method, router...
'Fanout the deleted router to all L3 agents'
def _notification_fanout(self, context, method, router_id):
LOG.debug(_('Fanout notify agent at %(topic)s the message %(method)s on router %(router_id)s'), {'topic': topics.DHCP_AGENT, 'method': method, 'router_id': router_id}) self.fanout_cast(context, self.make_msg(method, router_id=router_id), topic=topics.L3_AGENT)
'Notify the agent on host'
def _notification_host(self, context, method, payload, host):
self.cast(context, self.make_msg(method, payload=payload), topic=('%s.%s' % (topics.DHCP_AGENT, host)))
'Notify all the agents that are hosting the network'
def _notification(self, context, method, payload, network_id):
plugin = manager.QuantumManager.get_plugin() if ((method != 'network_delete_end') and utils.is_extension_supported(plugin, constants.AGENT_SCHEDULER_EXT_ALIAS)): if (method == 'port_create_end'): adminContext = (context if context.is_admin else context.elevated()) network = plugi...
'Fanout the payload to all dhcp agents'
def _notification_fanout(self, context, method, payload):
self.fanout_cast(context, self.make_msg(method, payload=payload), topic=topics.DHCP_AGENT)
'The __subclasshook__ method is a class method that will be called everytime a class is tested using issubclass(klass, PluginInterface). In that case, it will check that every method marked with the abstractmethod decorator is provided by the plugin class.'
@classmethod def __subclasshook__(cls, klass):
for method in cls.__abstractmethods__: if any(((method in base.__dict__) for base in klass.__mro__)): continue return NotImplemented return True
'The name of the extension. e.g. \'Fox In Socks\''
def get_name(self):
raise NotImplementedError()
'The alias for the extension. e.g. \'FOXNSOX\''
def get_alias(self):
raise NotImplementedError()
'Friendly description for the extension. e.g. \'The Fox In Socks Extension\''
def get_description(self):
raise NotImplementedError()
'The XML namespace for the extension. e.g. \'http://www.fox.in.socks/api/ext/pie/v1.0\''
def get_namespace(self):
raise NotImplementedError()
'The timestamp when the extension was last updated. e.g. \'2011-01-22T13:25:27-06:00\''
def get_updated(self):
raise NotImplementedError()
'List of extensions.ResourceExtension extension objects. Resources define new nouns, and are accessible through URLs.'
def get_resources(self):
resources = [] return resources
'List of extensions.ActionExtension extension objects. Actions are verbs callable from the API.'
def get_actions(self):
actions = [] return actions
'List of extensions.RequestException extension objects. Request extensions are used to handle custom request data.'
def get_request_extensions(self):
request_exts = [] return request_exts
'retrieve extended resources or attributes for core resources. Extended attributes are implemented by a core plugin similarly to the attributes defined in the core, and can appear in request and response messages. Their names are scoped with the extension\'s prefix. The core API version is passed to this function, whic...
def get_extended_resources(self, version):
return {}
'Returns an abstract class which defines contract for the plugin. The abstract class should inherit from extesnions.PluginInterface, Methods in this abstract class should be decorated as abstractmethod'
def get_plugin_interface(self):
return None
'Update attributes map for this extension This is default method for extending an extension\'s attributes map. An extension can use this method and supplying its own resource attribute map in extension_attrs_map argument to extend all its attributes that needs to be extended. If an extension does not implement update_a...
def update_attributes_map(self, extended_attributes, extension_attrs_map=None):
if (not extension_attrs_map): return for (resource, attrs) in extension_attrs_map.iteritems(): extended_attrs = extended_attributes.get(resource) if extended_attrs: attrs.update(extended_attrs)
'Paste factory.'
@classmethod def factory(cls, global_config, **local_config):
def _factory(app): return cls(app, global_config, **local_config) return _factory
'Return a dict of ActionExtensionController-s by collection.'
def _action_ext_controllers(self, application, ext_mgr, mapper):
action_controllers = {} for action in ext_mgr.get_actions(): if (action.collection not in action_controllers.keys()): controller = ActionExtensionController(application) mapper.connect(('/%s/:(id)/action.:(format)' % action.collection), action='action', controller=controller, con...
'Returns a dict of RequestExtensionController-s by collection.'
def _request_ext_controllers(self, application, ext_mgr, mapper):
request_ext_controllers = {} for req_ext in ext_mgr.get_request_extensions(): if (req_ext.key not in request_ext_controllers.keys()): controller = RequestExtensionController(application) mapper.connect((req_ext.url_route + '.:(format)'), action='process', controller=controller, c...
'Route the incoming request with router.'
@webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req):
req.environ['extended.app'] = self.application return self._router
'Dispatch the request. Returns the routed WSGI app\'s response or defers to the extended application.'
@staticmethod @webob.dec.wsgify(RequestClass=wsgi.Request) def _dispatch(req):
match = req.environ['wsgiorg.routing_args'][1] if (not match): return req.environ['extended.app'] app = match['controller'] return app
'Returns a list of ResourceExtension objects.'
def get_resources(self):
resources = [] resources.append(ResourceExtension('extensions', ExtensionController(self))) for ext in self.extensions.itervalues(): try: resources.extend(ext.get_resources()) except AttributeError: pass return resources
'Returns a list of ActionExtension objects.'
def get_actions(self):
actions = [] for ext in self.extensions.itervalues(): try: actions.extend(ext.get_actions()) except AttributeError: pass return actions
'Returns a list of RequestExtension objects.'
def get_request_extensions(self):
request_exts = [] for ext in self.extensions.itervalues(): try: request_exts.extend(ext.get_request_extensions()) except AttributeError: pass return request_exts
'Extend resources with additional resources or attributes. :param: attr_map, the existing mapping from resource name to attrs definition. After this function, we will extend the attr_map if an extension wants to extend this map.'
def extend_resources(self, version, attr_map):
update_exts = [] for ext in self.extensions.itervalues(): if (not hasattr(ext, 'get_extended_resources')): continue if hasattr(ext, 'update_attributes_map'): update_exts.append(ext) try: extended_attrs = ext.get_extended_resources(version) ...
'Checks for required methods in extension objects.'
def _check_extension(self, extension):
try: LOG.debug(_('Ext name: %s'), extension.get_name()) LOG.debug(_('Ext alias: %s'), extension.get_alias()) LOG.debug(_('Ext description: %s'), extension.get_description()) LOG.debug(_('Ext namespace: %s'), extension.get_namespace()) LOG.debug(_('Ext ...
'Load extensions from the configured path. Load extensions from the configured path. The extension name is constructed from the module_name. If your extension module was named widgets.py the extension class within that module should be \'Widgets\'. See tests/unit/extensions/foxinsocks.py for an example extension implem...
def _load_all_extensions(self):
for path in self.path.split(':'): if os.path.exists(path): self._load_all_extensions_from_path(path) else: LOG.error(_("Extension path '%s' doesn't exist!"), path)
'Checks if any of plugins supports extension and implements the extension contract.'
def _check_extension(self, extension):
extension_is_valid = super(PluginAwareExtensionManager, self)._check_extension(extension) return (extension_is_valid and self._plugins_support(extension) and self._plugins_implement_interface(extension))
'Retrieves and formats a list of elements of the requested entity'
def _items(self, request, do_authz=False, parent_id=None):
(original_fields, fields_to_add) = self._do_field_list(api_common.list_args(request, 'fields')) filters = api_common.get_filters(request, self._attr_info, ['fields', 'sort_key', 'sort_dir', 'limit', 'marker', 'page_reverse']) kwargs = {'filters': filters, 'fields': original_fields} sorting_helper = self...
'Retrieves and formats a single element of the requested entity'
def _item(self, request, id, do_authz=False, field_list=None, parent_id=None):
kwargs = {'fields': field_list} action = self._plugin_handlers[self.SHOW] if parent_id: kwargs[self._parent_id_name] = parent_id obj_getter = getattr(self._plugin, action) obj = obj_getter(request.context, id, **kwargs) if do_authz: policy.enforce(request.context, action, obj, pl...
'Returns a list of the requested entity'
def index(self, request, **kwargs):
parent_id = kwargs.get(self._parent_id_name) return self._items(request, True, parent_id)
'Returns detailed information about the requested entity'
def show(self, request, id, **kwargs):
try: (field_list, added_fields) = self._do_field_list(api_common.list_args(request, 'fields')) parent_id = kwargs.get(self._parent_id_name) return {self._resource: self._view(self._item(request, id, do_authz=True, field_list=field_list, parent_id=parent_id), fields_to_strip=added_fields)} ...
'Creates a new instance of the requested entity'
def create(self, request, body=None, **kwargs):
parent_id = kwargs.get(self._parent_id_name) notifier_api.notify(request.context, self._publisher_id, (self._resource + '.create.start'), notifier_api.CONF.default_notification_level, body) body = Controller.prepare_request_body(request.context, body, True, self._resource, self._attr_info, allow_bulk=self._...
'Deletes the specified entity'
def delete(self, request, id, **kwargs):
notifier_api.notify(request.context, self._publisher_id, (self._resource + '.delete.start'), notifier_api.CONF.default_notification_level, {(self._resource + '_id'): id}) action = self._plugin_handlers[self.DELETE] parent_id = kwargs.get(self._parent_id_name) obj = self._item(request, id, parent_id=pare...
'Updates the specified entity\'s attributes'
def update(self, request, id, body=None, **kwargs):
parent_id = kwargs.get(self._parent_id_name) try: payload = body.copy() except AttributeError: msg = (_('Invalid format: %s') % request.body) raise exceptions.BadRequest(resource='body', msg=msg) payload['id'] = id notifier_api.notify(request.context, self._publisher_id...
'verifies required attributes are in request body, and that an attribute is only specified if it is allowed for the given operation (create/update). Attribute with default values are considered to be optional. body argument must be the deserialized body'
@staticmethod def prepare_request_body(context, body, is_create, resource, attr_info, allow_bulk=False):
collection = (resource + 's') if (not body): raise webob.exc.HTTPBadRequest(_('Resource body required')) prep_req_body = (lambda x: Controller.prepare_request_body(context, (x if (resource in x) else {resource: x}), is_create, resource, attr_info, allow_bulk)) if (collection in body): ...
':param base_url: url of the root wsgi application'
def __init__(self, base_url):
self.base_url = base_url
'Generic method used to generate a version entity.'
def build(self, version_data):
version = {'id': version_data['id'], 'status': version_data['status'], 'links': self._build_links(version_data)} return version
'Generate a container of links that refer to the provided version.'
def _build_links(self, version_data):
href = self.generate_href(version_data['id']) links = [{'rel': 'self', 'href': href}] return links
'Create an url that refers to a specific version_number.'
def generate_href(self, version_number):
return os.path.join(self.base_url, version_number)
'verifies required parameters are in request body. sets default value for missing optional parameters. body argument must be the deserialized body'
def _prepare_request_body(self, body, params):
try: if (body is None): body = {self._resource_name: {}} data = body[self._resource_name] except KeyError: raise exc.HTTPBadRequest((_("Unable to find '%s' in request body") % self._resource_name)) for param in params: param_name = param['param-n...
'Respond to a request for all Quantum API versions.'
@webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req):
version_objs = [{'id': 'v2.0', 'status': 'CURRENT'}] if (req.path != '/'): return webob.exc.HTTPNotFound() builder = versions_view.get_view_builder(req) versions = [builder.build(version) for version in version_objs] response = dict(versions=versions) metadata = {'application/xml': {'att...
'Retrieve and return a list of the active network ids.'
def get_active_networks(self, context, **kwargs):
host = kwargs.get('host') LOG.debug(_('Network list requested from %s'), host) plugin = manager.QuantumManager.get_plugin() if utils.is_extension_supported(plugin, constants.AGENT_SCHEDULER_EXT_ALIAS): if cfg.CONF.network_auto_schedule: plugin.auto_schedule_networks(conte...
'Retrieve and return a extended information about a network.'
def get_network_info(self, context, **kwargs):
network_id = kwargs.get('network_id') host = kwargs.get('host') LOG.debug(_('Network %(network_id)s requested from %(host)s'), {'network_id': network_id, 'host': host}) plugin = manager.QuantumManager.get_plugin() network = plugin.get_network(context, network_id) filters = dict(netwo...
'Allocate a DHCP port for the host and return port information. This method will re-use an existing port if one already exists. When a port is re-used, the fixed_ip allocation will be updated to the current network state.'
def get_dhcp_port(self, context, **kwargs):
host = kwargs.get('host') network_id = kwargs.get('network_id') device_id = kwargs.get('device_id') LOG.debug(_('Port %(device_id)s for %(network_id)s requested from %(host)s'), {'device_id': device_id, 'network_id': network_id, 'host': host}) plugin = manager.QuantumManager.get_pl...
'Release the port currently being used by a DHCP agent.'
def release_dhcp_port(self, context, **kwargs):
host = kwargs.get('host') network_id = kwargs.get('network_id') device_id = kwargs.get('device_id') LOG.debug(_('DHCP port deletion for %(network_id)s request from %(host)s'), locals()) plugin = manager.QuantumManager.get_plugin() filters = dict(network_id=[network_id], devi...
'Release the fixed_ip associated the subnet on a port.'
def release_port_fixed_ip(self, context, **kwargs):
host = kwargs.get('host') network_id = kwargs.get('network_id') device_id = kwargs.get('device_id') subnet_id = kwargs.get('subnet_id') LOG.debug(_('DHCP port remove fixed_ip for %(subnet_id)s request from %(host)s'), locals()) plugin = manager.QuantumManager.get_plugin()...
'Release the fixed_ip associated the subnet on a port.'
def update_lease_expiration(self, context, **kwargs):
host = kwargs.get('host') network_id = kwargs.get('network_id') ip_address = kwargs.get('ip_address') lease_remaining = kwargs.get('lease_remaining') LOG.debug(_('Updating lease expiration for %(ip_address)s on network %(network_id)s from %(host)s.'), locals()) plugin ...
'Performs sanity check on session persistence info. :param info: Session persistence info'
def _check_session_persistence_info(self, info):
if (info['type'] == 'APP_COOKIE'): if (not info.get('cookie_name')): raise ValueError(_("'cookie_name' should be specified for this type of session persistence.")) elif ('cookie_name' in info): raise ValueError(_("'cookie_name' is not allowed fo...
'Add a l3 agent to host a router.'
def add_router_to_l3_agent(self, context, id, router_id):
router = self.get_router(context, router_id) with context.session.begin(subtransactions=True): agent_db = self._get_agent(context, id) if ((agent_db['agent_type'] != constants.AGENT_TYPE_L3) or (not agent_db['admin_state_up']) or (not self.get_l3_agent_candidates(router, [agent_db]))): ...
'Remove the router from l3 agent. After it, the router will be non-hosted until there is update which lead to re schedule or be added to another agent manually.'
def remove_router_from_l3_agent(self, context, id, router_id):
agent = self._get_agent(context, id) with context.session.begin(subtransactions=True): query = context.session.query(RouterL3AgentBinding) query = query.filter((RouterL3AgentBinding.router_id == router_id), (RouterL3AgentBinding.l3_agent_id == id)) try: binding = query.one() ...
'Get the valid l3 agents for the router from a list of l3_agents'
def get_l3_agent_candidates(self, sync_router, l3_agents):
candidates = [] for l3_agent in l3_agents: if (not l3_agent.admin_state_up): continue agent_conf = self.get_configuration_dict(l3_agent) router_id = agent_conf.get('router_id', None) use_namespaces = agent_conf.get('use_namespaces', True) handle_internal_only_...
'Schedule the routers to l3 agents.'
def schedule_routers(self, context, routers):
for router in routers: self.schedule_router(context, router)
'Create security group. If default_sg is true that means we are a default security group for a given tenant if it does not exist.'
def create_security_group(self, context, security_group, default_sg=False):
s = security_group['security_group'] tenant_id = self._get_tenant_id_for_create(context, s) if (not default_sg): self._ensure_default_security_group(context, tenant_id) with context.session.begin(subtransactions=True): security_group_db = SecurityGroup(id=(s.get('id') or uuidutils.genera...
'Tenant id is given to handle the case when we are creating a security group rule on behalf of another use.'
def get_security_group(self, context, id, fields=None, tenant_id=None):
if tenant_id: tmp_context_tenant_id = context.tenant_id context.tenant_id = tenant_id try: with context.session.begin(subtransactions=True): ret = self._make_security_group_dict(self._get_security_group(context, id), fields) ret['security_group_rules'] = self.get_...
'Check that rules being installed all belong to the same security group, remote_group_id/security_group_id belong to the same tenant, and rules are valid.'
def _validate_security_group_rules(self, context, security_group_rule):
new_rules = set() tenant_ids = set() for rules in security_group_rule['security_group_rules']: rule = rules.get('security_group_rule') new_rules.add(rule['security_group_id']) if ((rule['port_range_min'] is None) and (rule['port_range_max'] is None)): pass elif ((...
'Create a default security group if one doesn\'t exist. :returns: the default security group id.'
def _ensure_default_security_group(self, context, tenant_id):
filters = {'name': ['default'], 'tenant_id': [tenant_id]} default_group = self.get_security_groups(context, filters) if (not default_group): security_group = {'security_group': {'name': 'default', 'tenant_id': tenant_id, 'description': 'default'}} ret = self.create_security_group(context, se...
'Check that all security groups on port belong to tenant. :returns: all security groups IDs on port belonging to tenant.'
def _get_security_groups_on_port(self, context, port):
p = port['port'] if (not attr.is_attr_set(p.get(ext_sg.SECURITYGROUPS))): return if (p.get('device_owner') and p['device_owner'].startswith('network:')): return valid_groups = self.get_security_groups(context, fields=['id']) valid_group_map = dict(((g['id'], g['id']) for g in valid_g...
'Return True if port has as a security group and it\'s value is either [] or not is_attr_set, otherwise return False'
def _check_update_deletes_security_groups(self, port):
if ((ext_sg.SECURITYGROUPS in port['port']) and (not (attr.is_attr_set(port['port'][ext_sg.SECURITYGROUPS]) and (port['port'][ext_sg.SECURITYGROUPS] != [])))): return True return False
'Return True if port has as a security group and False if the security_group field is is_attr_set or [].'
def _check_update_has_security_groups(self, port):
if ((ext_sg.SECURITYGROUPS in port['port']) and (attr.is_attr_set(port['port'][ext_sg.SECURITYGROUPS]) and (port['port'][ext_sg.SECURITYGROUPS] != []))): return True return False
'Convert a row into a dict'
def as_dict(self):
ret_dict = {} for c in self.__table__.columns: ret_dict[c.name] = getattr(self, c.name) return ret_dict
'Retrieve a service type record'
def get_service_type(self, context, id, fields=None):
return self._make_svc_type_dict(context, self._get_service_type(context, id), fields)
'Retrieve a possibly filtered list of service types'
def get_service_types(self, context, fields=None, filters=None):
query = context.session.query(ServiceType) if filters: for (key, value) in filters.iteritems(): column = getattr(ServiceType, key, None) if column: query = query.filter(column.in_(value)) return [self._make_svc_type_dict(context, svc_type, fields) for svc_type...
'Create a new service type'
def create_service_type(self, context, service_type):
svc_type_data = service_type['service_type'] svc_type_db = self._create_service_type(context, svc_type_data) LOG.debug(_('Created service type object:%s'), svc_type_db['id']) return self._make_svc_type_dict(context, svc_type_db)
'Update a service type'
def update_service_type(self, context, id, service_type):
svc_type_data = service_type['service_type'] svc_type_db = self._update_service_type(context, id, svc_type_data) return self._make_svc_type_dict(context, svc_type_db)
'Delete a service type'
def delete_service_type(self, context, id):
svc_type_db = self._get_service_type(context, id) if (svc_type_db['num_instances'] > 0): raise ServiceTypeInUse(service_type_id=svc_type_db['id']) with context.session.begin(subtransactions=True): context.session.delete(svc_type_db)
'Increase references count for a service type object This method should be invoked by plugins using the service type concept everytime an instance of an object associated with a given service type is created.'
def increase_service_type_refcount(self, context, id):
with context.session.begin(subtransactions=True): svc_type_db = self._get_service_type(context, id) svc_type_db['num_instances'] = (svc_type_db['num_instances'] + 1) return svc_type_db['num_instances']
'Decrease references count for a service type object This method should be invoked by plugins using the service type concept everytime an instance of an object associated with a given service type is removed'
def decrease_service_type_refcount(self, context, id):
with context.session.begin(subtransactions=True): svc_type_db = self._get_service_type(context, id) if (svc_type_db['num_instances'] == 0): LOG.warning(_("Number of instances for service type '%s' is already 0."), svc_type_db['name']) return ...
'Query routers and their related floating_ips, interfaces.'
def get_sync_data(self, context, router_ids=None, active=None):
with context.session.begin(subtransactions=True): routers = super(ExtraRoute_db_mixin, self).get_sync_data(context, router_ids, active=active) for router in routers: router['routes'] = self._get_extra_routes_by_router_id(context, router['id']) return routers
'Make the model object behave like a dict'
def update(self, values):
for (k, v) in values.iteritems(): setattr(self, k, v)
'Make the model object behave like a dict. Includes attributes from joins.'
def iteritems(self):
local = dict(self) joined = dict([(k, v) for (k, v) in self.__dict__.iteritems() if (not (k[0] == '_'))]) local.update(joined) return local.iteritems()
'sqlalchemy based automatic __repr__ method'
def __repr__(self):
items = [('%s=%r' % (col.name, getattr(self, col.name))) for col in self.__table__.columns] return ('<%s.%s[object at %x] {%s}>' % (self.__class__.__module__, self.__class__.__name__, id(self), ', '.join(items)))
'Sync routers according to filters to a specific agent. @param context: contain user information @param kwargs: host, or router_id @return: a list of routers with their interfaces and floating_ips'
def sync_routers(self, context, **kwargs):
router_id = kwargs.get('router_id') host = kwargs.get('host') context = quantum_context.get_admin_context() plugin = manager.QuantumManager.get_plugin() if utils.is_extension_supported(plugin, constants.AGENT_SCHEDULER_EXT_ALIAS): if cfg.CONF.router_auto_schedule: plugin.auto_sch...
'Get one external network id for l3 agent. l3 agent expects only on external network when it performs this query.'
def get_external_network_id(self, context, **kwargs):
context = quantum_context.get_admin_context() plugin = manager.QuantumManager.get_plugin() net_id = plugin.get_external_network_id(context) LOG.debug(_('External network ID returned to l3 agent: %s'), net_id) return net_id
'register an hook to be invoked when a query is executed. Add the hooks to the _model_query_hooks dict. Models are the keys of this dict, whereas the value is another dict mapping hook names to callables performing the hook. Each hook has a "query" component, used to build the query expression and a "filter" component,...
@classmethod def register_model_query_hook(cls, model, name, query_hook, filter_hook, result_filters=None):
model_hooks = cls._model_query_hooks.get(model) if (not model_hooks): model_hooks = {} cls._model_query_hooks[model] = model_hooks model_hooks[name] = {'query': query_hook, 'filter': filter_hook, 'result_filters': result_filters}
'Return held ip allocations with expired leases back to the pool.'
@staticmethod def _recycle_expired_ip_allocations(context, network_id):
if (network_id in getattr(context, '_recycled_networks', set())): return expired_qry = context.session.query(models_v2.IPAllocation).with_lockmode('update') expired_qry = expired_qry.filter_by(network_id=network_id, port_id=None) expired_qry = expired_qry.filter((models_v2.IPAllocation.expiratio...
'Return an IP address to the pool of free IP\'s on the network subnet.'
@staticmethod def _recycle_ip(context, network_id, subnet_id, ip_address):
pool_qry = context.session.query(models_v2.IPAllocationPool).with_lockmode('update') allocation_pools = pool_qry.filter_by(subnet_id=subnet_id).all() pool_id = None for allocation_pool in allocation_pools: allocation_pool_range = netaddr.IPRange(allocation_pool['first_ip'], allocation_pool['last...
'Generate an IP address. The IP address will be generated from one of the subnets defined on the network.'
@staticmethod def _generate_ip(context, subnets):
range_qry = context.session.query(models_v2.IPAvailabilityRange).join(models_v2.IPAllocationPool).with_lockmode('update') for subnet in subnets: range = range_qry.filter_by(subnet_id=subnet['id']).first() if (not range): LOG.debug(_("All IP's from subnet %(subnet_id)s ...
'Allocate a specific IP address on the subnet.'
@staticmethod def _allocate_specific_ip(context, subnet_id, ip_address):
ip = int(netaddr.IPAddress(ip_address)) range_qry = context.session.query(models_v2.IPAvailabilityRange, models_v2.IPAllocationPool).join(models_v2.IPAllocationPool).with_lockmode('update') results = range_qry.filter_by(subnet_id=subnet_id).all() for (range, pool) in results: first = int(netaddr...
'Validate that the IP address on the subnet is not in use.'
@staticmethod def _check_unique_ip(context, network_id, subnet_id, ip_address):
ip_qry = context.session.query(models_v2.IPAllocation) try: ip_qry.filter_by(network_id=network_id, subnet_id=subnet_id, ip_address=ip_address).one() except exc.NoResultFound: return True return False
'Validate that the IP address is on the subnet.'
@staticmethod def _check_subnet_ip(cidr, ip_address):
ip = netaddr.IPAddress(ip_address) net = netaddr.IPNetwork(cidr) if ((ip != net.network) and (ip != net.broadcast) and ((net.netmask & ip) == net.ip)): return True return False
'Validate IP in allocation pool. Validates that the IP address is either the default gateway or in the allocation pools of the subnet.'
@staticmethod def _check_ip_in_allocation_pool(context, subnet_id, gateway_ip, ip_address):
if (ip_address == gateway_ip): return False pool_qry = context.session.query(models_v2.IPAllocationPool) allocation_pools = pool_qry.filter_by(subnet_id=subnet_id).all() ip = netaddr.IPAddress(ip_address) for allocation_pool in allocation_pools: allocation_pool_range = netaddr.IPRang...
'Test fixed IPs for port. Check that configured subnets are valid prior to allocating any IPs. Include the subnet_id in the result if only an IP address is configured. :raises: InvalidInput, IpAddressInUse'
def _test_fixed_ips_for_port(self, context, network_id, fixed_ips):
fixed_ip_set = [] for fixed in fixed_ips: found = False if ('subnet_id' not in fixed): if ('ip_address' not in fixed): msg = _('IP allocation requires subnet_id or ip_address') raise q_exc.InvalidInput(error_message=msg) filt...
'Allocate IP addresses according to the configured fixed_ips.'
def _allocate_fixed_ips(self, context, network, fixed_ips):
ips = [] for fixed in fixed_ips: if ('ip_address' in fixed): QuantumDbPluginV2._allocate_specific_ip(context, fixed['subnet_id'], fixed['ip_address']) ips.append({'ip_address': fixed['ip_address'], 'subnet_id': fixed['subnet_id']}) else: subnets = [self._get_s...
'Add or remove IPs from the port.'
def _update_ips_for_port(self, context, network_id, port_id, original_ips, new_ips):
ips = [] if (len(new_ips) > cfg.CONF.max_fixed_ips_per_port): msg = _('Exceeded maximim amount of fixed ips per port') raise q_exc.InvalidInput(error_message=msg) for original_ip in original_ips[:]: for new_ip in new_ips[:]: if (('ip_address' in new_i...
'Allocate IP addresses for the port. If port[\'fixed_ips\'] is set to \'ATTR_NOT_SPECIFIED\', allocate IP addresses for the port. If port[\'fixed_ips\'] contains an IP address or a subnet_id then allocate an IP address accordingly.'
def _allocate_ips_for_port(self, context, network, port):
p = port['port'] ips = [] fixed_configured = (p['fixed_ips'] is not attributes.ATTR_NOT_SPECIFIED) if fixed_configured: configured_ips = self._test_fixed_ips_for_port(context, p['network_id'], p['fixed_ips']) ips = self._allocate_fixed_ips(context, network, configured_ips) else: ...
'Validate the CIDR for a subnet. Verifies the specified CIDR does not overlap with the ones defined for the other subnets specified for this network, or with any other CIDR if overlapping IPs are disabled.'
def _validate_subnet_cidr(self, context, network, new_subnet_cidr):
new_subnet_ipset = netaddr.IPSet([new_subnet_cidr]) if cfg.CONF.allow_overlapping_ips: subnet_list = network.subnets else: subnet_list = self._get_all_subnets(context) for subnet in subnet_list: if (netaddr.IPSet([subnet.cidr]) & new_subnet_ipset): err_msg = (_('Reque...
'Validate IP allocation pools. Verify start and end address for each allocation pool are valid, ie: constituted by valid and appropriately ordered IP addresses. Also, verify pools do not overlap among themselves. Finally, verify that each range fall within the subnet\'s CIDR.'
def _validate_allocation_pools(self, ip_pools, subnet_cidr):
subnet = netaddr.IPNetwork(subnet_cidr) subnet_first_ip = netaddr.IPAddress((subnet.first + 1)) subnet_last_ip = netaddr.IPAddress((subnet.last - 1)) LOG.debug(_('Performing IP validity checks on allocation pools')) ip_sets = [] for ip_pool in ip_pools: try: ...
'Create IP allocation pools for a given subnet Pools are defined by the \'allocation_pools\' attribute, a list of dict objects with \'start\' and \'end\' keys for defining the pool range.'
def _allocate_pools_for_subnet(self, context, subnet):
pools = [] net = netaddr.IPNetwork(subnet['cidr']) first_ip = (net.first + 1) last_ip = (net.last - 1) gw_ip = int(netaddr.IPAddress((subnet['gateway_ip'] or net.last))) split_ip = min(max(gw_ip, net.first), net.last) if (split_ip > first_ip): pools.append({'start': str(netaddr.IPAdd...
'handle creation of a single network'
def create_network(self, context, network):
n = network['network'] tenant_id = self._get_tenant_id_for_create(context, n) with context.session.begin(subtransactions=True): args = {'tenant_id': tenant_id, 'id': (n.get('id') or uuidutils.generate_uuid()), 'name': n['name'], 'admin_state_up': n['admin_state_up'], 'shared': n['shared'], 'status':...
'Check IP field of a subnet match specified ip version'
def _validate_ip_version(self, ip_version, addr, name):
ip = netaddr.IPNetwork(addr) if (ip.version != ip_version): msg = (_("%(name)s '%(addr)s' does not match the ip_version '%(ip_version)s'") % locals()) raise q_exc.InvalidInput(error_message=msg)
'Validate a subnet spec'
def _validate_subnet(self, s):
ip_ver = s['ip_version'] if ('cidr' in s): self._validate_ip_version(ip_ver, s['cidr'], 'cidr') if attributes.is_attr_set(s.get('gateway_ip')): self._validate_ip_version(ip_ver, s['gateway_ip'], 'gateway_ip') if (cfg.CONF.force_gateway_on_subnet and (not QuantumDbPluginV2._check_subn...
'Update the subnet with new info. The change however will not be realized until the client renew the dns lease or we support gratuitous DHCP offers'
def update_subnet(self, context, id, subnet):
s = subnet['subnet'] db_subnet = self._get_subnet(context, id) s['ip_version'] = db_subnet.ip_version s['cidr'] = db_subnet.cidr self._validate_subnet(s) if ('gateway_ip' in s): allocation_pools = [{'start': p['first_ip'], 'end': p['last_ip']} for p in db_subnet.allocation_pools] ...
'When a floating IP is associated with an internal port, we need to extract/determine some data associated with the internal port, including the internal_ip_address, and router_id. We also need to confirm that this internal port is owned by the tenant who owns the floating IP.'
def get_assoc_data(self, context, fip, floating_network_id):
internal_port = self._get_port(context, fip['port_id']) if (not (internal_port['tenant_id'] == fip['tenant_id'])): port_id = fip['port_id'] if ('id' in fip): floatingip_id = fip['id'] msg = _('Port %(port_id)s is associated with a different tenant ...
'Checks to make sure a port is allowed to be deleted, raising an exception if this is not the case. This should be called by any plugin when the API requests the deletion of a port, since some ports for L3 are not intended to be deleted directly via a DELETE to /ports, but rather via other API calls that perform the p...
def prevent_l3_port_deletion(self, context, port_id):
port_db = self._get_port(context, port_id) if (port_db['device_owner'] in [DEVICE_OWNER_ROUTER_INTF, DEVICE_OWNER_ROUTER_GW, DEVICE_OWNER_FLOATINGIP]): fixed_ips = port_db['fixed_ips'].all() if fixed_ips: raise l3.L3PortInUse(port_id=port_id, device_owner=port_db['device_owner']) ...
'Query routers and their gw ports for l3 agent. Query routers with the router_ids. The gateway ports, if any, will be queried too. l3 agent has an option to deal with only one router id. In addition, when we need to notify the agent the data about only one router (when modification of router, its interfaces, gw_port an...
def _get_sync_routers(self, context, router_ids=None, active=None):
router_query = context.session.query(Router) if router_ids: if (1 == len(router_ids)): router_query = router_query.filter((Router.id == router_ids[0])) else: router_query = router_query.filter(Router.id.in_(router_ids)) if (active is not None): router_query = ...
'Query floating_ips that relate to list of router_ids.'
def _get_sync_floating_ips(self, context, router_ids):
if (not router_ids): return [] return self.get_floatingips(context, {'router_id': router_ids})
'Query router interfaces that relate to list of router_ids.'
def get_sync_interfaces(self, context, router_ids, device_owner=DEVICE_OWNER_ROUTER_INTF):
if (not router_ids): return [] filters = {'device_id': router_ids, 'device_owner': [device_owner]} interfaces = self.get_ports(context, filters) if interfaces: self._populate_subnet_for_ports(context, interfaces) return interfaces
'Populate ports with subnet. These ports already have fixed_ips populated.'
def _populate_subnet_for_ports(self, context, ports):
if (not ports): return subnet_id_ports_dict = {} for port in ports: fixed_ips = port.get('fixed_ips', []) if (len(fixed_ips) > 1): LOG.info(_('Ignoring multiple IPs on router port %s'), port['id']) continue elif (not fixed_ips): ...