desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Delete a network and its corresponding MidoNet bridge.'
| def delete_network(self, context, id):
| LOG.debug(_('MidonetPluginV2.delete_network called: id=%r'), id)
self.mido_api.get_bridge(id).delete()
try:
super(MidonetPluginV2, self).delete_network(context, id)
except Exception:
LOG.error(_('Failed to delete quantum db, while Midonet bridge=%rhad been ... |
'Create a L2 port in Quantum/MidoNet.'
| def create_port(self, context, port):
| LOG.debug(_('MidonetPluginV2.create_port called: port=%r'), port)
is_compute_interface = False
port_data = port['port']
try:
bridge = self.mido_api.get_bridge(port_data['network_id'])
except w_exc.HTTPNotFound:
raise MidonetResourceNotFound(resource_type='Bridge', id=port_data[... |
'Update port.'
| def update_port(self, context, id, port):
| LOG.debug(_('MidonetPluginV2.update_port called: id=%(id)s port=%(port)r'), {'id': id, 'port': port})
return super(MidonetPluginV2, self).update_port(context, id, port)
|
'Retrieve port.'
| def get_port(self, context, id, fields=None):
| LOG.debug(_('MidonetPluginV2.get_port called: id=%(id)s fields=%(fields)r'), {'id': id, 'fields': fields})
port_db_entry = super(MidonetPluginV2, self).get_port(context, id, fields)
self._extend_port_dict_security_group(context, port_db_entry)
try:
self.mido_api.get_port(id)
except ... |
'List quantum ports and verify that they exist in MidoNet.'
| def get_ports(self, context, filters=None, fields=None):
| LOG.debug(_('MidonetPluginV2.get_ports called: filters=%(filters)s fields=%(fields)r'), {'filters': filters, 'fields': fields})
ports_db_entry = super(MidonetPluginV2, self).get_ports(context, filters, fields)
if ports_db_entry:
try:
for port in ports_db_entry:
s... |
'Delete a quantum port and corresponding MidoNet bridge port.'
| def delete_port(self, context, id, l3_port_check=True):
| LOG.debug(_('MidonetPluginV2.delete_port called: id=%(id)s l3_port_check=%(l3_port_check)r'), {'id': id, 'l3_port_check': l3_port_check})
if l3_port_check:
self.prevent_l3_port_deletion(context, id)
session = context.session
with session.begin(subtransactions=True):
port_db_entr... |
'Remove interior router ports.'
| def remove_router_interface(self, context, router_id, interface_info):
| LOG.debug(_('MidonetPluginV2.remove_router_interface called: router_id=%(router_id)s interface_info=%(interface_info)r'), {'router_id': router_id, 'interface_info': interface_info})
if ('port_id' in interface_info):
mbridge_port = self.mido_api.get_port(interface_info['port_id'])
subnet... |
'Create chains for Quantum security group.'
| def create_security_group(self, context, security_group, default_sg=False):
| LOG.debug(_('MidonetPluginV2.create_security_group called: security_group=%(security_group)s default_sg=%(default_sg)s '), {'security_group': security_group, 'default_sg': default_sg})
sg = security_group.get('security_group')
tenant_id = self._get_tenant_id_for_create(context, sg)
with cont... |
'Delete chains for Quantum security group.'
| def delete_security_group(self, context, id):
| LOG.debug(_('MidonetPluginV2.delete_security_group called: id=%s'), id)
with context.session.begin(subtransactions=True):
sg_db_entry = super(MidonetPluginV2, self).get_security_group(context, id)
if (not sg_db_entry):
raise ext_sg.SecurityGroupNotFound(id=id)
sg_name =... |
'Adds to the list of exptected inputs. The incomming request is
matched in the order of priority. For same priority, match the
oldest match request first.
:param prior: intgere priority of this match (e.g. 100)
:param method_regexp: regexp to match method (e.g. \'PUT|POST\')
:param uri_regexp: regexp to match uri (e.g.... | def match(self, prior, method_regexp, uri_regexp, handler, data=None, multi=True):
| assert (int(prior) == prior), 'Priority should an integer be >= 0'
assert (prior >= 0), 'Priority should an integer be >= 0'
(lo, hi) = (0, len(self.matches))
while (lo < hi):
mid = ((lo + hi) // 2)
if (prior < self.matches[mid]):
hi = mid
... |
'Define failure codes as required.
Note: We assume 301-303 is a failure, and try the next server in
the server pool.'
| def server_failure(self, resp):
| return (resp[0] in FAILURE_CODES)
|
'Defining success codes as required.
Note: We assume any valid 2xx as being successful response.'
| def action_success(self, resp):
| return (resp[0] in SUCCESS_CODES)
|
'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
:returns: a sequence of mappings with the following signature:
"id": UUID representing the network.
"name"... | def create_network(self, context, network):
| LOG.debug(_('QuantumRestProxyV2: create_network() called'))
self._warn_on_state_status(network['network'])
tenant_id = self._get_tenant_id_for_create(context, network['network'])
session = context.session
with session.begin(subtransactions=True):
new_net = super(QuantumRestProxyV2, sel... |
'Updates the properties of a particular Virtual Network.
:param context: quantum api request context
:param net_id: uuid of the network to update
:param network: dictionary describing the updates
:returns: a sequence of mappings with the following signature:
"id": UUID representing the network.
"name": Human-readable n... | def update_network(self, context, net_id, network):
| LOG.debug(_('QuantumRestProxyV2.update_network() called'))
self._warn_on_state_status(network['network'])
session = context.session
with session.begin(subtransactions=True):
orig_net = super(QuantumRestProxyV2, self).get_network(context, net_id)
new_net = super(QuantumRestProxyV2, sel... |
'Delete a network.
:param context: quantum api request context
:param id: UUID representing the network to delete.
:returns: None
:raises: exceptions.NetworkInUse
:raises: exceptions.NetworkNotFound
:raises: RemoteRestError'
| def delete_network(self, context, net_id):
| LOG.debug(_('QuantumRestProxyV2: delete_network() called'))
orig_net = super(QuantumRestProxyV2, self).get_network(context, net_id)
tenant_id = orig_net['tenant_id']
filter = {'network_id': [net_id]}
ports = self.get_ports(context, filters=filter)
auto_delete_port_owners = db_base_plugin_v... |
'Create a port, which is a connection point of a device
(e.g., a VM NIC) to attach to a L2 Quantum network.
:param context: quantum api request context
:param port: dictionary describing the port
:returns:
"id": uuid represeting the port.
"network_id": uuid of network.
"tenant_id": tenant_id
"mac_address": mac address ... | def create_port(self, context, port):
| LOG.debug(_('QuantumRestProxyV2: create_port() called'))
port['port']['admin_state_up'] = False
new_port = super(QuantumRestProxyV2, self).create_port(context, port)
net = super(QuantumRestProxyV2, self).get_network(context, new_port['network_id'])
if self.add_meta_server_route:
if (ne... |
'Update values of a port.
:param context: quantum api request context
:param id: UUID representing the port to update.
:param port: dictionary with keys indicating fields to update.
:returns: a mapping sequence with the following signature:
"id": uuid represeting the port.
"network_id": uuid of network.
"tenant_id": te... | def update_port(self, context, port_id, port):
| LOG.debug(_('QuantumRestProxyV2: update_port() called'))
self._warn_on_state_status(port['port'])
orig_port = super(QuantumRestProxyV2, self).get_port(context, port_id)
new_port = super(QuantumRestProxyV2, self).update_port(context, port_id, port)
try:
resource = (PORTS_PATH % (orig_po... |
'Delete a port.
:param context: quantum api request context
:param id: UUID representing the port to delete.
:raises: exceptions.PortInUse
:raises: exceptions.PortNotFound
:raises: exceptions.NetworkNotFound
:raises: RemoteRestError'
| def delete_port(self, context, port_id, l3_port_check=True):
| LOG.debug(_('QuantumRestProxyV2: delete_port() called'))
if l3_port_check:
self.prevent_l3_port_deletion(context, port_id)
self.disassociate_floatingips(context, port_id)
super(QuantumRestProxyV2, self).delete_port(context, port_id)
|
'Attaches a remote interface to the specified port on the
specified Virtual Network.
:returns: None
:raises: exceptions.NetworkNotFound
:raises: exceptions.PortNotFound
:raises: RemoteRestError'
| def _plug_interface(self, context, tenant_id, net_id, port_id, remote_interface_id):
| LOG.debug(_('QuantumRestProxyV2: _plug_interface() called'))
try:
port = super(QuantumRestProxyV2, self).get_port(context, port_id)
mac = port['mac_address']
if (mac is not None):
resource = (ATTACHMENT_PATH % (tenant_id, net_id, port_id))
data = {'attachmen... |
'Detaches a remote interface from the specified port on the
network controller
:returns: None
:raises: RemoteRestError'
| def _unplug_interface(self, context, tenant_id, net_id, port_id):
| LOG.debug(_('QuantumRestProxyV2: _unplug_interface() called'))
try:
resource = (ATTACHMENT_PATH % (tenant_id, net_id, port_id))
ret = self.servers.delete(resource)
if (not self.servers.action_success(ret)):
raise RemoteRestError(ret[2])
except RemoteRestError as e:
... |
'Pushes all data to network ctrl (networks/ports, ports/attachments)
to give the controller an option to re-sync it\'s persistent store
with quantum\'s current view of that data.'
| def _send_all_data(self):
| admin_context = qcontext.get_admin_context()
networks = []
routers = []
all_networks = (super(QuantumRestProxyV2, self).get_networks(admin_context) or [])
for net in all_networks:
mapped_network = self._get_mapped_network_with_subnets(net)
net_fl_ips = self._get_network_with_floating... |
'Look up an option value.
:param name: the opt name (or \'dest\', more precisely)
:param group: an OptGroup
:returns: the option value, or a GroupAttr object
:raises: NoSuchOptError, NoSuchGroupError, ConfigFileValueError,
TemplateSubstitutionError'
| def _do_get(self, name, group=None):
| if ((group is None) and (name in self._groups)):
return self.GroupAttr(self, self._get_group(name))
info = self._get_opt_info(name, group)
opt = info['opt']
if ('override' in info):
return info['override']
values = []
if (self._cparser is not None):
section = (group.name ... |
'Register multiple option schemas at once.'
| def register_opts(self, opts, group_internal_name=None, group=None):
| if group_internal_name:
self._group_mappings[group] = group_internal_name
for opt in opts:
self.register_opt(opt, group, clear_cache=False)
|
'Converts Quantum API security group rule to NVP API.'
| def _convert_to_nvp_rule(self, rule, with_id=False):
| nvp_rule = {}
params = ['remote_ip_prefix', 'protocol', 'remote_group_id', 'port_range_min', 'port_range_max', 'ethertype']
if with_id:
params.append('id')
for param in params:
value = rule.get(param)
if (param not in rule):
nvp_rule[param] = value
elif (not v... |
'Converts a list of Quantum API security group rules to NVP API.'
| def _convert_to_nvp_rules(self, rules, with_id=False):
| nvp_rules = {'logical_port_ingress_rules': [], 'logical_port_egress_rules': []}
for direction in ['logical_port_ingress_rules', 'logical_port_egress_rules']:
for rule in rules[direction]:
nvp_rules[direction].append(self._convert_to_nvp_rule(rule, with_id))
return nvp_rules
|
'Query quantum db for security group rules.'
| def _get_security_group_rules_nvp_format(self, context, security_group_id, with_id=False):
| fields = ['remote_ip_prefix', 'remote_group_id', 'protocol', 'port_range_min', 'port_range_max', 'protocol', 'ethertype']
if with_id:
fields.append('id')
filters = {'security_group_id': [security_group_id], 'direction': ['ingress']}
ingress_rules = self.get_security_group_rules(context, filters,... |
'Return profile id from novas group id.'
| def _get_profile_uuid(self, context, remote_group_id):
| security_group = self.get_security_group(context, remote_group_id)
if (not security_group):
raise ext_sg.SecurityGroupNotFound(id=remote_group_id)
return security_group['id']
|
'This function receives all of the current rule associated with a
security group and then removes the rule that matches the rule_id. In
addition it removes the id field in the dict with each rule since that
should not be passed to nvp.'
| def _remove_security_group_with_id_and_id_field(self, rules, rule_id):
| for rule_direction in rules.values():
item_to_remove = None
for port_rule in rule_direction:
if (port_rule['id'] == rule_id):
item_to_remove = port_rule
else:
del port_rule['id']
if item_to_remove:
rule_direction.remove(item... |
'Add a new set of controller parameters.
:param ip: IP address of controller.
:param port: port controller is listening on.
:param user: user name.
:param password: user password.
:param request_timeout: timeout for an entire API request.
:param http_timeout: timeout for a connect to a controller.
:param retries: maxim... | def add_controller(self, ip, port, user, password, request_timeout, http_timeout, retries, redirects, default_tz_uuid, uuid=None, zone=None, default_l3_gw_service_uuid=None, default_l2_gw_service_uuid=None, default_interface_name=None):
| keys = ['ip', 'user', 'password', 'default_tz_uuid', 'default_l3_gw_service_uuid', 'default_l2_gw_service_uuid', 'default_interface_name', 'uuid', 'zone']
controller_dict = dict([(k, locals()[k]) for k in keys])
default_tz_uuid = controller_dict.get('default_tz_uuid')
if (not re.match(attributes.UUID_PA... |
'Get the rpc dispatcher for this manager.
If a manager would like to set an rpc API version, or support more than
one class as the target of rpc messages, override this method.'
| def create_rpc_dispatcher(self):
| return q_rpc.PluginRpcDispatcher([self, agents_db.AgentExtRpcCallback()])
|
'Build ip_addresses data structure for logical router port
No need to perform validation on IPs - this has already been
done in the l3_db mixin class'
| def _build_ip_address_list(self, context, fixed_ips, subnet_ids=None):
| ip_addresses = []
for ip in fixed_ips:
if ((not subnet_ids) or (ip['subnet_id'] in subnet_ids)):
subnet = self._get_subnet(context, ip['subnet_id'])
ip_prefix = ('%s/%s' % (ip['ip_address'], subnet['cidr'].split('/')[1]))
ip_addresses.append(ip_prefix)
return ip_a... |
'Retrieve ports associated with a specific device id.
Used for retrieving all quantum ports attached to a given router.'
| def _get_port_by_device_id(self, context, device_id, device_owner):
| port_qry = context.session.query(models_v2.Port)
return port_qry.filter_by(device_id=device_id, device_owner=device_owner).all()
|
'Retrieve subnets attached to the specified router'
| def _find_router_subnets_cidrs(self, context, router_id):
| ports = self._get_port_by_device_id(context, router_id, l3_db.DEVICE_OWNER_ROUTER_INTF)
cidrs = []
for port in ports:
for ip in port.get('fixed_ips', []):
cidrs.append(self._get_subnet(context, ip.subnet_id).cidr)
return cidrs
|
'Driver for creating a logical switch port on NVP platform'
| def _nvp_create_port(self, context, port_data):
| if self._network_is_external(context, port_data['network_id']):
LOG.error(_('NVP plugin does not support regular VIF ports on external networks. Port %s will be down.'), port_data['network_id'])
return port_data
try:
cluster = self._find_targe... |
'Driver for creating a switch port to be connected to a router'
| def _nvp_create_router_port(self, context, port_data):
| if self._network_is_external(context, port_data['network_id']):
raise nvp_exc.NvpPluginException(err_msg=(_("It is not allowed to create router interface ports on external networks as '%s'") % port_data['network_id']))
try:
selected_lswitch = self._nvp_find... |
'Driver for creating an external gateway port on NVP platform'
| def _nvp_create_ext_gw_port(self, context, port_data):
| lr_port = self._find_router_gw_port(context, port_data)
ip_addresses = self._build_ip_address_list(context, port_data['fixed_ips'])
cluster = self._find_target_cluster(port_data)
router_id = port_data['device_id']
nvplib.update_router_lport(cluster, router_id, lr_port['uuid'], port_data['tenant_id']... |
'Create a switch port, and attach it to a L2 gateway attachment'
| def _nvp_create_l2_gw_port(self, context, port_data):
| if self._network_is_external(context, port_data['network_id']):
LOG.error(_('NVP plugin does not support regular VIF ports on external networks. Port %s will be down.'), port_data['network_id'])
return port_data
try:
cluster = self._find_targe... |
'Return the NVP port uuid for a given quantum port.
First, look up the Quantum database. If not found, execute
a query on NVP platform as the mapping might be missing because
the port was created before upgrading to grizzly.'
| def _nvp_get_port_id(self, context, cluster, quantum_port):
| nvp_port_id = nicira_db.get_nvp_port_id(context.session, quantum_port['id'])
if nvp_port_id:
return nvp_port_id
try:
nvp_port = nvplib.get_port_by_quantum_tag(cluster, quantum_port['network_id'], quantum_port['id'])
if nvp_port:
nicira_db.add_quantum_nvp_port_mapping(cont... |
'Extends the Quantum Fault Map
Exceptions specific to the NVP Plugin are mapped to standard
HTTP Exceptions'
| def _extend_fault_map(self):
| base.FAULT_MAP.update({nvp_exc.NvpInvalidNovaZone: webob.exc.HTTPBadRequest, nvp_exc.NvpNoMorePortsException: webob.exc.HTTPBadRequest})
|
'Return cluster where configuration should be applied
If the resource being configured has a paremeter expressing
the zone id (nova_id), then select corresponding cluster,
otherwise return default cluster.'
| def _find_target_cluster(self, resource):
| if ('nova_id' in resource):
return self._novazone_to_cluster(resource['nova_id'])
else:
return self.default_cluster
|
'Figure out the set of lswitches on each cluster that maps to this
network id'
| def _get_lswitch_cluster_pairs(self, netw_id, tenant_id):
| pairs = []
for c in self.clusters.itervalues():
lswitches = []
try:
results = nvplib.get_lswitches(c, netw_id)
lswitches.extend([ls['uuid'] for ls in results])
except q_exc.NetworkNotFound:
continue
pairs.append((c, lswitches))
if (len(pair... |
'Deletes a port on a specified Virtual Network,
if the port contains a remote interface attachment,
the remote interface is first un-plugged and then the port
is deleted.
:returns: None
:raises: exception.PortInUse
:raises: exception.PortNotFound
:raises: exception.NetworkNotFound'
| def delete_port(self, context, id, l3_port_check=True, nw_gw_port_check=True):
| if l3_port_check:
self.prevent_l3_port_deletion(context, id)
quantum_db_port = self._get_port(context, id)
if nw_gw_port_check:
self.prevent_network_gateway_port_deletion(context, quantum_db_port)
port_delete_func = self._port_drivers['delete'].get(quantum_db_port.device_owner, self._por... |
'Update floating IP association data.
Overrides method from base class.
The method is augmented for creating NAT rules in the process.'
| def _update_fip_assoc(self, context, fip, floatingip_db, external_port):
| if ((('fixed_ip_address' in fip) and fip['fixed_ip_address']) and (not (('port_id' in fip) and fip['port_id']))):
msg = _('fixed_ip_address cannot be specified without a port_id')
raise q_exc.BadRequest(resource='floatingip', msg=msg)
port_id = internal_ip = router_id = None
... |
'Create a layer-2 network gateway
Create the gateway service on NVP platform and corresponding data
structures in Quantum datase'
| def create_network_gateway(self, context, network_gateway):
| gw_data = network_gateway[networkgw.RESOURCE_NAME.replace('-', '_')]
tenant_id = self._get_tenant_id_for_create(context, gw_data)
cluster = self._find_target_cluster(gw_data)
devices = gw_data['devices']
for device in devices:
if (not device.get('interface_name')):
device['interf... |
'Remove a layer-2 network gateway
Remove the gateway service from NVP platform and corresponding data
structures in Quantum datase'
| def delete_network_gateway(self, context, id):
| with context.session.begin(subtransactions=True):
try:
super(NvpPluginV2, self).delete_network_gateway(context, id)
nvplib.delete_l2_gw_service(self.default_cluster, id)
except NvpApiClient.ResourceNotFound:
LOG.exception(_('Unable to remove gateway se... |
'Create security group.
If default_sg is true that means a we are creating a default security
group and we don\'t need to check if one exists.'
| def create_security_group(self, context, security_group, default_sg=False):
| s = security_group.get('security_group')
tenant_id = self._get_tenant_id_for_create(context, s)
if (not default_sg):
self._ensure_default_security_group(context, tenant_id)
nvp_secgroup = nvplib.create_security_profile(self.default_cluster, tenant_id, s)
security_group['security_group']['id'... |
'Delete a security group
:param security_group_id: security group rule to remove.'
| def delete_security_group(self, context, security_group_id):
| with context.session.begin(subtransactions=True):
security_group = super(NvpPluginV2, self).get_security_group(context, security_group_id)
if (not security_group):
raise ext_sg.SecurityGroupNotFound(id=security_group_id)
if (security_group['name'] == 'default'):
raise... |
'create a single security group rule'
| def create_security_group_rule(self, context, security_group_rule):
| bulk_rule = {'security_group_rules': [security_group_rule]}
return self.create_security_group_rule_bulk(context, bulk_rule)[0]
|
'create security group rules
:param security_group_rule: list of rules to create'
| def create_security_group_rule_bulk(self, context, security_group_rule):
| s = security_group_rule.get('security_group_rules')
tenant_id = self._get_tenant_id_for_create(context, s)
with context.session.begin(subtransactions=True):
self._ensure_default_security_group(context, tenant_id)
security_group_id = self._validate_security_group_rules(context, security_group... |
'Delete a security group rule
:param sgrid: security group id to remove.'
| def delete_security_group_rule(self, context, sgrid):
| with context.session.begin(subtransactions=True):
security_group_rule = super(NvpPluginV2, self).get_security_group_rule(context, sgrid)
if (not security_group_rule):
raise ext_sg.SecurityGroupRuleNotFound(id=sgrid)
sgid = security_group_rule['security_group_id']
current_... |
'This function determines if a port should be associated with a
queue. It works by first querying NetworkQueueMapping to determine
if the network is associated with a queue. If so, then it queries
NetworkQueueMapping for all the networks that are associated with
this queue. Next, it queries against all the ports on the... | def _check_for_queue_and_create(self, context, port):
| queue_to_create = None
if ((not port.get('device_id')) or port['device_owner'].startswith('network:')):
return
filters = {'network_id': [port['network_id']]}
network_queue_id = self._get_network_queue_bindings(context, filters, ['queue_id'])
if network_queue_id:
filters = {'queue_id'... |
'Convert fields to nvp fields.'
| def _nvp_lqueue(self, queue):
| nvp_queue = {}
params = {'name': 'display_name', 'qos_marking': 'qos_marking', 'min': 'min_bandwidth_rate', 'max': 'max_bandwidth_rate', 'dscp': 'dscp'}
nvp_queue = dict(((nvp_name, queue.get(api_name)) for (api_name, nvp_name) in params.iteritems() if attr.is_attr_set(queue.get(api_name))))
if ('displa... |
'Returns Ext Resources'
| @classmethod
def get_resources(cls):
| plugin = manager.QuantumManager.get_plugin()
params = RESOURCE_ATTRIBUTE_MAP.get(COLLECTION_NAME, dict())
member_actions = {'connect_network': 'PUT', 'disconnect_network': 'PUT'}
quota.QUOTAS.register_resource_by_name(RESOURCE_NAME)
controller = base.create_resource(COLLECTION_NAME, RESOURCE_NAME, p... |
'Returns Ext Resources'
| @classmethod
def get_resources(cls):
| exts = []
plugin = manager.QuantumManager.get_plugin()
resource_name = 'qos_queue'
collection_name = (resource_name.replace('_', '-') + 's')
params = RESOURCE_ATTRIBUTE_MAP.get((resource_name + 's'), dict())
controller = base.create_resource(collection_name, resource_name, plugin, params, allow_... |
'Constructor.
:param api_providers: a list of tuples in the form:
(host, port, is_ssl=True). Passed on to NvpClientEventlet.
:param user: the login username.
:param password: the login password.
:param concurrent_connections: the number of concurrent connections.
:param request_timeout: all operations (including retrie... | def __init__(self, api_providers, user, password, request_timeout, http_timeout, retries, redirects, concurrent_connections=3, nvp_gen_timeout=(-1)):
| client_eventlet.NvpApiClientEventlet.__init__(self, api_providers, user, password, concurrent_connections, nvp_gen_timeout)
self._request_timeout = request_timeout
self._http_timeout = http_timeout
self._retries = retries
self._redirects = redirects
self._nvp_version = None
|
'Login to NVP controller.
Assumes same password is used for all controllers.
:param user: NVP controller user (usually admin). Provided for
backwards compatability. In the normal mode of operation
this should be None.
:param password: NVP controller password. Provided for backwards
compatability. In the normal mode of... | def login(self, user=None, password=None):
| if user:
self._user = user
if password:
self._password = password
return client_eventlet.NvpApiClientEventlet._login(self)
|
'Issues request to controller.'
| def request(self, method, url, body='', content_type='application/json'):
| g = request_eventlet.NvpGenericRequestEventlet(self, method, url, body, content_type, auto_login=True, request_timeout=self._request_timeout, http_timeout=self._http_timeout, retries=self._retries, redirects=self._redirects)
g.start()
response = g.join()
LOG.debug(_('NVPApiHelper.request() returns ... |
'Constructor.'
| def __init__(self, nvp_api_client, url, method='GET', body=None, headers=None, request_timeout=request.DEFAULT_REQUEST_TIMEOUT, retries=request.DEFAULT_RETRIES, auto_login=True, redirects=request.DEFAULT_REDIRECTS, http_timeout=request.DEFAULT_HTTP_TIMEOUT, client_conn=None):
| self._api_client = nvp_api_client
self._url = url
self._method = method
self._body = body
self._headers = (headers or {})
self._request_timeout = request_timeout
self._retries = retries
self._auto_login = auto_login
self._redirects = redirects
self._http_timeout = http_timeout
... |
'Allocate a green thread from the class pool.'
| @classmethod
def _spawn(cls, func, *args, **kwargs):
| return cls.API_REQUEST_POOL.spawn(func, *args, **kwargs)
|
'Spawn a new green thread with the supplied function and args.'
| def spawn(self, func, *args, **kwargs):
| return self.__class__._spawn(func, *args, **kwargs)
|
'Wait for all outstanding requests to complete.'
| @classmethod
def joinall(cls):
| return cls.API_REQUEST_POOL.waitall()
|
'Wait for instance green thread to complete.'
| def join(self):
| if (self._green_thread is not None):
return self._green_thread.wait()
return Exception(_('Joining an invalid green thread'))
|
'Start request processing.'
| def start(self):
| self._green_thread = self.spawn(self._run)
|
'Return a copy of this request instance.'
| def copy(self):
| return NvpApiRequestEventlet(self._api_client, self._url, self._method, self._body, self._headers, self._request_timeout, self._retries, self._auto_login, self._redirects, self._http_timeout)
|
'Method executed within green thread.'
| def _run(self):
| if self._request_timeout:
with eventlet.timeout.Timeout(self._request_timeout, False):
return self._handle_request()
LOG.info(_('[%d] Request timeout.'), self._rid())
self._request_error = Exception(_('Request timeout'))
return None
else:
return self.... |
'First level request handling.'
| def _handle_request(self):
| attempt = 0
response = None
while ((response is None) and (attempt <= self._retries)):
attempt += 1
req = self.spawn(self._issue_request).wait()
if isinstance(req, httplib.HTTPResponse):
if ((attempt <= self._retries) and (not self._abort)):
if ((req.statu... |
'Parse api_providers from response.
Returns: api_providers in [(host, port, is_ssl), ...] format'
| def api_providers(self):
| def _provider_from_listen_addr(addr):
parts = addr.split(':')
return (parts[1], int(parts[2]), (parts[0] == 'pssl'))
try:
if self.successful():
ret = []
body = json.loads(self.value.body)
for node in body.get('results', []):
for role in... |
'Check out an available HTTPConnection instance.
Blocks until a connection is available.
:auto_login: automatically logins before returning conn
:headers: header to pass on to login attempt
:param rid: request id passed in from request eventlet.
:returns: An available HTTPConnection instance or None if no
api_providers... | def acquire_connection(self, auto_login=True, headers=None, rid=(-1)):
| if (not self._api_providers):
LOG.warn(_('[%d] no API providers currently available.'), rid)
return None
if self._conn_pool.empty():
LOG.debug(_('[%d] Waiting to acquire API client connection.'), rid)
(priority, conn) = self._conn_pool.get()
now =... |
'Mark HTTPConnection instance as available for check-out.
:param http_conn: An HTTPConnection instance obtained from this
instance.
:param bad_state: True if http_conn is known to be in a bad state
(e.g. connection fault.)
:service_unavail: True if http_conn returned 503 response.
:param rid: request id passed in from ... | def release_connection(self, http_conn, bad_state=False, service_unavail=False, rid=(-1)):
| conn_params = self._conn_params(http_conn)
if (self._conn_params(http_conn) not in self._api_providers):
LOG.debug(_('[%(rid)d] Released connection %(conn)s is not an API provider for the cluster'), {'rid': rid, 'conn': _conn_str(http_conn)})
return
elif hasa... |
'Block until a login has occurred for the current API provider.'
| def _wait_for_login(self, conn, headers=None):
| data = self._get_provider_data(conn)
if (data is None):
LOG.error(_("Login request for an invalid connection: '%s'"), _conn_str(conn))
return
provider_sem = data[0]
if provider_sem.acquire(blocking=False):
try:
cookie = self._login(conn, headers)
... |
'Get data for specified API provider.
Args:
conn_or_conn_params: either a HTTP(S)Connection object or the
resolved conn_params tuple returned by self._conn_params().
default: conn_params if ones passed aren\'t known
Returns: Data associated with specified provider'
| def _get_provider_data(self, conn_or_conn_params, default=None):
| conn_params = self._normalize_conn_params(conn_or_conn_params)
return self._api_provider_data.get(conn_params, default)
|
'Set data for specified API provider.
Args:
conn_or_conn_params: either a HTTP(S)Connection object or the
resolved conn_params tuple returned by self._conn_params().
data: data to associate with API provider'
| def _set_provider_data(self, conn_or_conn_params, data):
| conn_params = self._normalize_conn_params(conn_or_conn_params)
if (data is None):
del self._api_provider_data[conn_params]
else:
self._api_provider_data[conn_params] = data
|
'Normalize conn_param tuple.
Args:
conn_or_conn_params: either a HTTP(S)Connection object or the
resolved conn_params tuple returned by self._conn_params().
Returns: Normalized conn_param tuple'
| def _normalize_conn_params(self, conn_or_conn_params):
| if ((not isinstance(conn_or_conn_params, tuple)) and (not isinstance(conn_or_conn_params, httplib.HTTPConnection))):
LOG.debug(_("Invalid conn_params value: '%s'"), str(conn_or_conn_params))
return conn_or_conn_params
if isinstance(conn_or_conn_params, httplib.HTTPConnection):
c... |
'Constructor
:param api_providers: a list of tuples of the form: (host, port,
is_ssl).
:param user: login username.
:param password: login password.
:param concurrent_connections: total number of concurrent connections.
:param use_https: whether or not to use https for requests.
:param connect_timeout: connection timeo... | def __init__(self, api_providers, user, password, concurrent_connections=client.DEFAULT_CONCURRENT_CONNECTIONS, nvp_gen_timeout=client.GENERATION_ID_TIMEOUT, use_https=True, connect_timeout=client.DEFAULT_CONNECT_TIMEOUT):
| if (not api_providers):
api_providers = []
self._api_providers = set([tuple(p) for p in api_providers])
self._api_provider_data = {}
for p in self._api_providers:
self._set_provider_data(p, (eventlet.semaphore.Semaphore(1), None))
self._user = user
self._password = password
s... |
'Check out or create connection to redirected NVP API server.
Args:
conn_params: tuple specifying target of redirect, see
self._conn_params()
auto_login: returned connection should have valid session cookie
headers: headers to pass on if auto_login
Returns: An available HTTPConnection instance corresponding to the
spec... | def acquire_redirect_connection(self, conn_params, auto_login=True, headers=None):
| result_conn = None
data = self._get_provider_data(conn_params)
if data:
conns = []
while (not self._conn_pool.empty()):
(priority, conn) = self._conn_pool.get_nowait()
if ((not result_conn) and (self._conn_params(conn) == conn_params)):
conn.priority =... |
'Issue login request and update authentication cookie.'
| def _login(self, conn=None, headers=None):
| cookie = None
g = request_eventlet.NvpLoginRequestEventlet(self, self._user, self._password, conn, headers)
g.start()
ret = g.join()
if ret:
if isinstance(ret, Exception):
LOG.error(_('NvpApiClient: login error "%s"'), ret)
raise ret
cookie = ret.geth... |
'Issue a request to a provider.'
| def _issue_request(self):
| conn = (self._client_conn or self._api_client.acquire_connection(True, copy.copy(self._headers), rid=self._rid()))
if (conn is None):
error = Exception(_('No API connections available'))
self._request_error = error
return error
url = self._url
LOG.debug(_('[%(rid)d] I... |
'Process redirect response, create new connection if necessary.
Args:
conn: connection that returned the redirect response
headers: response headers of the redirect response
allow_release_conn: if redirecting to a different server,
release existing connection back to connection pool.
Returns: Return tuple(conn, url) wh... | def _redirect_params(self, conn, headers, allow_release_conn=False):
| url = None
for (name, value) in headers:
if (name.lower() == 'location'):
url = value
break
if (not url):
LOG.warn(_('[%d] Received redirect status without location header field'), self._rid())
return (conn, None)
result = urlparse.url... |
'Return current request id.'
| def _rid(self):
| return self._request_id
|
'Return any errors associated with this instance.'
| @property
def request_error(self):
| return self._request_error
|
'Return string representation of connection.'
| def _request_str(self, conn, url):
| return ('%s %s/%s' % (self._method, _conn_str(conn), url))
|
'Pre-deletion check.
Ensures a port will not be deleted if is being used by a network
gateway. In that case an exception will be raised.'
| def prevent_network_gateway_port_deletion(self, context, port):
| if (port['device_owner'] == DEVICE_OWNER_NET_GW_INTF):
raise NetworkGatewayPortInUse(port_id=port['id'], device_owner=port['device_owner'])
|
'Create network core Quantum API'
| def create_network(self, context, network):
| LOG.debug(_('QuantumPluginPLUMgrid Status: create_network() called'))
tenant_id = self._get_tenant_id_for_create(context, network['network'])
self._network_admin_state(network)
with context.session.begin(subtransactions=True):
net = super(QuantumPluginPLUMgridV2, self).create_network(co... |
'Update network core Quantum API'
| def update_network(self, context, net_id, network):
| LOG.debug(_('QuantumPluginPLUMgridV2.update_network() called'))
self._network_admin_state(network)
tenant_id = self._get_tenant_id_for_create(context, network['network'])
original_net = super(QuantumPluginPLUMgridV2, self).get_network(context, net_id)
with context.session.begin(subtransactions=Tr... |
'Delete network core Quantum API'
| def delete_network(self, context, net_id):
| LOG.debug(_('QuantumPluginPLUMgrid Status: delete_network() called'))
super(QuantumPluginPLUMgridV2, self).get_network(context, net_id)
with context.session.begin(subtransactions=True):
net_deleted = super(QuantumPluginPLUMgridV2, self).delete_network(context, net_id)
try:
... |
'Create port core Quantum API'
| def create_port(self, context, port):
| LOG.debug(_('QuantumPluginPLUMgrid Status: create_port() called'))
port['port']['admin_state_up'] = True
return super(QuantumPluginPLUMgridV2, self).create_port(context, port)
|
'Update port core Quantum API'
| def update_port(self, context, port_id, port):
| LOG.debug(_('QuantumPluginPLUMgrid Status: update_port() called'))
return super(QuantumPluginPLUMgridV2, self).update_port(context, port_id, port)
|
'Delete port core Quantum API'
| def delete_port(self, context, port_id):
| LOG.debug(_('QuantumPluginPLUMgrid Status: delete_port() called'))
super(QuantumPluginPLUMgridV2, self).delete_port(context, port_id)
|
'Create subnet core Quantum API'
| def create_subnet(self, context, subnet):
| LOG.debug(_('QuantumPluginPLUMgrid Status: create_subnet() called'))
with context.session.begin(subtransactions=True):
subnet = super(QuantumPluginPLUMgridV2, self).create_subnet(context, subnet)
subnet_details = self._get_subnet(context, subnet['id'])
net_id = subnet_details['n... |
'Delete subnet core Quantum API'
| def delete_subnet(self, context, subnet_id):
| LOG.debug(_('QuantumPluginPLUMgrid Status: delete_subnet() called'))
subnet_details = self._get_subnet(context, subnet_id)
with context.session.begin(subtransactions=True):
del_subnet = super(QuantumPluginPLUMgridV2, self).delete_subnet(context, subnet_id)
try:
headers =... |
'Update subnet core Quantum API'
| def update_subnet(self, context, subnet_id, subnet):
| LOG.debug(_('update_subnet() called'))
initial_subnet = self._get_subnet(context, subnet_id)
net_id = initial_subnet['network_id']
tenant_id = initial_subnet['tenant_id']
with context.session.begin(subtransactions=True):
new_subnet = super(QuantumPluginPLUMgridV2, self).update_subnet(cont... |
'Check if ethernet device exists.'
| def device_exists(self, device):
| try:
utils.execute(['ip', 'link', 'show', 'dev', device], root_helper=self.root_helper)
except RuntimeError:
return False
return True
|
'Create a vlan and bridge unless they already exist.'
| def ensure_vlan_bridge(self, network_id, physical_interface, vlan_id):
| interface = self.ensure_vlan(physical_interface, vlan_id)
bridge_name = self.get_bridge_name(network_id)
self.ensure_bridge(bridge_name, interface)
return interface
|
'Create a non-vlan bridge unless it already exists.'
| def ensure_flat_bridge(self, network_id, physical_interface):
| bridge_name = self.get_bridge_name(network_id)
(ips, gateway) = self.get_interface_details(physical_interface)
self.ensure_bridge(bridge_name, physical_interface, ips, gateway)
return physical_interface
|
'Create a local bridge unless it already exists.'
| def ensure_local_bridge(self, network_id):
| bridge_name = self.get_bridge_name(network_id)
self.ensure_bridge(bridge_name)
|
'Create a vlan unless it already exists.'
| def ensure_vlan(self, physical_interface, vlan_id):
| interface = self.get_subinterface_name(physical_interface, vlan_id)
if (not self.device_exists(interface)):
LOG.debug(_('Creating subinterface %(interface)s for VLAN %(vlan_id)s on interface %(physical_interface)s'), locals())
if utils.execute(['ip', 'link', 'add', 'link'... |
'Create a bridge unless it already exists.'
| def ensure_bridge(self, bridge_name, interface=None, ips=None, gateway=None):
| if (not self.device_exists(bridge_name)):
LOG.debug(_('Starting bridge %(bridge_name)s for subinterface %(interface)s'), locals())
if utils.execute(['brctl', 'addbr', bridge_name], root_helper=self.root_helper):
return
if utils.execute(['brctl', 'setfd', bridge_nam... |
'If a VIF has been plugged into a network, this function will
add the corresponding tap device to the relevant bridge'
| def add_tap_interface(self, network_id, physical_network, vlan_id, tap_device_name):
| if (not self.device_exists(tap_device_name)):
LOG.debug(_('Tap device: %s does not exist on this host, skipped'), tap_device_name)
return False
bridge_name = self.get_bridge_name(network_id)
if (int(vlan_id) == lconst.LOCAL_VLAN_ID):
self.ensure_local_bridg... |
'Get the rpc dispatcher for this manager.
If a manager would like to set an rpc API version, or support more than
one class as the target of rpc messages, override this method.'
| def create_rpc_dispatcher(self):
| return dispatcher.RpcDispatcher([self])
|
'Get the rpc dispatcher for this manager.
If a manager would like to set an rpc API version, or support more than
one class as the target of rpc messages, override this method.'
| def create_rpc_dispatcher(self):
| return q_rpc.PluginRpcDispatcher([self, agents_db.AgentExtRpcCallback()])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.