def sync_tunnel_allocations(tunnel_id_ranges): """Synchronize tunnel_allocations table with configured tunnel ranges""" # determine current configured allocatable tunnels tunnel_ids = set() for tunnel_id_range in tunnel_id_ranges: tun_min, tun_max = tunnel_id_range if tun_max + 1 - tun_min > 1000000: LOG.error("Skipping unreasonable tunnel ID range %s:%s" % tunnel_id_range) else: tunnel_ids |= set(xrange(tun_min, tun_max + 1)) session = db.get_session() with session.begin(): # remove from table unallocated tunnels not currently allocatable allocs = (session.query(ovs_models_v2.TunnelAllocation).all()) for alloc in allocs: try: # see if tunnel is allocatable tunnel_ids.remove(alloc.tunnel_id) except KeyError: # it's not allocatable, so check if its allocated if not alloc.allocated: # it's not, so remove it from table LOG.debug("removing tunnel %s from pool" % alloc.tunnel_id) session.delete(alloc) # add missing allocatable tunnels to table for tunnel_id in sorted(tunnel_ids): alloc = ovs_models_v2.TunnelAllocation(tunnel_id) session.add(alloc)
def reserve_specific_tunnel(session, tunnel_id): with session.begin(subtransactions=True): try: alloc = (session.query(ovs_models_v2.TunnelAllocation).filter_by( tunnel_id=tunnel_id).one()) if alloc.allocated: raise q_exc.TunnelIdInUse(tunnel_id=tunnel_id) LOG.debug("reserving specific tunnel %s from pool" % tunnel_id) alloc.allocated = True except exc.NoResultFound: LOG.debug("reserving specific tunnel %s outside pool" % tunnel_id) alloc = ovs_models_v2.TunnelAllocation(tunnel_id) alloc.allocated = True session.add(alloc)