def reserve_specific_vlan(session, physical_network, vlan_id): with session.begin(subtransactions=True): try: alloc = (session.query(ovs_models_v2.VlanAllocation).filter_by( physical_network=physical_network, vlan_id=vlan_id).with_lockmode('update').one()) if alloc.allocated: if vlan_id == constants.FLAT_VLAN_ID: raise q_exc.FlatNetworkInUse( physical_network=physical_network) else: raise q_exc.VlanIdInUse(vlan_id=vlan_id, physical_network=physical_network) LOG.debug( _("Reserving specific vlan %(vlan_id)s on physical " "network %(physical_network)s from pool"), { 'vlan_id': vlan_id, 'physical_network': physical_network }) alloc.allocated = True except exc.NoResultFound: LOG.debug( _("Reserving specific vlan %(vlan_id)s on physical " "network %(physical_network)s outside pool"), { 'vlan_id': vlan_id, 'physical_network': physical_network }) alloc = ovs_models_v2.VlanAllocation(physical_network, vlan_id) alloc.allocated = True session.add(alloc)
def sync_vlan_allocations(network_vlan_ranges): """Synchronize vlan_allocations table with configured VLAN ranges.""" session = db.get_session() with session.begin(): # get existing allocations for all physical networks allocations = dict() allocs = (session.query(ovs_models_v2.VlanAllocation).all()) for alloc in allocs: if alloc.physical_network not in allocations: allocations[alloc.physical_network] = set() allocations[alloc.physical_network].add(alloc) # process vlan ranges for each configured physical network for physical_network, vlan_ranges in network_vlan_ranges.iteritems(): # determine current configured allocatable vlans for this # physical network vlan_ids = set() for vlan_range in vlan_ranges: vlan_ids |= set(xrange(vlan_range[0], vlan_range[1] + 1)) # remove from table unallocated vlans not currently allocatable if physical_network in allocations: for alloc in allocations[physical_network]: try: # see if vlan is allocatable vlan_ids.remove(alloc.vlan_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 vlan %(vlan_id)s on " "physical network " "%(physical_network)s from pool"), { 'vlan_id': alloc.vlan_id, 'physical_network': physical_network }) session.delete(alloc) del allocations[physical_network] # add missing allocatable vlans to table for vlan_id in sorted(vlan_ids): alloc = ovs_models_v2.VlanAllocation(physical_network, vlan_id) session.add(alloc) # remove from table unallocated vlans for any unconfigured physical # networks for allocs in allocations.itervalues(): for alloc in allocs: if not alloc.allocated: LOG.debug( _("Removing vlan %(vlan_id)s on physical " "network %(physical_network)s from pool"), { 'vlan_id': alloc.vlan_id, 'physical_network': alloc.physical_network }) session.delete(alloc)