'Add a fixed IP to the instance from specified network.'

@base_api.refresh_cache
def add_fixed_ip_to_instance(self, context, instance, network_id):

    neutron = get_client(context)
    search_opts = {'network_id': network_id}
    data = neutron.list_subnets(**search_opts)
    ipam_subnets = data.get('subnets', [])
    if (not ipam_subnets):
        raise exception.NetworkNotFoundForInstance(instance_id=instance.uuid)
    zone = ('compute:%s' % instance.availability_zone)
    search_opts = {'device_id': instance.uuid, 'device_owner': zone, 'network_id': network_id}
    data = neutron.list_ports(**search_opts)
    ports = data['ports']
    for p in ports:
        for subnet in ipam_subnets:
            fixed_ips = p['fixed_ips']
            fixed_ips.append({'subnet_id': subnet['id']})
            port_req_body = {'port': {'fixed_ips': fixed_ips}}
            try:
                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    %(subnet_id)s    with    failure:    %(exception)s'
                LOG.debug(msg, {'portid': p['id'], 'subnet_id': subnet['id'], 'exception': ex}, instance=instance)
    raise exception.NetworkNotFoundForInstance(instance_id=instance.uuid)
