neutronv2: only create client once when adding/removing fixed IPs

We don't need to create a neutron client object (session) every time we
need to make an API call in add_fixed_ip_to_instance or
remove_fixed_ip_from_instance, especially when looping over ports and
subnets.

Just create the client once at the beginning of the method and reuse it.

Closes-Bug: #1430481

Change-Id: If9181c2ef5fb94652d0205d6d69521bcc5d85cff
This commit is contained in:
Matt Riedemann 2015-03-10 13:54:52 -07:00
parent e5ed57dc3f
commit 7560620da7

View File

@ -751,8 +751,9 @@ class API(base_api.NetworkAPI):
@base_api.refresh_cache
def add_fixed_ip_to_instance(self, context, instance, network_id):
"""Add a fixed ip to the instance from specified network."""
neutron = get_client(context)
search_opts = {'network_id': network_id}
data = get_client(context).list_subnets(**search_opts)
data = neutron.list_subnets(**search_opts)
ipam_subnets = data.get('subnets', [])
if not ipam_subnets:
raise exception.NetworkNotFoundForInstance(
@ -762,7 +763,7 @@ class API(base_api.NetworkAPI):
search_opts = {'device_id': instance.uuid,
'device_owner': zone,
'network_id': network_id}
data = get_client(context).list_ports(**search_opts)
data = neutron.list_ports(**search_opts)
ports = data['ports']
for p in ports:
for subnet in ipam_subnets:
@ -770,8 +771,7 @@ class API(base_api.NetworkAPI):
fixed_ips.append({'subnet_id': subnet['id']})
port_req_body = {'port': {'fixed_ips': fixed_ips}}
try:
get_client(context).update_port(p['id'],
port_req_body)
neutron.update_port(p['id'], port_req_body)
return self._get_instance_nw_info(context, instance)
except Exception as ex:
msg = ("Unable to update port %(portid)s on subnet "
@ -786,11 +786,12 @@ class API(base_api.NetworkAPI):
@base_api.refresh_cache
def remove_fixed_ip_from_instance(self, context, instance, address):
"""Remove a fixed ip from the instance."""
neutron = get_client(context)
zone = 'compute:%s' % instance.availability_zone
search_opts = {'device_id': instance.uuid,
'device_owner': zone,
'fixed_ips': 'ip_address=%s' % address}
data = get_client(context).list_ports(**search_opts)
data = neutron.list_ports(**search_opts)
ports = data['ports']
for p in ports:
fixed_ips = p['fixed_ips']
@ -800,8 +801,7 @@ class API(base_api.NetworkAPI):
new_fixed_ips.append(fixed_ip)
port_req_body = {'port': {'fixed_ips': new_fixed_ips}}
try:
get_client(context).update_port(p['id'],
port_req_body)
neutron.update_port(p['id'], port_req_body)
except Exception as ex:
msg = ("Unable to update port %(portid)s with"
" failure: %(exception)s")