2 * Copyright (c) 2016, 2017 Ericsson India Global Services Pvt Ltd. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.genius.idmanager;
11 import static org.opendaylight.controller.md.sal.binding.api.WriteTransaction.CREATE_MISSING_PARENTS;
13 import com.google.common.base.Optional;
14 import com.google.common.net.InetAddresses;
15 import java.net.InetAddress;
16 import java.net.UnknownHostException;
17 import java.util.ArrayList;
18 import java.util.LinkedList;
19 import java.util.List;
20 import java.util.concurrent.CompletableFuture;
21 import java.util.concurrent.ConcurrentHashMap;
22 import java.util.concurrent.CountDownLatch;
23 import java.util.concurrent.ExecutionException;
24 import java.util.concurrent.Future;
25 import java.util.concurrent.atomic.AtomicInteger;
26 import javax.annotation.Nonnull;
27 import javax.annotation.Nullable;
28 import javax.inject.Singleton;
29 import org.opendaylight.genius.idmanager.ReleasedIdHolder.DelayedIdEntry;
30 import org.opendaylight.genius.infra.Datastore.Configuration;
31 import org.opendaylight.genius.infra.TypedWriteTransaction;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdPools;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.IdPool;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.IdPoolBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.IdPoolKey;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.id.pool.AvailableIdsHolder;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.id.pool.AvailableIdsHolderBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.id.pool.ChildPools;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.id.pool.ChildPoolsBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.id.pool.ChildPoolsKey;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.id.pool.IdEntries;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.id.pool.IdEntriesBuilder;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.id.pool.IdEntriesKey;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.id.pool.ReleasedIdsHolder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.id.pool.ReleasedIdsHolderBuilder;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.released.ids.DelayedIdEntries;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.released.ids.DelayedIdEntriesBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.lockmanager.rev160413.LockInput;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.lockmanager.rev160413.LockInputBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.lockmanager.rev160413.LockManagerService;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.lockmanager.rev160413.LockOutput;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.lockmanager.rev160413.UnlockInput;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.lockmanager.rev160413.UnlockInputBuilder;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.lockmanager.rev160413.UnlockOutput;
55 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
56 import org.opendaylight.yangtools.yang.common.RpcResult;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
61 public class IdUtils {
63 private static final Logger LOG = LoggerFactory.getLogger(IdUtils.class);
65 public static final long DEFAULT_DELAY_TIME = 30;
66 private static final long DEFAULT_AVAILABLE_ID_COUNT = 0;
67 private static final int DEFAULT_BLOCK_SIZE_DIFF = 10;
68 public static final int RETRY_COUNT = 6;
70 private final ConcurrentHashMap<String, CompletableFuture<List<Long>>> allocatedIdMap = new ConcurrentHashMap<>();
71 private final ConcurrentHashMap<String, CountDownLatch> releaseIdLatchMap = new ConcurrentHashMap<>();
72 private final ConcurrentHashMap<String, AtomicInteger> poolUpdatedMap = new ConcurrentHashMap<>();
74 private final int bladeId;
76 public IdUtils() throws UnknownHostException {
77 bladeId = InetAddresses.coerceToInteger(InetAddress.getLocalHost());
80 public CompletableFuture<List<Long>> removeAllocatedIds(String uniqueIdKey) {
81 return allocatedIdMap.remove(uniqueIdKey);
84 public CompletableFuture<List<Long>> putAllocatedIdsIfAbsent(String uniqueIdKey,
85 CompletableFuture<List<Long>> futureIdValues) {
86 return allocatedIdMap.putIfAbsent(uniqueIdKey, futureIdValues);
89 public void putReleaseIdLatch(String uniqueIdKey, CountDownLatch latch) {
90 releaseIdLatchMap.put(uniqueIdKey, latch);
93 public CountDownLatch getReleaseIdLatch(String uniqueIdKey) {
94 return releaseIdLatchMap.get(uniqueIdKey);
97 public CountDownLatch removeReleaseIdLatch(String uniqueIdKey) {
98 return releaseIdLatchMap.remove(uniqueIdKey);
101 public InstanceIdentifier<IdEntries> getIdEntry(InstanceIdentifier<IdPool> poolName, String idKey) {
102 InstanceIdentifier.InstanceIdentifierBuilder<IdEntries> idEntriesBuilder = poolName
103 .builder().child(IdEntries.class, new IdEntriesKey(idKey));
104 return idEntriesBuilder.build();
107 public IdEntries createIdEntries(String idKey, List<Long> newIdVals) {
108 return new IdEntriesBuilder().withKey(new IdEntriesKey(idKey))
109 .setIdKey(idKey).setIdValue(newIdVals).build();
112 public DelayedIdEntries createDelayedIdEntry(long idValue, long delayTime) {
113 return new DelayedIdEntriesBuilder()
115 .setReadyTimeSec(delayTime).build();
118 protected IdPool createGlobalPool(String poolName, long low, long high, long blockSize) {
119 AvailableIdsHolder availableIdsHolder = createAvailableIdsHolder(low, high, low - 1);
120 ReleasedIdsHolder releasedIdsHolder = createReleasedIdsHolder(DEFAULT_AVAILABLE_ID_COUNT, 0);
121 int size = (int) blockSize;
122 return new IdPoolBuilder().withKey(new IdPoolKey(poolName))
123 .setBlockSize(size).setPoolName(poolName)
124 .setAvailableIdsHolder(availableIdsHolder)
125 .setReleasedIdsHolder(releasedIdsHolder).build();
128 public AvailableIdsHolder createAvailableIdsHolder(long low, long high, long cursor) {
129 return new AvailableIdsHolderBuilder()
130 .setStart(low).setEnd(high).setCursor(cursor).build();
133 protected ReleasedIdsHolder createReleasedIdsHolder(long availableIdCount, long delayTime) {
134 return new ReleasedIdsHolderBuilder()
135 .setAvailableIdCount(availableIdCount)
136 .setDelayedTimeSec(delayTime).build();
139 public InstanceIdentifier<IdPool> getIdPoolInstance(String poolName) {
140 InstanceIdentifier.InstanceIdentifierBuilder<IdPool> idPoolBuilder = InstanceIdentifier
141 .builder(IdPools.class).child(IdPool.class,
142 new IdPoolKey(poolName));
143 return idPoolBuilder.build();
146 public InstanceIdentifier<ReleasedIdsHolder> getReleasedIdsHolderInstance(String poolName) {
147 InstanceIdentifier.InstanceIdentifierBuilder<ReleasedIdsHolder> releasedIdsHolder = InstanceIdentifier
148 .builder(IdPools.class).child(IdPool.class,
149 new IdPoolKey(poolName)).child(ReleasedIdsHolder.class);
150 return releasedIdsHolder.build();
153 protected boolean isIdAvailable(AvailableIdsHolderBuilder availableIds) {
154 if (availableIds.getCursor() != null && availableIds.getEnd() != null) {
155 return availableIds.getCursor() < availableIds.getEnd();
160 // public only to re-use this from IdManagerTest
161 public String getLocalPoolName(String poolName) {
162 return poolName + "." + bladeId;
165 protected ChildPools createChildPool(String childPoolName) {
166 return new ChildPoolsBuilder().withKey(new ChildPoolsKey(childPoolName)).setChildPoolName(childPoolName)
167 .setLastAccessTime(System.currentTimeMillis() / 1000).build();
170 protected AvailableIdsHolderBuilder getAvailableIdsHolderBuilder(IdPool pool) {
171 AvailableIdsHolder availableIds = pool.getAvailableIdsHolder();
172 if (availableIds != null) {
173 return new AvailableIdsHolderBuilder(availableIds);
175 return new AvailableIdsHolderBuilder();
178 protected static ReleasedIdsHolderBuilder getReleaseIdsHolderBuilder(IdPool pool) {
179 ReleasedIdsHolder releasedIds = pool.getReleasedIdsHolder();
180 if (releasedIds != null) {
181 return new ReleasedIdsHolderBuilder(releasedIds);
183 return new ReleasedIdsHolderBuilder();
187 * Changes made to the parameters passed are not persisted to the Datastore.
188 * Method invoking should ensure that these gets persisted.
190 public void freeExcessAvailableIds(ReleasedIdHolder releasedIdHolder,
191 ReleasedIdsHolderBuilder releasedIdsParent, long idCountToBeFreed) {
192 List<DelayedIdEntries> existingDelayedIdEntriesInParent = releasedIdsParent.getDelayedIdEntries();
193 long availableIdCountChild = releasedIdHolder.getAvailableIdCount();
194 if (existingDelayedIdEntriesInParent == null) {
195 existingDelayedIdEntriesInParent = new LinkedList<>();
197 idCountToBeFreed = Math.min(idCountToBeFreed, availableIdCountChild);
198 for (int index = 0; index < idCountToBeFreed; index++) {
199 Optional<Long> idValueOptional = releasedIdHolder.allocateId();
200 if (!idValueOptional.isPresent()) {
203 long idValue = idValueOptional.get();
204 DelayedIdEntries delayedIdEntries = new DelayedIdEntriesBuilder().setId(idValue)
205 .setReadyTimeSec(System.currentTimeMillis() / 1000).build();
206 existingDelayedIdEntriesInParent.add(delayedIdEntries);
208 long availableIdCountParent = releasedIdsParent.getAvailableIdCount();
209 releasedIdsParent.setDelayedIdEntries(existingDelayedIdEntriesInParent)
210 .setAvailableIdCount(availableIdCountParent + idCountToBeFreed);
213 public InstanceIdentifier<IdEntries> getIdEntriesInstanceIdentifier(String poolName, String idKey) {
214 return InstanceIdentifier
215 .builder(IdPools.class).child(IdPool.class,
216 new IdPoolKey(poolName)).child(IdEntries.class, new IdEntriesKey(idKey)).build();
219 protected InstanceIdentifier<ChildPools> getChildPoolsInstanceIdentifier(String poolName, String localPoolName) {
220 return InstanceIdentifier
221 .builder(IdPools.class)
222 .child(IdPool.class, new IdPoolKey(poolName))
223 .child(ChildPools.class, new ChildPoolsKey(localPoolName)).build();
226 public long computeBlockSize(long low, long high) {
229 long diff = high - low;
230 if (diff > DEFAULT_BLOCK_SIZE_DIFF) {
231 blockSize = diff / DEFAULT_BLOCK_SIZE_DIFF;
238 public long getAvailableIdsCount(AvailableIdsHolderBuilder availableIds) {
239 if (availableIds != null && isIdAvailable(availableIds)) {
240 return availableIds.getEnd() - availableIds.getCursor();
245 public void lock(LockManagerService lockManager, String poolName) throws IdManagerException {
246 LockInput input = new LockInputBuilder().setLockName(poolName).build();
247 Future<RpcResult<LockOutput>> result = lockManager.lock(input);
249 if (result != null && result.get().isSuccessful()) {
250 if (LOG.isDebugEnabled()) {
251 LOG.debug("Acquired lock {}", poolName);
254 throw new IdManagerException(String.format("Unable to getLock for pool %s", poolName));
256 } catch (InterruptedException | ExecutionException e) {
257 LOG.error("Unable to getLock for pool {}", poolName, e);
258 throw new RuntimeException(String.format("Unable to getLock for pool %s", poolName), e);
262 public void unlock(LockManagerService lockManager, String poolName) {
263 UnlockInput input = new UnlockInputBuilder().setLockName(poolName).build();
264 Future<RpcResult<UnlockOutput>> result = lockManager.unlock(input);
266 if (result != null && result.get().isSuccessful()) {
267 if (LOG.isDebugEnabled()) {
268 LOG.debug("Unlocked {}", poolName);
271 if (LOG.isDebugEnabled()) {
272 LOG.debug("Unable to unlock pool {}", poolName);
275 } catch (InterruptedException | ExecutionException e) {
276 LOG.error("Unable to unlock for pool {}", poolName, e);
277 throw new RuntimeException(String.format("Unable to unlock pool %s", poolName), e);
281 public InstanceIdentifier<IdPools> getIdPools() {
282 return InstanceIdentifier.builder(IdPools.class).build();
285 public void syncReleaseIdHolder(ReleasedIdHolder releasedIdHolder, IdPoolBuilder idPool) {
286 long delayTime = releasedIdHolder.getTimeDelaySec();
287 ReleasedIdsHolderBuilder releasedIdsBuilder = new ReleasedIdsHolderBuilder();
288 List<DelayedIdEntries> delayedIdEntriesList = new ArrayList<>();
289 List<DelayedIdEntry> delayList = releasedIdHolder.getDelayedEntries();
290 for (DelayedIdEntry delayedId : delayList) {
291 DelayedIdEntries delayedIdEntry = createDelayedIdEntry(delayedId.getId(), delayedId.getReadyTimeSec());
292 delayedIdEntriesList.add(delayedIdEntry);
294 releasedIdsBuilder.setAvailableIdCount((long) delayedIdEntriesList.size()).setDelayedTimeSec(delayTime)
295 .setDelayedIdEntries(delayedIdEntriesList);
296 idPool.setReleasedIdsHolder(releasedIdsBuilder.build());
299 public void syncAvailableIdHolder(AvailableIdHolder availableIdHolder, IdPoolBuilder idPool) {
300 long cur = availableIdHolder.getCur().get();
301 long low = availableIdHolder.getLow();
302 long high = availableIdHolder.getHigh();
303 AvailableIdsHolder availableIdsHolder = createAvailableIdsHolder(low, high, cur);
304 idPool.setAvailableIdsHolder(availableIdsHolder);
307 public void updateChildPool(TypedWriteTransaction<Configuration> tx, String poolName, String localPoolName) {
308 ChildPools childPool = createChildPool(localPoolName);
309 InstanceIdentifier<ChildPools> childPoolInstanceIdentifier =
310 getChildPoolsInstanceIdentifier(poolName, localPoolName);
311 tx.merge(childPoolInstanceIdentifier, childPool, CREATE_MISSING_PARENTS);
314 public void incrementPoolUpdatedMap(String localPoolName) {
315 AtomicInteger value = poolUpdatedMap.putIfAbsent(localPoolName, new AtomicInteger(0));
317 value = poolUpdatedMap.get(localPoolName);
319 value.incrementAndGet();
322 public void decrementPoolUpdatedMap(String localPoolName) {
323 AtomicInteger value = poolUpdatedMap.get(localPoolName);
324 if (value != null && value.get() >= 1) {
325 value.decrementAndGet();
329 public boolean getPoolUpdatedMap(String localPoolName) {
330 AtomicInteger value = poolUpdatedMap.get(localPoolName);
331 return value != null && value.get() > 0;
334 public void removeFromPoolUpdatedMap(String localPoolName) {
335 poolUpdatedMap.remove(localPoolName);
338 public String getUniqueKey(String parentPoolName, String idKey) {
339 return parentPoolName + idKey;
342 // TODO Replace this with mdsal's DataObjectUtils.nullToEmpty when upgrading to mdsal 3.0.2
344 public static <T> List<T> nullToEmpty(final @Nullable List<T> input) {
345 return input != null ? input : new ArrayList<>(0);