本文整理汇总了Python中nova.compute.utils.get_nw_info_for_instance函数的典型用法代码示例。如果您正苦于以下问题:Python get_nw_info_for_instance函数的具体用法?Python get_nw_info_for_instance怎么用?Python get_nw_info_for_instance使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_nw_info_for_instance函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _test_init_instance_reverts_crashed_migrations
def _test_init_instance_reverts_crashed_migrations(self, old_vm_state=None):
power_on = True if (not old_vm_state or old_vm_state == vm_states.ACTIVE) else False
sys_meta = {"old_vm_state": old_vm_state}
instance = {
"uuid": "foo",
"vm_state": vm_states.ERROR,
"task_state": task_states.RESIZE_MIGRATING,
"power_state": power_state.SHUTDOWN,
"system_metadata": sys_meta,
}
fixed = dict(instance, task_state=None)
self.mox.StubOutWithMock(compute_utils, "get_nw_info_for_instance")
self.mox.StubOutWithMock(utils, "instance_sys_meta")
self.mox.StubOutWithMock(self.compute.driver, "plug_vifs")
self.mox.StubOutWithMock(self.compute.driver, "finish_revert_migration")
self.mox.StubOutWithMock(self.compute, "_get_instance_volume_block_device_info")
self.mox.StubOutWithMock(self.compute.driver, "get_info")
self.mox.StubOutWithMock(self.compute, "_instance_update")
compute_utils.get_nw_info_for_instance(instance).AndReturn(network_model.NetworkInfo())
self.compute.driver.plug_vifs(instance, [])
utils.instance_sys_meta(instance).AndReturn(sys_meta)
self.compute._get_instance_volume_block_device_info(self.context, instance).AndReturn([])
self.compute.driver.finish_revert_migration(instance, [], [], power_on)
self.compute._instance_update(self.context, instance["uuid"], task_state=None).AndReturn(fixed)
self.compute.driver.get_info(fixed).AndReturn({"state": power_state.SHUTDOWN})
self.mox.ReplayAll()
self.compute._init_instance(self.context, instance)
示例2: _add_floating_ip
def _add_floating_ip(self, req, id, body):
"""Associate floating_ip to an instance."""
context = req.environ['nova.context']
authorize(context)
address = body['addFloatingIp']['address']
instance = common.get_instance(self.compute_api, context, id,
want_objects=True)
cached_nwinfo = compute_utils.get_nw_info_for_instance(instance)
if not cached_nwinfo:
msg = _('No nw_info cache associated with instance')
raise webob.exc.HTTPBadRequest(explanation=msg)
fixed_ips = cached_nwinfo.fixed_ips()
if not fixed_ips:
msg = _('No fixed ips associated to instance')
raise webob.exc.HTTPBadRequest(explanation=msg)
fixed_address = None
if 'fixed_address' in body['addFloatingIp']:
fixed_address = body['addFloatingIp']['fixed_address']
for fixed in fixed_ips:
if fixed['address'] == fixed_address:
break
else:
msg = _('Specified fixed address not assigned to instance')
raise webob.exc.HTTPBadRequest(explanation=msg)
if not fixed_address:
fixed_address = fixed_ips[0]['address']
if len(fixed_ips) > 1:
LOG.warning(_LW('multiple fixed_ips exist, using the first: '
'%s'), fixed_address)
try:
self.network_api.associate_floating_ip(context, instance,
floating_address=address,
fixed_address=fixed_address)
except exception.FloatingIpAssociated:
msg = _('floating ip is already associated')
raise webob.exc.HTTPBadRequest(explanation=msg)
except exception.NoFloatingIpInterface:
msg = _('l3driver call to add floating ip failed')
raise webob.exc.HTTPBadRequest(explanation=msg)
except exception.FloatingIpNotFoundForAddress:
msg = _('floating ip not found')
raise webob.exc.HTTPNotFound(explanation=msg)
except exception.Forbidden as e:
raise webob.exc.HTTPForbidden(explanation=e.format_message())
except Exception as e:
msg = _('Unable to associate floating ip %(address)s to '
'fixed ip %(fixed_address)s for instance %(id)s. '
'Error: %(error)s') % (
{'address': address, 'fixed_address': fixed_address,
'id': id, 'error': e})
LOG.exception(msg)
raise webob.exc.HTTPBadRequest(explanation=msg)
return webob.Response(status_int=202)
示例3: _prepare_instance
def _prepare_instance(self, context, instance):
instance["name"] = instance["display_name"]
instance["status"] = self._status_map.get(
instance["vm_state"], instance["vm_state"])
image_id = instance["image_ref"]
if image_id is None or len(image_id) == 0:
image_id = instance["system_metadata"]["image_base_image_ref"]
if image_id is None or len(image_id) == 0:
image_id = instance["system_metadata"]["image_image_id"]
image = image_api.API().get_item_by_id(context, image_id)
if image is not None:
instance["image"] = image['name']
instance["cached_nwinfo"] = \
compute_utils.get_nw_info_for_instance(instance)
attached_disks = db.block_device_mapping_get_all_by_instance(
nova_context.get_admin_context(), instance['uuid'])
for disk in attached_disks:
if disk["volume_id"] is not None:
disk["volume"] = disk_api.API().get_item_by_id(
context, disk["volume_id"])
instance["attached_disks"] = attached_disks
return instance
示例4: get_vifs_for_instance
def get_vifs_for_instance(self, context, **kwargs):
"""Return the list of VIF for an instance."""
instance_id = kwargs['instance_id']
LOG.debug('get_vifs_for_instance %s' % instance_id)
instance = objects.Instance.get_by_uuid(
nova_context.get_admin_context(), instance_id)
hyper_net_info = compute_utils.get_nw_info_for_instance(instance)
neutron = neutronapi.get_client(context, admin=True)
check_host_exist(neutron, instance_id)
tenant_ids = []
LOG.debug('hyper_net_info: %s' % hyper_net_info)
for vif in hyper_net_info:
tenant_ids.append(vif['network']['meta']['tenant_id'])
neutron.update_port(vif['id'],
{'port': {'binding:host_id': instance_id}})
# get all the tenant router
LOG.debug('tenant_ids: %s' % tenant_ids)
for tenant_id in tenant_ids:
routers = neutron.list_routers({'tenant_id': tenant_id})['routers']
LOG.debug('routers: %s' % routers)
for router in routers:
neutron.update_router(router['id'],
{'router': {'admin_state_up': 'False'}})
neutron.update_router(router['id'],
{'router': {'admin_state_up': 'True'}})
return hyper_net_info
示例5: get_vif_for_provider_ip
def get_vif_for_provider_ip(self, context, **kwargs):
"""Return the VIF for a VM."""
provider_ip = kwargs['provider_ip']
LOG.debug("provider ip = % s" % provider_ip)
# retrieve the instance id from the provider ip
# from the nova metadata
filters = {
'filter': [{'name': 'tag:provider_ip', 'value': provider_ip}]
}
instances = objects.InstanceList.get_by_filters(
context, filters=filters)
# should return only one and check it
if len(instances) == 1:
instance = instances[0]
vif_id = instance.metadata['ip_%s' % provider_ip]
hyper_net_info = compute_utils.get_nw_info_for_instance(instance)
hyper_vif = None
for vif in hyper_net_info:
if vif.get('id') == vif_id:
hyper_vif = vif
break
neutron = neutronapi.get_client(context, admin=True)
check_host_exist(neutron, instance.uuid)
neutron.update_port(hyper_vif,
{'port': {'binding:host_id': instance.uuid}})
return {'instance_id': instance.uuid, 'hyper_vif': hyper_vif}
else:
return None
示例6: add_floating_ip
def add_floating_ip(uid, pool_name, context):
"""
Adds an ip to an VM instance.
uid -- id of the VM.
pool_name -- name of the pool
context -- The os context.
"""
vm_instance = vm.get_vm(uid, context)
cached_nwinfo = utils.get_nw_info_for_instance(vm_instance)
if not cached_nwinfo:
raise AttributeError('No nw_info cache associated with instance')
fixed_ips = cached_nwinfo.fixed_ips()
if not fixed_ips:
raise AttributeError('No fixed ips associated to instance')
float_address = NETWORK_API.allocate_floating_ip(context, pool_name)
try:
address = fixed_ips[0]['address']
NETWORK_API.associate_floating_ip(context, vm_instance,
float_address, address)
except exception.FloatingIpAssociated:
msg = 'floating ip is already associated'
raise AttributeError(msg)
except exception.NoFloatingIpInterface:
msg = 'l3driver call to add floating ip failed'
raise AttributeError(msg)
return float_address
示例7: get_vifs_for_instance
def get_vifs_for_instance(self, context, **kwargs):
"""Return the list of VIF for an instance."""
instance_id = kwargs['instance_id']
LOG.debug("get_vifs_for_instance %s" % instance_id)
instance = objects.Instance.get_by_uuid(
nova_context.get_admin_context(), instance_id)
net_info = compute_utils.get_nw_info_for_instance(instance)
# TODO: retrieve the provider_net_info (IP/MAC)
return {'net_info': net_info,
'provider_net_info': [None, None, None]}
示例8: _get_instances_with_network
def _get_instances_with_network(self, context, network, zone_id):
affected_instances = []
network_id = network['id']
instances = self.get_items(context, zone_id)
for instance in instances:
cached_nwinfo = compute_utils.get_nw_info_for_instance(instance)
if cached_nwinfo:
for network_info in cached_nwinfo:
if network_id == network_info['network']['id']:
affected_instances.append(instance)
return affected_instances
示例9: _add_floating_ip
def _add_floating_ip(self, req, id, body):
"""Associate floating_ip to an instance."""
context = req.environ['nova.context']
authorize(context)
try:
address = body['addFloatingIp']['address']
except TypeError:
msg = _("Missing parameter dict")
raise webob.exc.HTTPBadRequest(explanation=msg)
except KeyError:
msg = _("Address not specified")
raise webob.exc.HTTPBadRequest(explanation=msg)
instance = self.compute_api.get(context, id)
cached_nwinfo = compute_utils.get_nw_info_for_instance(instance)
if not cached_nwinfo:
msg = _('No nw_info cache associated with instance')
raise webob.exc.HTTPBadRequest(explanation=msg)
fixed_ips = cached_nwinfo.fixed_ips()
if not fixed_ips:
msg = _('No fixed ips associated to instance')
raise webob.exc.HTTPBadRequest(explanation=msg)
# TODO(tr3buchet): this will associate the floating IP with the
# first fixed_ip an instance has. This should be
# changed to support specifying a particular fixed_ip if
# multiple exist.
if len(fixed_ips) > 1:
msg = _('multiple fixed_ips exist, using the first: %s')
LOG.warning(msg, fixed_ips[0]['address'])
try:
self.network_api.associate_floating_ip(context, instance,
floating_address=address,
fixed_address=fixed_ips[0]['address'])
except exception.FloatingIpAssociated:
msg = _('floating ip is already associated')
raise webob.exc.HTTPBadRequest(explanation=msg)
except exception.NoFloatingIpInterface:
msg = _('l3driver call to add floating ip failed')
raise webob.exc.HTTPBadRequest(explanation=msg)
except (exception.FloatingIpNotFoundForAddress,
exception.NotAuthorized):
msg = _('floating ip not found')
raise webob.exc.HTTPNotFound(explanation=msg)
except Exception:
msg = _('Error. Unable to associate floating ip')
LOG.exception(msg)
raise webob.exc.HTTPBadRequest(explanation=msg)
return webob.Response(status_int=202)
示例10: _get_existing_networks
def _get_existing_networks(self, context, server_id):
"""Returns networks a server is already connected to."""
instance = self.get_instance(context, server_id)
nw_info = compute_utils.get_nw_info_for_instance(instance)
networks = []
for vif in nw_info:
networks.append(vif["network"]["id"])
if not networks:
return set()
return set(networks)
示例11: _test_init_instance_reverts_crashed_migrations
def _test_init_instance_reverts_crashed_migrations(self,
old_vm_state=None):
power_on = True if (not old_vm_state or
old_vm_state == vm_states.ACTIVE) else False
sys_meta = {
'old_vm_state': old_vm_state
}
instance = {
'uuid': 'foo',
'vm_state': vm_states.ERROR,
'task_state': task_states.RESIZE_MIGRATING,
'power_state': power_state.SHUTDOWN,
'system_metadata': sys_meta
}
fixed = dict(instance, task_state=None)
self.mox.StubOutWithMock(compute_utils, 'get_nw_info_for_instance')
self.mox.StubOutWithMock(utils, 'instance_sys_meta')
self.mox.StubOutWithMock(self.compute.driver, 'plug_vifs')
self.mox.StubOutWithMock(self.compute.driver,
'finish_revert_migration')
self.mox.StubOutWithMock(self.compute,
'_get_instance_volume_block_device_info')
self.mox.StubOutWithMock(self.compute.driver, 'get_info')
self.mox.StubOutWithMock(self.compute, '_instance_update')
compute_utils.get_nw_info_for_instance(instance).AndReturn(
network_model.NetworkInfo())
self.compute.driver.plug_vifs(instance, [])
utils.instance_sys_meta(instance).AndReturn(sys_meta)
self.compute._get_instance_volume_block_device_info(
self.context, instance).AndReturn([])
self.compute.driver.finish_revert_migration(instance, [], [], power_on)
self.compute._instance_update(self.context, instance['uuid'],
task_state=None).AndReturn(fixed)
self.compute.driver.get_info(fixed).AndReturn(
{'state': power_state.SHUTDOWN})
self.mox.ReplayAll()
self.compute._init_instance(self.context, instance)
示例12: get_networks_for_instance
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}]},
...}
"""
nw_info = compute_utils.get_nw_info_for_instance(instance)
return get_networks_for_instance_from_nw_info(nw_info)
示例13: _gather_port_ids
def _gather_port_ids(self, context, instance,
port_ids=None):
"""Return an instance's complete list of port_ids."""
ifaces = compute_utils.get_nw_info_for_instance(instance)
# This code path is only done when refreshing the network_cache
if port_ids is None:
port_ids = [iface['id'] for iface in ifaces]
else:
# an interface was added/removed from instance.
# Include existing interfaces so they are not removed from the db.
port_ids = [iface['id'] for iface in ifaces] + port_ids
return port_ids
示例14: _get_network_info
def _get_network_info(self, context, server_id, entity_maker):
"""Returns a list of VIFs, transformed through entity_maker."""
instance = self._get_instance(context, server_id)
nw_info = compute_utils.get_nw_info_for_instance(instance)
vifs = []
for vif in nw_info:
addr = [dict(network_id=vif["network"]["id"],
network_label=vif["network"]["label"],
address=ip["address"]) for ip in vif.fixed_ips()]
v = dict(address=vif["address"],
id=vif["id"],
ip_addresses=addr)
vifs.append(entity_maker(context, v))
return {'virtual_interfaces': vifs}
示例15: __init__
def __init__(self, instance, **kwargs):
super(InstancePayload, self).__init__(**kwargs)
# Note(gibi): ugly but needed to avoid cyclic import
from nova.compute import utils
network_info = utils.get_nw_info_for_instance(instance)
ips = IpPayload.from_network_info(network_info)
flavor = flavor_payload.FlavorPayload(flavor=instance.flavor)
super(InstancePayload, self).__init__(
ip_addresses=ips,
flavor=flavor,
**kwargs)
self.populate_schema(instance=instance)