Merge "avoiding logging full stack trace in case of id doesn't exist"
[genius.git] / idmanager / idmanager-impl / src / main / java / org / opendaylight / genius / idmanager / IdManager.java
1 /*
2  * Copyright (c) 2016 Ericsson India Global Services Pvt Ltd. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.genius.idmanager;
10
11 import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.CONFIGURATION;
12
13 import com.google.common.base.Optional;
14 import com.google.common.util.concurrent.ListenableFuture;
15
16 import java.util.ArrayList;
17 import java.util.Collections;
18 import java.util.HashMap;
19 import java.util.LinkedList;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Timer;
23 import java.util.TimerTask;
24 import java.util.concurrent.CompletableFuture;
25 import java.util.concurrent.ConcurrentHashMap;
26 import java.util.concurrent.ConcurrentMap;
27 import java.util.concurrent.CopyOnWriteArrayList;
28 import java.util.concurrent.CountDownLatch;
29 import java.util.concurrent.ExecutionException;
30 import java.util.concurrent.Future;
31 import java.util.concurrent.TimeUnit;
32 import java.util.stream.Collectors;
33
34 import javax.annotation.PostConstruct;
35 import javax.annotation.PreDestroy;
36 import javax.inject.Inject;
37 import javax.inject.Singleton;
38
39 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
40 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
41 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
42 import org.opendaylight.genius.datastoreutils.DataStoreJobCoordinator;
43 import org.opendaylight.genius.datastoreutils.SingleTransactionDataBroker;
44 import org.opendaylight.genius.idmanager.ReleasedIdHolder.DelayedIdEntry;
45 import org.opendaylight.genius.idmanager.api.IdManagerMonitor;
46 import org.opendaylight.genius.idmanager.jobs.CleanUpJob;
47 import org.opendaylight.genius.idmanager.jobs.IdHolderSyncJob;
48 import org.opendaylight.genius.idmanager.jobs.LocalPoolCreateJob;
49 import org.opendaylight.genius.idmanager.jobs.LocalPoolDeleteJob;
50 import org.opendaylight.genius.idmanager.jobs.UpdateIdEntryJob;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutputBuilder;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdRangeInput;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdRangeOutput;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdRangeOutputBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.CreateIdPoolInput;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.DeleteIdPoolInput;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdPools;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.IdPool;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.IdPoolBuilder;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.IdPoolKey;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.id.pool.AvailableIdsHolder;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.id.pool.AvailableIdsHolderBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.id.pool.ChildPools;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.id.pool.IdEntries;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.id.pool.ReleasedIdsHolder;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.id.pools.id.pool.ReleasedIdsHolderBuilder;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.released.ids.DelayedIdEntries;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.lockmanager.rev160413.LockManagerService;
73 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
74 import org.opendaylight.yangtools.yang.common.OperationFailedException;
75 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
76 import org.opendaylight.yangtools.yang.common.RpcResult;
77 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
80
81 @Singleton
82 public class IdManager implements IdManagerService, IdManagerMonitor {
83
84     private static final Logger LOG = LoggerFactory.getLogger(IdManager.class);
85     private static final long DEFAULT_IDLE_TIME = 24 * 60 * 60;
86
87     private final DataBroker broker;
88     private final SingleTransactionDataBroker singleTxDB;
89     private final LockManagerService lockManager;
90     private final IdUtils idUtils;
91
92     private final ConcurrentMap<String, IdLocalPool> localPool;
93     private final Timer cleanJobTimer = new Timer();
94
95     @Inject
96     public IdManager(DataBroker db, LockManagerService lockManager, IdUtils idUtils) throws ReadFailedException {
97         this.broker = db;
98         this.singleTxDB = new SingleTransactionDataBroker(db);
99         this.lockManager = lockManager;
100         this.idUtils = idUtils;
101         this.localPool = new ConcurrentHashMap<>();
102         populateCache();
103     }
104
105     @Override
106     public Map<String, String> getLocalPoolsDetails() {
107         Map<String, String> map = new HashMap<>();
108         localPool.entrySet().stream().forEach(entry -> map.put(entry.getKey(), entry.getValue().toString()));
109         return map;
110     }
111
112     @PostConstruct
113     public void start() {
114         LOG.info("{} start", getClass().getSimpleName());
115     }
116
117     @PreDestroy
118     public void close() {
119         LOG.info("{} close", getClass().getSimpleName());
120     }
121
122     private void populateCache() throws ReadFailedException {
123         // If IP changes during reboot, then there will be orphaned child pools.
124         InstanceIdentifier<IdPools> idPoolsInstance = idUtils.getIdPools();
125         Optional<IdPools> idPoolsOptional = singleTxDB.syncReadOptional(CONFIGURATION, idPoolsInstance);
126         if (!idPoolsOptional.isPresent()) {
127             return;
128         }
129         IdPools idPools = idPoolsOptional.get();
130         List<IdPool> idPoolList = idPools.getIdPool();
131         idPoolList
132                 .parallelStream()
133                 .filter(idPool -> idPool.getParentPoolName() != null
134                         && !idPool.getParentPoolName().isEmpty()
135                         && idUtils.getLocalPoolName(idPool.getParentPoolName())
136                                 .equals(idPool.getPoolName()))
137                 .forEach(
138                     idPool -> updateLocalIdPoolCache(idPool,
139                         idPool.getParentPoolName()));
140     }
141
142     public boolean updateLocalIdPoolCache(IdPool idPool, String parentPoolName) {
143         AvailableIdsHolder availableIdsHolder = idPool.getAvailableIdsHolder();
144         AvailableIdHolder availableIdHolder = new AvailableIdHolder(idUtils, availableIdsHolder.getStart(),
145                 availableIdsHolder.getEnd());
146         availableIdHolder.setCur(availableIdsHolder.getCursor());
147         ReleasedIdsHolder releasedIdsHolder = idPool.getReleasedIdsHolder();
148         ReleasedIdHolder releasedIdHolder = new ReleasedIdHolder(idUtils, releasedIdsHolder.getDelayedTimeSec());
149         releasedIdHolder.setAvailableIdCount(releasedIdsHolder.getAvailableIdCount());
150         List<DelayedIdEntries> delayedEntries = releasedIdsHolder.getDelayedIdEntries();
151         List<DelayedIdEntry> delayedIdEntryInCache = new CopyOnWriteArrayList<>();
152         if (delayedEntries != null) {
153             delayedIdEntryInCache = delayedEntries
154                     .parallelStream()
155                     .map(delayedIdEntry -> new DelayedIdEntry(delayedIdEntry
156                             .getId(), delayedIdEntry.getReadyTimeSec()))
157                             .sorted((idEntry1, idEntry2) -> Long.compare(idEntry1.getReadyTimeSec(),
158                                     idEntry2.getReadyTimeSec())).collect(Collectors.toList());
159         }
160         releasedIdHolder.setDelayedEntries(delayedIdEntryInCache);
161
162         IdLocalPool idLocalPool = new IdLocalPool(idUtils, idPool.getPoolName());
163         idLocalPool.setAvailableIds(availableIdHolder);
164         idLocalPool.setReleasedIds(releasedIdHolder);
165         localPool.put(parentPoolName, idLocalPool);
166         if (LOG.isDebugEnabled()) {
167             LOG.debug("Populating cache for {} with {}", idLocalPool.getPoolName(), idLocalPool);
168         }
169         return true;
170     }
171
172     @Override
173     public Future<RpcResult<Void>> createIdPool(CreateIdPoolInput input) {
174         LOG.info("createIdPool called with input {}", input);
175         String poolName = input.getPoolName();
176         long low = input.getLow();
177         long high = input.getHigh();
178         long blockSize = idUtils.computeBlockSize(low, high);
179         Future<RpcResult<Void>> futureResult;
180         try {
181             idUtils.lock(lockManager, poolName);
182             WriteTransaction tx = broker.newWriteOnlyTransaction();
183             poolName = poolName.intern();
184             IdPool idPool;
185             idPool = createGlobalPool(tx, poolName, low, high, blockSize);
186             String localPoolName = idUtils.getLocalPoolName(poolName);
187             IdLocalPool idLocalPool = localPool.get(poolName);
188             if (idLocalPool == null) {
189                 createLocalPool(tx, localPoolName, idPool);
190                 idUtils.updateChildPool(tx, idPool.getPoolName(), localPoolName);
191             }
192             tx.submit().checkedGet();
193             futureResult = RpcResultBuilder.<Void>success().buildFuture();
194         } catch (OperationFailedException | IdManagerException e) {
195             futureResult = buildFailedRpcResultFuture("createIdPool failed: " + input.toString(), e);
196         } finally {
197             idUtils.unlock(lockManager, poolName);
198         }
199         return futureResult;
200     }
201
202     @Override
203     public Future<RpcResult<AllocateIdOutput>> allocateId(AllocateIdInput input) {
204         LOG.debug("AllocateId called with input {}", input);
205         String idKey = input.getIdKey();
206         String poolName = input.getPoolName();
207         String localPoolName = idUtils.getLocalPoolName(poolName);
208         long newIdValue = -1;
209         AllocateIdOutputBuilder output = new AllocateIdOutputBuilder();
210         Future<RpcResult<AllocateIdOutput>> futureResult;
211         String uniqueKey = idUtils.getUniqueKey(poolName, idKey);
212         try {
213             idUtils.lock(lockManager, uniqueKey);
214             //allocateIdFromLocalPool method returns a list of IDs with one element. This element is obtained by get(0)
215             newIdValue = allocateIdFromLocalPool(poolName, localPoolName, idKey, 1).get(0);
216             output.setIdValue(newIdValue);
217             futureResult = RpcResultBuilder.<AllocateIdOutput>success().withResult(output.build()).buildFuture();
218         } catch (OperationFailedException | IdManagerException e) {
219             completeExceptionallyIfPresent(poolName, idKey, e);
220             futureResult = buildFailedRpcResultFuture("allocateId failed: " + input.toString(), e);
221             idUtils.unlock(lockManager, uniqueKey);
222         }
223         return futureResult;
224     }
225
226     private void completeExceptionallyIfPresent(String poolName, String idKey, Exception exception) {
227         CompletableFuture<List<Long>> completableFuture =
228                 idUtils.allocatedIdMap.remove(idUtils.getUniqueKey(poolName, idKey));
229         if (completableFuture != null) {
230             completableFuture.completeExceptionally(exception);
231         }
232     }
233
234     @Override
235     public Future<RpcResult<AllocateIdRangeOutput>> allocateIdRange(AllocateIdRangeInput input) {
236         if (LOG.isDebugEnabled()) {
237             LOG.debug("AllocateIdRange called with input {}", input);
238         }
239         String idKey = input.getIdKey();
240         String poolName = input.getPoolName();
241         long size = input.getSize();
242         String localPoolName = idUtils.getLocalPoolName(poolName);
243         List<Long> newIdValuesList = new ArrayList<>();
244         AllocateIdRangeOutputBuilder output = new AllocateIdRangeOutputBuilder();
245         Future<RpcResult<AllocateIdRangeOutput>> futureResult;
246         String uniqueKey = idUtils.getUniqueKey(poolName, idKey);
247         try {
248             idUtils.lock(lockManager, uniqueKey);
249             newIdValuesList = allocateIdFromLocalPool(poolName, localPoolName, idKey, size);
250             Collections.sort(newIdValuesList);
251             output.setIdValues(newIdValuesList);
252             futureResult = RpcResultBuilder.<AllocateIdRangeOutput>success().withResult(output.build()).buildFuture();
253         } catch (OperationFailedException | IdManagerException e) {
254             completeExceptionallyIfPresent(poolName, idKey, e);
255             futureResult = buildFailedRpcResultFuture("allocateIdRange failed: " + input.toString(), e);
256             idUtils.unlock(lockManager, uniqueKey);
257         }
258         return futureResult;
259     }
260
261     @Override
262     public Future<RpcResult<Void>> deleteIdPool(DeleteIdPoolInput input) {
263         if (LOG.isDebugEnabled()) {
264             LOG.debug("DeleteIdPool called with input {}", input);
265         }
266         String poolName = input.getPoolName();
267         Future<RpcResult<Void>> futureResult;
268         try {
269             InstanceIdentifier<IdPool> idPoolToBeDeleted = idUtils.getIdPoolInstance(poolName);
270             poolName = poolName.intern();
271             synchronized (poolName) {
272                 IdPool idPool = singleTxDB.syncRead(CONFIGURATION, idPoolToBeDeleted);
273                 List<ChildPools> childPoolList = idPool.getChildPools();
274                 if (childPoolList != null) {
275                     childPoolList.parallelStream().forEach(childPool -> deletePool(childPool.getChildPoolName()));
276                 }
277                 singleTxDB.syncDelete(CONFIGURATION, idPoolToBeDeleted);
278                 if (LOG.isDebugEnabled()) {
279                     LOG.debug("Deleted id pool {}", poolName);
280                 }
281             }
282             futureResult = RpcResultBuilder.<Void>success().buildFuture();
283         } catch (OperationFailedException e) {
284             futureResult = buildFailedRpcResultFuture("deleteIdPool failed: " + input.toString(), e);
285         }
286         return futureResult;
287     }
288
289     @Override
290     public Future<RpcResult<Void>> releaseId(ReleaseIdInput input) {
291         String poolName = input.getPoolName();
292         String idKey = input.getIdKey();
293         LOG.info("Releasing ID {} from pool {}", idKey, poolName);
294         Future<RpcResult<Void>> futureResult;
295         String uniqueKey = idUtils.getUniqueKey(poolName, idKey);
296         try {
297             idUtils.lock(lockManager, uniqueKey);
298             releaseIdFromLocalPool(poolName, idUtils.getLocalPoolName(poolName), idKey);
299             futureResult = RpcResultBuilder.<Void>success().buildFuture();
300         } catch (ReadFailedException | IdManagerException e) {
301             futureResult = buildFailedRpcResultFuture("releaseId failed: " + input.toString(), e);
302             idUtils.unlock(lockManager, uniqueKey);
303         }
304         return futureResult;
305     }
306
307     private <T> ListenableFuture<RpcResult<T>> buildFailedRpcResultFuture(String msg, Exception exception) {
308         if (exception instanceof IdDoesNotExistException) {
309             // Do not log full stack trace in case ID does not exist
310             LOG.error(msg + " : " + exception.getMessage());
311         } else {
312             LOG.error(msg, exception);
313         }
314         RpcResultBuilder<T> failedRpcResultBuilder = RpcResultBuilder.failed();
315         failedRpcResultBuilder.withError(ErrorType.APPLICATION, msg, exception);
316         if (exception instanceof OperationFailedException) {
317             failedRpcResultBuilder.withRpcErrors(((OperationFailedException) exception).getErrorList());
318         }
319         return failedRpcResultBuilder.buildFuture();
320     }
321
322     private List<Long> allocateIdFromLocalPool(String parentPoolName, String localPoolName,
323             String idKey, long size) throws OperationFailedException, IdManagerException {
324         LOG.debug("Allocating id from local pool {}. Parent pool {}. Idkey {}", localPoolName, parentPoolName,
325                     idKey);
326         List<Long> newIdValuesList = new ArrayList<>();
327         String uniqueIdKey = idUtils.getUniqueKey(parentPoolName, idKey);
328         CompletableFuture<List<Long>> futureIdValues = new CompletableFuture<>();
329         CompletableFuture<List<Long>> existingFutureIdValue =
330                 idUtils.allocatedIdMap.putIfAbsent(uniqueIdKey, futureIdValues);
331         if (existingFutureIdValue != null) {
332             try {
333                 newIdValuesList = existingFutureIdValue.get();
334                 idUtils.unlock(lockManager, uniqueIdKey);
335                 return newIdValuesList;
336             } catch (InterruptedException | ExecutionException e) {
337                 LOG.warn("Could not obtain id from existing futureIdValue for idKey {} and pool {}.",
338                         idKey, parentPoolName);
339                 throw new IdManagerException(e.getMessage(), e);
340             }
341         }
342         long newIdValue = -1;
343         localPoolName = localPoolName.intern();
344         InstanceIdentifier<IdPool> parentIdPoolInstanceIdentifier = idUtils.getIdPoolInstance(parentPoolName);
345         InstanceIdentifier<IdEntries> existingId = idUtils.getIdEntry(parentIdPoolInstanceIdentifier, idKey);
346         Optional<IdEntries> existingIdEntry = singleTxDB.syncReadOptional(CONFIGURATION, existingId);
347         if (existingIdEntry.isPresent()) {
348             newIdValuesList = existingIdEntry.get().getIdValue();
349             LOG.debug("Existing ids {} for the key {} ", newIdValuesList, idKey);
350             // Inform other waiting threads about this new value.
351             futureIdValues.complete(newIdValuesList);
352             // This is to avoid stale entries in the map. If this thread had populated the map,
353             // then the entry should be removed.
354             if (existingFutureIdValue == null) {
355                 idUtils.allocatedIdMap.remove(uniqueIdKey);
356             }
357             idUtils.unlock(lockManager, uniqueIdKey);
358             return newIdValuesList;
359         }
360         //This get will not help in concurrent reads. Hence the same read needs to be done again.
361         IdLocalPool localIdPool = localPool.get(parentPoolName);
362         if (localIdPool == null) {
363             idUtils.lock(lockManager, parentPoolName);
364             try {
365                 //Check if a previous thread that got the cluster-wide lock first, has created the localPool
366                 if (localPool.get(parentPoolName) == null) {
367                     WriteTransaction tx = broker.newWriteOnlyTransaction();
368                     IdPool parentIdPool = singleTxDB.syncRead(CONFIGURATION, parentIdPoolInstanceIdentifier);
369                     localIdPool = createLocalPool(tx, localPoolName, parentIdPool); // Return localIdPool.....
370                     tx.submit().checkedGet();
371                 } else {
372                     localIdPool = localPool.get(parentPoolName);
373                 }
374             } finally {
375                 idUtils.unlock(lockManager, parentPoolName);
376             }
377         }
378         LOG.info("Got pool {}", localIdPool);
379         if (size == 1) {
380             newIdValue = getIdFromLocalPoolCache(localIdPool, parentPoolName);
381             newIdValuesList.add(newIdValue);
382         } else {
383             IdPool parentIdPool = singleTxDB.syncRead(CONFIGURATION, parentIdPoolInstanceIdentifier);
384             long totalAvailableIdCount = localIdPool.getAvailableIds().getAvailableIdCount()
385                     + localIdPool.getReleasedIds().getAvailableIdCount();
386             AvailableIdsHolderBuilder availableParentIds = idUtils.getAvailableIdsHolderBuilder(parentIdPool);
387             ReleasedIdsHolderBuilder releasedParentIds = idUtils.getReleaseIdsHolderBuilder(parentIdPool);
388             totalAvailableIdCount = totalAvailableIdCount + releasedParentIds.getAvailableIdCount()
389                     + idUtils.getAvailableIdsCount(availableParentIds);
390             if (totalAvailableIdCount > size) {
391                 while (size > 0) {
392                     try {
393                         newIdValue = getIdFromLocalPoolCache(localIdPool, parentPoolName);
394                     } catch (OperationFailedException e) {
395                         if (LOG.isDebugEnabled()) {
396                             LOG.debug("Releasing IDs to pool {}", localPoolName);
397                         }
398                         // Releasing the IDs added in newIdValuesList since a null list would be returned now, as the
399                         // requested size of list IDs exceeds the number of available IDs.
400                         updateDelayedEntriesInLocalCache(newIdValuesList, parentPoolName, localIdPool);
401                     }
402                     newIdValuesList.add(newIdValue);
403                     size--;
404                 }
405             } else {
406                 throw new IdManagerException(String.format("Ids exhausted for pool : %s", parentPoolName));
407             }
408         }
409         LOG.info("The newIdValues {} for the idKey {}", newIdValuesList, idKey);
410         idUtils.releaseIdLatchMap.put(uniqueIdKey, new CountDownLatch(1));
411         UpdateIdEntryJob job = new UpdateIdEntryJob(parentPoolName, localPoolName, idKey, newIdValuesList, broker,
412                 idUtils, lockManager);
413         DataStoreJobCoordinator.getInstance().enqueueJob(parentPoolName, job, IdUtils.RETRY_COUNT);
414         futureIdValues.complete(newIdValuesList);
415         return newIdValuesList;
416     }
417
418     private Long getIdFromLocalPoolCache(IdLocalPool localIdPool, String parentPoolName)
419             throws OperationFailedException, IdManagerException {
420         while (true) {
421             IdHolder releasedIds = localIdPool.getReleasedIds();
422             Optional<Long> releasedId = Optional.absent();
423             releasedId = releasedIds.allocateId();
424             if (releasedId.isPresent()) {
425                 IdHolderSyncJob poolSyncJob =
426                         new IdHolderSyncJob(localIdPool.getPoolName(), localIdPool.getReleasedIds(), broker,
427                                 idUtils);
428                 DataStoreJobCoordinator.getInstance().enqueueJob(localIdPool.getPoolName(),
429                         poolSyncJob, IdUtils.RETRY_COUNT);
430                 return releasedId.get();
431             }
432             Optional<Long> availableId = Optional.absent();
433             IdHolder availableIds = localIdPool.getAvailableIds();
434             if (availableIds != null) {
435                 availableId = availableIds.allocateId();
436                 if (availableId.isPresent()) {
437                     IdHolderSyncJob poolSyncJob =
438                             new IdHolderSyncJob(localIdPool.getPoolName(), localIdPool.getAvailableIds(),
439                                     broker, idUtils);
440                     DataStoreJobCoordinator.getInstance().enqueueJob(localIdPool.getPoolName(),
441                             poolSyncJob, IdUtils.RETRY_COUNT);
442                     return availableId.get();
443                 }
444             }
445             long idCount = getIdBlockFromParentPool(parentPoolName, localIdPool);
446             if (idCount <= 0) {
447                 if (LOG.isDebugEnabled()) {
448                     LOG.debug("Unable to allocate Id block from global pool");
449                 }
450                 throw new IdManagerException(String.format("Ids exhausted for pool : %s", parentPoolName));
451             }
452         }
453     }
454
455     /**
456      * Changes made to availableIds and releasedIds will not be persisted to the datastore.
457      */
458     private long getIdBlockFromParentPool(String parentPoolName, IdLocalPool localIdPool)
459             throws OperationFailedException, IdManagerException {
460         if (LOG.isDebugEnabled()) {
461             LOG.debug("Allocating block of id from parent pool {}", parentPoolName);
462         }
463         InstanceIdentifier<IdPool> idPoolInstanceIdentifier = idUtils.getIdPoolInstance(parentPoolName);
464         parentPoolName = parentPoolName.intern();
465         idUtils.lock(lockManager, parentPoolName);
466         long idCount = 0;
467         try {
468             // Check if the childpool already got id block.
469             long availableIdCount =
470                     localIdPool.getAvailableIds().getAvailableIdCount()
471                             + localIdPool.getReleasedIds().getAvailableIdCount();
472             if (availableIdCount > 0) {
473                 return availableIdCount;
474             }
475             WriteTransaction tx = broker.newWriteOnlyTransaction();
476             IdPool parentIdPool = singleTxDB.syncRead(CONFIGURATION, idPoolInstanceIdentifier);
477             idCount = allocateIdBlockFromParentPool(localIdPool, parentIdPool, tx);
478             tx.submit().checkedGet();
479         } catch (IdManagerException | NullPointerException e) {
480             LOG.error("Error getting id block from parent pool. {}", e.getMessage());
481         } finally {
482             idUtils.unlock(lockManager, parentPoolName);
483         }
484         return idCount;
485     }
486
487     private long allocateIdBlockFromParentPool(IdLocalPool localPoolCache, IdPool parentIdPool, WriteTransaction tx)
488             throws OperationFailedException, IdManagerException {
489         long idCount = -1;
490         ReleasedIdsHolderBuilder releasedIdsBuilderParent = idUtils.getReleaseIdsHolderBuilder(parentIdPool);
491         while (true) {
492             idCount = allocateIdBlockFromReleasedIdsHolder(localPoolCache, releasedIdsBuilderParent, parentIdPool, tx);
493             if (idCount > 0) {
494                 return idCount;
495             }
496             idCount = allocateIdBlockFromAvailableIdsHolder(localPoolCache, parentIdPool, tx);
497             if (idCount > 0) {
498                 return idCount;
499             }
500             idCount = getIdsFromOtherChildPools(releasedIdsBuilderParent, parentIdPool);
501             if (idCount <= 0) {
502                 if (LOG.isDebugEnabled()) {
503                     LOG.debug("Unable to allocate Id block from global pool");
504                 }
505                 throw new IdManagerException(String.format("Ids exhausted for pool : %s", parentIdPool.getPoolName()));
506             }
507         }
508     }
509
510     private long getIdsFromOtherChildPools(ReleasedIdsHolderBuilder releasedIdsBuilderParent, IdPool parentIdPool)
511             throws OperationFailedException {
512         List<ChildPools> childPoolsList = parentIdPool.getChildPools();
513         // Sorting the child pools on last accessed time so that the pool that
514         // was not accessed for a long time comes first.
515         Collections.sort(childPoolsList,
516             (childPool1, childPool2) -> childPool1.getLastAccessTime().compareTo(childPool2.getLastAccessTime()));
517         long currentTime = System.currentTimeMillis() / 1000;
518         for (ChildPools childPools : childPoolsList) {
519             if (childPools.getLastAccessTime() + DEFAULT_IDLE_TIME > currentTime) {
520                 break;
521             }
522             if (!childPools.getChildPoolName().equals(idUtils.getLocalPoolName(parentIdPool.getPoolName()))) {
523                 InstanceIdentifier<IdPool> idPoolInstanceIdentifier = idUtils
524                         .getIdPoolInstance(childPools.getChildPoolName());
525                 IdPool otherChildPool = singleTxDB.syncRead(CONFIGURATION, idPoolInstanceIdentifier);
526                 ReleasedIdsHolderBuilder releasedIds = idUtils.getReleaseIdsHolderBuilder(otherChildPool);
527
528                 List<DelayedIdEntries> delayedIdEntriesChild = releasedIds.getDelayedIdEntries();
529                 List<DelayedIdEntries> delayedIdEntriesParent = releasedIdsBuilderParent.getDelayedIdEntries();
530                 if (delayedIdEntriesParent == null) {
531                     delayedIdEntriesParent = new LinkedList<>();
532                 }
533                 delayedIdEntriesParent.addAll(delayedIdEntriesChild);
534                 delayedIdEntriesChild.removeAll(delayedIdEntriesChild);
535
536                 AvailableIdsHolderBuilder availableIds = idUtils.getAvailableIdsHolderBuilder(otherChildPool);
537                 while (idUtils.isIdAvailable(availableIds)) {
538                     long cursor = availableIds.getCursor() + 1;
539                     delayedIdEntriesParent.add(idUtils.createDelayedIdEntry(cursor, currentTime));
540                     availableIds.setCursor(cursor);
541                 }
542
543                 long totalAvailableIdCount = releasedIds.getDelayedIdEntries().size()
544                         + idUtils.getAvailableIdsCount(availableIds);
545                 long count = releasedIdsBuilderParent.getAvailableIdCount() + totalAvailableIdCount;
546                 releasedIdsBuilderParent.setDelayedIdEntries(delayedIdEntriesParent).setAvailableIdCount(count);
547                 singleTxDB.syncUpdate(CONFIGURATION, idPoolInstanceIdentifier,
548                         new IdPoolBuilder().setKey(new IdPoolKey(otherChildPool.getPoolName()))
549                                 .setAvailableIdsHolder(availableIds.build()).setReleasedIdsHolder(releasedIds.build())
550                                 .build());
551                 return totalAvailableIdCount;
552             }
553         }
554         return 0;
555     }
556
557     private long allocateIdBlockFromReleasedIdsHolder(IdLocalPool localIdPool,
558             ReleasedIdsHolderBuilder releasedIdsBuilderParent, IdPool parentIdPool, WriteTransaction tx) {
559         if (releasedIdsBuilderParent.getAvailableIdCount() == 0) {
560             LOG.debug("Ids unavailable in releasedIds of parent pool {}", parentIdPool);
561             return 0;
562         }
563         List<DelayedIdEntries> delayedIdEntriesParent = releasedIdsBuilderParent.getDelayedIdEntries();
564         int idCount = Math.min(delayedIdEntriesParent.size(), parentIdPool.getBlockSize());
565         List<DelayedIdEntries> idEntriesToBeRemoved = delayedIdEntriesParent.subList(0, idCount);
566         ReleasedIdHolder releasedIds = (ReleasedIdHolder) localIdPool.getReleasedIds();
567         List<DelayedIdEntry> delayedIdEntriesLocalCache = releasedIds.getDelayedEntries();
568         delayedIdEntriesLocalCache = idEntriesToBeRemoved
569                 .parallelStream()
570                 .map(delayedIdEntry -> new DelayedIdEntry(delayedIdEntry
571                         .getId(), delayedIdEntry.getReadyTimeSec()))
572                 .sorted((idEntry1, idEntry2) -> Long.compare(idEntry1.getReadyTimeSec(),
573                         idEntry2.getReadyTimeSec())).collect(Collectors.toList());
574         releasedIds.setDelayedEntries(delayedIdEntriesLocalCache);
575         releasedIds.setAvailableIdCount(releasedIds.getAvailableIdCount() + idCount);
576         localIdPool.setReleasedIds(releasedIds);
577         delayedIdEntriesParent.removeAll(idEntriesToBeRemoved);
578         releasedIdsBuilderParent.setDelayedIdEntries(delayedIdEntriesParent);
579         InstanceIdentifier<ReleasedIdsHolder> releasedIdsHolderInstanceIdentifier = InstanceIdentifier
580                 .builder(IdPools.class).child(IdPool.class,
581                         new IdPoolKey(parentIdPool.getPoolName())).child(ReleasedIdsHolder.class).build();
582         releasedIdsBuilderParent.setAvailableIdCount(releasedIdsBuilderParent.getAvailableIdCount() - idCount);
583         LOG.debug("Allocated {} ids from releasedIds of parent pool {}", idCount, parentIdPool);
584         tx.merge(CONFIGURATION, releasedIdsHolderInstanceIdentifier,
585                 releasedIdsBuilderParent.build(), true);
586         return idCount;
587     }
588
589     private long allocateIdBlockFromAvailableIdsHolder(IdLocalPool localIdPool, IdPool parentIdPool,
590             WriteTransaction tx) {
591         long idCount = 0;
592         AvailableIdsHolderBuilder availableIdsBuilderParent = idUtils.getAvailableIdsHolderBuilder(parentIdPool);
593         long end = availableIdsBuilderParent.getEnd();
594         long cur = availableIdsBuilderParent.getCursor();
595         if (!idUtils.isIdAvailable(availableIdsBuilderParent)) {
596             if (LOG.isDebugEnabled()) {
597                 LOG.debug("Ids exhausted in parent pool {}", parentIdPool);
598             }
599             return idCount;
600         }
601         // Update availableIdsHolder of Local Pool
602         idCount = Math.min(end - cur, parentIdPool.getBlockSize());
603         AvailableIdHolder availableIds = new AvailableIdHolder(idUtils, cur + 1, cur + idCount);
604         localIdPool.setAvailableIds(availableIds);
605         // Update availableIdsHolder of Global Pool
606         InstanceIdentifier<AvailableIdsHolder> availableIdsHolderInstanceIdentifier = InstanceIdentifier
607                 .builder(IdPools.class).child(IdPool.class,
608                         new IdPoolKey(parentIdPool.getPoolName())).child(AvailableIdsHolder.class).build();
609         availableIdsBuilderParent.setCursor(cur + idCount);
610         if (LOG.isDebugEnabled()) {
611             LOG.debug("Allocated {} ids from availableIds of global pool {}", idCount, parentIdPool);
612         }
613         tx.merge(CONFIGURATION, availableIdsHolderInstanceIdentifier,
614                 availableIdsBuilderParent.build(), true);
615         return idCount;
616     }
617
618     private void releaseIdFromLocalPool(String parentPoolName, String localPoolName, String idKey)
619             throws ReadFailedException, IdManagerException {
620         String idLatchKey = idUtils.getUniqueKey(parentPoolName, idKey);
621         LOG.debug("Releasing ID {} from pool {}", idKey, localPoolName);
622         CountDownLatch latch = idUtils.releaseIdLatchMap.get(idLatchKey);
623         if (latch != null) {
624             try {
625                 latch.await(10, TimeUnit.SECONDS);
626             } catch (InterruptedException ignored) {
627                 LOG.warn("Thread interrupted while releasing id {} from id pool {}", idKey, parentPoolName);
628             } finally {
629                 idUtils.releaseIdLatchMap.remove(idLatchKey);
630             }
631         }
632         localPoolName = localPoolName.intern();
633         InstanceIdentifier<IdPool> parentIdPoolInstanceIdentifier = idUtils.getIdPoolInstance(parentPoolName);
634         IdPool parentIdPool = singleTxDB.syncRead(CONFIGURATION, parentIdPoolInstanceIdentifier);
635         List<IdEntries> idEntries = parentIdPool.getIdEntries();
636         List<IdEntries> newIdEntries = idEntries;
637         if (idEntries == null) {
638             throw new IdDoesNotExistException(parentPoolName, idKey);
639         }
640         InstanceIdentifier<IdEntries> existingId = idUtils.getIdEntry(parentIdPoolInstanceIdentifier, idKey);
641         Optional<IdEntries> existingIdEntryObject = singleTxDB.syncReadOptional(CONFIGURATION, existingId);
642         if (!existingIdEntryObject.isPresent()) {
643             LOG.info("Specified Id key {} does not exist in id pool {}", idKey, parentPoolName);
644             idUtils.unlock(lockManager, idLatchKey);
645             return;
646         }
647         IdEntries existingIdEntry = existingIdEntryObject.get();
648         List<Long> idValuesList = existingIdEntry.getIdValue();
649         IdLocalPool localIdPoolCache = localPool.get(parentPoolName);
650         boolean isRemoved = newIdEntries.remove(existingIdEntry);
651         LOG.debug("The entry {} is removed {}", existingIdEntry, isRemoved);
652         updateDelayedEntriesInLocalCache(idValuesList, parentPoolName, localIdPoolCache);
653         IdHolderSyncJob poolSyncJob = new IdHolderSyncJob(localPoolName, localIdPoolCache.getReleasedIds(), broker,
654                 idUtils);
655         DataStoreJobCoordinator.getInstance().enqueueJob(localPoolName, poolSyncJob, IdUtils.RETRY_COUNT);
656         scheduleCleanUpTask(localIdPoolCache, parentPoolName, parentIdPool.getBlockSize());
657         LOG.debug("Released id ({}, {}) from pool {}", idKey, idValuesList, localPoolName);
658         // Updating id entries in the parent pool. This will be used for restart scenario
659         UpdateIdEntryJob job = new UpdateIdEntryJob(parentPoolName, localPoolName, idKey, null, broker, idUtils,
660                         lockManager);
661         DataStoreJobCoordinator.getInstance().enqueueJob(parentPoolName, job, IdUtils.RETRY_COUNT);
662     }
663
664     private void scheduleCleanUpTask(final IdLocalPool localIdPoolCache,
665             final String parentPoolName, final int blockSize) {
666         TimerTask scheduledTask = new TimerTask() {
667             @Override
668             public void run() {
669                 CleanUpJob job = new CleanUpJob(localIdPoolCache, broker, parentPoolName, blockSize, lockManager,
670                         idUtils);
671                 DataStoreJobCoordinator.getInstance().enqueueJob(localIdPoolCache.getPoolName(), job,
672                         IdUtils.RETRY_COUNT);
673             }
674         };
675         cleanJobTimer.schedule(scheduledTask, IdUtils.DEFAULT_DELAY_TIME * 1000);
676     }
677
678     private IdPool createGlobalPool(WriteTransaction tx, String poolName, long low, long high, long blockSize)
679             throws ReadFailedException {
680         IdPool idPool;
681         InstanceIdentifier<IdPool> idPoolInstanceIdentifier = idUtils.getIdPoolInstance(poolName);
682         Optional<IdPool> existingIdPool = singleTxDB.syncReadOptional(CONFIGURATION, idPoolInstanceIdentifier);
683         if (!existingIdPool.isPresent()) {
684             if (LOG.isDebugEnabled()) {
685                 LOG.debug("Creating new global pool {}", poolName);
686             }
687             idPool = idUtils.createGlobalPool(poolName, low, high, blockSize);
688             tx.put(CONFIGURATION, idPoolInstanceIdentifier, idPool, true);
689         } else {
690             idPool = existingIdPool.get();
691             if (LOG.isDebugEnabled()) {
692                 LOG.debug("GlobalPool exists {}", idPool);
693             }
694         }
695         return idPool;
696     }
697
698     private IdLocalPool createLocalPool(WriteTransaction tx, String localPoolName, IdPool idPool)
699             throws OperationFailedException, IdManagerException {
700         localPoolName = localPoolName.intern();
701         IdLocalPool idLocalPool = new IdLocalPool(idUtils, localPoolName);
702         allocateIdBlockFromParentPool(idLocalPool, idPool, tx);
703         String parentPool = idPool.getPoolName();
704         localPool.put(parentPool, idLocalPool);
705         LocalPoolCreateJob job = new LocalPoolCreateJob(idLocalPool, broker, idPool.getPoolName(),
706                 idPool.getBlockSize(), idUtils);
707         DataStoreJobCoordinator.getInstance().enqueueJob(localPoolName, job, IdUtils.RETRY_COUNT);
708         return idLocalPool;
709     }
710
711     private void deletePool(String poolName) {
712         LocalPoolDeleteJob job = new LocalPoolDeleteJob(poolName, broker, idUtils);
713         DataStoreJobCoordinator.getInstance().enqueueJob(poolName, job, IdUtils.RETRY_COUNT);
714     }
715
716     public void poolDeleted(String parentPoolName, String poolName) {
717         IdLocalPool idLocalPool = localPool.get(parentPoolName);
718         if (idLocalPool != null) {
719             if (idLocalPool.getPoolName().equals(poolName)) {
720                 localPool.remove(parentPoolName);
721             }
722         }
723     }
724
725     private void updateDelayedEntriesInLocalCache(List<Long> idsList, String parentPoolName,
726             IdLocalPool localPoolCache) {
727         for (long idValue : idsList) {
728             localPoolCache.getReleasedIds().addId(idValue);
729         }
730         localPool.put(parentPoolName, localPoolCache);
731     }
732
733     public java.util.Optional<IdLocalPool> getIdLocalPool(String parentPoolName) {
734         return java.util.Optional.ofNullable(localPool.get(parentPoolName))
735                 .map(localPool -> localPool.deepCopyOf());
736     }
737
738 }