Merge "Bug 7826: Data validation failed for path"
[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             java.util.Optional.ofNullable(
220                     idUtils.allocatedIdMap.remove(idUtils.getUniqueKey(poolName, idKey)))
221                     .ifPresent(futureId -> futureId.completeExceptionally(e));
222             futureResult = buildFailedRpcResultFuture("allocateId failed: " + input.toString(), e);
223             idUtils.unlock(lockManager, uniqueKey);
224         }
225         return futureResult;
226     }
227
228     @Override
229     public Future<RpcResult<AllocateIdRangeOutput>> allocateIdRange(AllocateIdRangeInput input) {
230         if (LOG.isDebugEnabled()) {
231             LOG.debug("AllocateIdRange called with input {}", input);
232         }
233         String idKey = input.getIdKey();
234         String poolName = input.getPoolName();
235         long size = input.getSize();
236         String localPoolName = idUtils.getLocalPoolName(poolName);
237         List<Long> newIdValuesList = new ArrayList<>();
238         AllocateIdRangeOutputBuilder output = new AllocateIdRangeOutputBuilder();
239         Future<RpcResult<AllocateIdRangeOutput>> futureResult;
240         String uniqueKey = idUtils.getUniqueKey(poolName, idKey);
241         try {
242             idUtils.lock(lockManager, uniqueKey);
243             newIdValuesList = allocateIdFromLocalPool(poolName, localPoolName, idKey, size);
244             Collections.sort(newIdValuesList);
245             output.setIdValues(newIdValuesList);
246             futureResult = RpcResultBuilder.<AllocateIdRangeOutput>success().withResult(output.build()).buildFuture();
247         } catch (OperationFailedException | IdManagerException e) {
248             java.util.Optional.ofNullable(
249                     idUtils.allocatedIdMap.remove(idUtils.getUniqueKey(poolName, idKey)))
250                     .ifPresent(futureId -> futureId.completeExceptionally(e));
251             futureResult = buildFailedRpcResultFuture("allocateIdRange failed: " + input.toString(), e);
252             idUtils.unlock(lockManager, uniqueKey);
253         }
254         return futureResult;
255     }
256
257     @Override
258     public Future<RpcResult<Void>> deleteIdPool(DeleteIdPoolInput input) {
259         if (LOG.isDebugEnabled()) {
260             LOG.debug("DeleteIdPool called with input {}", input);
261         }
262         String poolName = input.getPoolName();
263         Future<RpcResult<Void>> futureResult;
264         try {
265             InstanceIdentifier<IdPool> idPoolToBeDeleted = idUtils.getIdPoolInstance(poolName);
266             poolName = poolName.intern();
267             synchronized (poolName) {
268                 IdPool idPool = singleTxDB.syncRead(CONFIGURATION, idPoolToBeDeleted);
269                 List<ChildPools> childPoolList = idPool.getChildPools();
270                 if (childPoolList != null) {
271                     childPoolList.parallelStream().forEach(childPool -> deletePool(childPool.getChildPoolName()));
272                 }
273                 singleTxDB.syncDelete(CONFIGURATION, idPoolToBeDeleted);
274                 if (LOG.isDebugEnabled()) {
275                     LOG.debug("Deleted id pool {}", poolName);
276                 }
277             }
278             futureResult = RpcResultBuilder.<Void>success().buildFuture();
279         } catch (OperationFailedException e) {
280             futureResult = buildFailedRpcResultFuture("deleteIdPool failed: " + input.toString(), e);
281         }
282         return futureResult;
283     }
284
285     @Override
286     public Future<RpcResult<Void>> releaseId(ReleaseIdInput input) {
287         String poolName = input.getPoolName();
288         String idKey = input.getIdKey();
289         LOG.info("Releasing ID {} from pool {}", idKey, poolName);
290         Future<RpcResult<Void>> futureResult;
291         String uniqueKey = idUtils.getUniqueKey(poolName, idKey);
292         try {
293             idUtils.lock(lockManager, uniqueKey);
294             releaseIdFromLocalPool(poolName, idUtils.getLocalPoolName(poolName), idKey);
295             futureResult = RpcResultBuilder.<Void>success().buildFuture();
296         } catch (ReadFailedException | IdManagerException e) {
297             futureResult = buildFailedRpcResultFuture("releaseId failed: " + input.toString(), e);
298             idUtils.unlock(lockManager, uniqueKey);
299         }
300         return futureResult;
301     }
302
303     private <T> ListenableFuture<RpcResult<T>> buildFailedRpcResultFuture(String msg, Exception exception) {
304         LOG.error(msg, exception);
305         RpcResultBuilder<T> failedRpcResultBuilder = RpcResultBuilder.failed();
306         failedRpcResultBuilder.withError(ErrorType.APPLICATION, msg, exception);
307         if (exception instanceof OperationFailedException) {
308             failedRpcResultBuilder.withRpcErrors(((OperationFailedException) exception).getErrorList());
309         }
310         return failedRpcResultBuilder.buildFuture();
311     }
312
313     private List<Long> allocateIdFromLocalPool(String parentPoolName, String localPoolName,
314             String idKey, long size) throws OperationFailedException, IdManagerException {
315         LOG.debug("Allocating id from local pool {}. Parent pool {}. Idkey {}", localPoolName, parentPoolName,
316                     idKey);
317         List<Long> newIdValuesList = new ArrayList<>();
318         String uniqueIdKey = idUtils.getUniqueKey(parentPoolName, idKey);
319         CompletableFuture<List<Long>> futureIdValues = new CompletableFuture<>();
320         CompletableFuture<List<Long>> existingFutureIdValue =
321                 idUtils.allocatedIdMap.putIfAbsent(uniqueIdKey, futureIdValues);
322         if (existingFutureIdValue != null) {
323             try {
324                 newIdValuesList = existingFutureIdValue.get();
325                 idUtils.unlock(lockManager, uniqueIdKey);
326                 return newIdValuesList;
327             } catch (InterruptedException | ExecutionException e) {
328                 LOG.warn("Could not obtain id from existing futureIdValue for idKey {} and pool {}.",
329                         idKey, parentPoolName);
330                 throw new IdManagerException(e.getMessage(), e);
331             }
332         }
333         long newIdValue = -1;
334         localPoolName = localPoolName.intern();
335         InstanceIdentifier<IdPool> parentIdPoolInstanceIdentifier = idUtils.getIdPoolInstance(parentPoolName);
336         InstanceIdentifier<IdEntries> existingId = idUtils.getIdEntry(parentIdPoolInstanceIdentifier, idKey);
337         Optional<IdEntries> existingIdEntry = singleTxDB.syncReadOptional(CONFIGURATION, existingId);
338         if (existingIdEntry.isPresent()) {
339             newIdValuesList = existingIdEntry.get().getIdValue();
340             LOG.debug("Existing ids {} for the key {} ", newIdValuesList, idKey);
341             // Inform other waiting threads about this new value.
342             futureIdValues.complete(newIdValuesList);
343             // This is to avoid stale entries in the map. If this thread had populated the map,
344             // then the entry should be removed.
345             if (existingFutureIdValue == null) {
346                 idUtils.allocatedIdMap.remove(uniqueIdKey);
347             }
348             idUtils.unlock(lockManager, uniqueIdKey);
349             return newIdValuesList;
350         }
351         //This get will not help in concurrent reads. Hence the same read needs to be done again.
352         IdLocalPool localIdPool = localPool.get(parentPoolName);
353         if (localIdPool == null) {
354             idUtils.lock(lockManager, parentPoolName);
355             try {
356                 //Check if a previous thread that got the cluster-wide lock first, has created the localPool
357                 if (localPool.get(parentPoolName) == null) {
358                     WriteTransaction tx = broker.newWriteOnlyTransaction();
359                     IdPool parentIdPool = singleTxDB.syncRead(CONFIGURATION, parentIdPoolInstanceIdentifier);
360                     localIdPool = createLocalPool(tx, localPoolName, parentIdPool); // Return localIdPool.....
361                     tx.submit().checkedGet();
362                 } else {
363                     localIdPool = localPool.get(parentPoolName);
364                 }
365             } finally {
366                 idUtils.unlock(lockManager, parentPoolName);
367             }
368         }
369         LOG.info("Got pool {}", localIdPool);
370         if (size == 1) {
371             newIdValue = getIdFromLocalPoolCache(localIdPool, parentPoolName);
372             newIdValuesList.add(newIdValue);
373         } else {
374             IdPool parentIdPool = singleTxDB.syncRead(CONFIGURATION, parentIdPoolInstanceIdentifier);
375             long totalAvailableIdCount = localIdPool.getAvailableIds().getAvailableIdCount()
376                     + localIdPool.getReleasedIds().getAvailableIdCount();
377             AvailableIdsHolderBuilder availableParentIds = idUtils.getAvailableIdsHolderBuilder(parentIdPool);
378             ReleasedIdsHolderBuilder releasedParentIds = idUtils.getReleaseIdsHolderBuilder(parentIdPool);
379             totalAvailableIdCount = totalAvailableIdCount + releasedParentIds.getAvailableIdCount()
380                     + idUtils.getAvailableIdsCount(availableParentIds);
381             if (totalAvailableIdCount > size) {
382                 while (size > 0) {
383                     try {
384                         newIdValue = getIdFromLocalPoolCache(localIdPool, parentPoolName);
385                     } catch (OperationFailedException e) {
386                         if (LOG.isDebugEnabled()) {
387                             LOG.debug("Releasing IDs to pool {}", localPoolName);
388                         }
389                         // Releasing the IDs added in newIdValuesList since a null list would be returned now, as the
390                         // requested size of list IDs exceeds the number of available IDs.
391                         updateDelayedEntriesInLocalCache(newIdValuesList, parentPoolName, localIdPool);
392                     }
393                     newIdValuesList.add(newIdValue);
394                     size--;
395                 }
396             } else {
397                 throw new IdManagerException(String.format("Ids exhausted for pool : %s", parentPoolName));
398             }
399         }
400         LOG.info("The newIdValues {} for the idKey {}", newIdValuesList, idKey);
401         idUtils.releaseIdLatchMap.put(uniqueIdKey, new CountDownLatch(1));
402         UpdateIdEntryJob job = new UpdateIdEntryJob(parentPoolName, localPoolName, idKey, newIdValuesList, broker,
403                 idUtils, lockManager);
404         DataStoreJobCoordinator.getInstance().enqueueJob(parentPoolName, job, IdUtils.RETRY_COUNT);
405         futureIdValues.complete(newIdValuesList);
406         return newIdValuesList;
407     }
408
409     private Long getIdFromLocalPoolCache(IdLocalPool localIdPool, String parentPoolName)
410             throws OperationFailedException, IdManagerException {
411         while (true) {
412             IdHolder releasedIds = localIdPool.getReleasedIds();
413             Optional<Long> releasedId = Optional.absent();
414             releasedId = releasedIds.allocateId();
415             if (releasedId.isPresent()) {
416                 IdHolderSyncJob poolSyncJob =
417                         new IdHolderSyncJob(localIdPool.getPoolName(), localIdPool.getReleasedIds(), broker,
418                                 idUtils);
419                 DataStoreJobCoordinator.getInstance().enqueueJob(localIdPool.getPoolName(),
420                         poolSyncJob, IdUtils.RETRY_COUNT);
421                 return releasedId.get();
422             }
423             Optional<Long> availableId = Optional.absent();
424             IdHolder availableIds = localIdPool.getAvailableIds();
425             if (availableIds != null) {
426                 availableId = availableIds.allocateId();
427                 if (availableId.isPresent()) {
428                     IdHolderSyncJob poolSyncJob =
429                             new IdHolderSyncJob(localIdPool.getPoolName(), localIdPool.getAvailableIds(),
430                                     broker, idUtils);
431                     DataStoreJobCoordinator.getInstance().enqueueJob(localIdPool.getPoolName(),
432                             poolSyncJob, IdUtils.RETRY_COUNT);
433                     return availableId.get();
434                 }
435             }
436             long idCount = getIdBlockFromParentPool(parentPoolName, localIdPool);
437             if (idCount <= 0) {
438                 if (LOG.isDebugEnabled()) {
439                     LOG.debug("Unable to allocate Id block from global pool");
440                 }
441                 throw new IdManagerException(String.format("Ids exhausted for pool : %s", parentPoolName));
442             }
443         }
444     }
445
446     /**
447      * Changes made to availableIds and releasedIds will not be persisted to the datastore.
448      */
449     private long getIdBlockFromParentPool(String parentPoolName, IdLocalPool localIdPool)
450             throws OperationFailedException, IdManagerException {
451         if (LOG.isDebugEnabled()) {
452             LOG.debug("Allocating block of id from parent pool {}", parentPoolName);
453         }
454         InstanceIdentifier<IdPool> idPoolInstanceIdentifier = idUtils.getIdPoolInstance(parentPoolName);
455         parentPoolName = parentPoolName.intern();
456         idUtils.lock(lockManager, parentPoolName);
457         long idCount = 0;
458         try {
459             // Check if the childpool already got id block.
460             long availableIdCount =
461                     localIdPool.getAvailableIds().getAvailableIdCount()
462                             + localIdPool.getReleasedIds().getAvailableIdCount();
463             if (availableIdCount > 0) {
464                 return availableIdCount;
465             }
466             WriteTransaction tx = broker.newWriteOnlyTransaction();
467             IdPool parentIdPool = singleTxDB.syncRead(CONFIGURATION, idPoolInstanceIdentifier);
468             idCount = allocateIdBlockFromParentPool(localIdPool, parentIdPool, tx);
469             tx.submit().checkedGet();
470         } catch (IdManagerException | NullPointerException e) {
471             LOG.error("Error getting id block from parent pool. {}", e.getMessage());
472         } finally {
473             idUtils.unlock(lockManager, parentPoolName);
474         }
475         return idCount;
476     }
477
478     private long allocateIdBlockFromParentPool(IdLocalPool localPoolCache, IdPool parentIdPool, WriteTransaction tx)
479             throws OperationFailedException, IdManagerException {
480         long idCount = -1;
481         ReleasedIdsHolderBuilder releasedIdsBuilderParent = idUtils.getReleaseIdsHolderBuilder(parentIdPool);
482         while (true) {
483             idCount = allocateIdBlockFromReleasedIdsHolder(localPoolCache, releasedIdsBuilderParent, parentIdPool, tx);
484             if (idCount > 0) {
485                 return idCount;
486             }
487             idCount = allocateIdBlockFromAvailableIdsHolder(localPoolCache, parentIdPool, tx);
488             if (idCount > 0) {
489                 return idCount;
490             }
491             idCount = getIdsFromOtherChildPools(releasedIdsBuilderParent, parentIdPool);
492             if (idCount <= 0) {
493                 if (LOG.isDebugEnabled()) {
494                     LOG.debug("Unable to allocate Id block from global pool");
495                 }
496                 throw new IdManagerException(String.format("Ids exhausted for pool : %s", parentIdPool.getPoolName()));
497             }
498         }
499     }
500
501     private long getIdsFromOtherChildPools(ReleasedIdsHolderBuilder releasedIdsBuilderParent, IdPool parentIdPool)
502             throws OperationFailedException {
503         List<ChildPools> childPoolsList = parentIdPool.getChildPools();
504         // Sorting the child pools on last accessed time so that the pool that
505         // was not accessed for a long time comes first.
506         Collections.sort(childPoolsList,
507             (childPool1, childPool2) -> childPool1.getLastAccessTime().compareTo(childPool2.getLastAccessTime()));
508         long currentTime = System.currentTimeMillis() / 1000;
509         for (ChildPools childPools : childPoolsList) {
510             if (childPools.getLastAccessTime() + DEFAULT_IDLE_TIME > currentTime) {
511                 break;
512             }
513             if (!childPools.getChildPoolName().equals(idUtils.getLocalPoolName(parentIdPool.getPoolName()))) {
514                 InstanceIdentifier<IdPool> idPoolInstanceIdentifier = idUtils
515                         .getIdPoolInstance(childPools.getChildPoolName());
516                 IdPool otherChildPool = singleTxDB.syncRead(CONFIGURATION, idPoolInstanceIdentifier);
517                 ReleasedIdsHolderBuilder releasedIds = idUtils.getReleaseIdsHolderBuilder(otherChildPool);
518
519                 List<DelayedIdEntries> delayedIdEntriesChild = releasedIds.getDelayedIdEntries();
520                 List<DelayedIdEntries> delayedIdEntriesParent = releasedIdsBuilderParent.getDelayedIdEntries();
521                 if (delayedIdEntriesParent == null) {
522                     delayedIdEntriesParent = new LinkedList<>();
523                 }
524                 delayedIdEntriesParent.addAll(delayedIdEntriesChild);
525                 delayedIdEntriesChild.removeAll(delayedIdEntriesChild);
526
527                 AvailableIdsHolderBuilder availableIds = idUtils.getAvailableIdsHolderBuilder(otherChildPool);
528                 while (idUtils.isIdAvailable(availableIds)) {
529                     long cursor = availableIds.getCursor() + 1;
530                     delayedIdEntriesParent.add(idUtils.createDelayedIdEntry(cursor, currentTime));
531                     availableIds.setCursor(cursor);
532                 }
533
534                 long totalAvailableIdCount = releasedIds.getDelayedIdEntries().size()
535                         + idUtils.getAvailableIdsCount(availableIds);
536                 long count = releasedIdsBuilderParent.getAvailableIdCount() + totalAvailableIdCount;
537                 releasedIdsBuilderParent.setDelayedIdEntries(delayedIdEntriesParent).setAvailableIdCount(count);
538                 singleTxDB.syncUpdate(CONFIGURATION, idPoolInstanceIdentifier,
539                         new IdPoolBuilder().setKey(new IdPoolKey(otherChildPool.getPoolName()))
540                                 .setAvailableIdsHolder(availableIds.build()).setReleasedIdsHolder(releasedIds.build())
541                                 .build());
542                 return totalAvailableIdCount;
543             }
544         }
545         return 0;
546     }
547
548     private long allocateIdBlockFromReleasedIdsHolder(IdLocalPool localIdPool,
549             ReleasedIdsHolderBuilder releasedIdsBuilderParent, IdPool parentIdPool, WriteTransaction tx) {
550         if (releasedIdsBuilderParent.getAvailableIdCount() == 0) {
551             LOG.debug("Ids unavailable in releasedIds of parent pool {}", parentIdPool);
552             return 0;
553         }
554         List<DelayedIdEntries> delayedIdEntriesParent = releasedIdsBuilderParent.getDelayedIdEntries();
555         int idCount = Math.min(delayedIdEntriesParent.size(), parentIdPool.getBlockSize());
556         List<DelayedIdEntries> idEntriesToBeRemoved = delayedIdEntriesParent.subList(0, idCount);
557         ReleasedIdHolder releasedIds = (ReleasedIdHolder) localIdPool.getReleasedIds();
558         List<DelayedIdEntry> delayedIdEntriesLocalCache = releasedIds.getDelayedEntries();
559         delayedIdEntriesLocalCache = idEntriesToBeRemoved
560                 .parallelStream()
561                 .map(delayedIdEntry -> new DelayedIdEntry(delayedIdEntry
562                         .getId(), delayedIdEntry.getReadyTimeSec()))
563                 .sorted((idEntry1, idEntry2) -> Long.compare(idEntry1.getReadyTimeSec(),
564                         idEntry2.getReadyTimeSec())).collect(Collectors.toList());
565         releasedIds.setDelayedEntries(delayedIdEntriesLocalCache);
566         releasedIds.setAvailableIdCount(releasedIds.getAvailableIdCount() + idCount);
567         localIdPool.setReleasedIds(releasedIds);
568         delayedIdEntriesParent.removeAll(idEntriesToBeRemoved);
569         releasedIdsBuilderParent.setDelayedIdEntries(delayedIdEntriesParent);
570         InstanceIdentifier<ReleasedIdsHolder> releasedIdsHolderInstanceIdentifier = InstanceIdentifier
571                 .builder(IdPools.class).child(IdPool.class,
572                         new IdPoolKey(parentIdPool.getPoolName())).child(ReleasedIdsHolder.class).build();
573         releasedIdsBuilderParent.setAvailableIdCount(releasedIdsBuilderParent.getAvailableIdCount() - idCount);
574         LOG.debug("Allocated {} ids from releasedIds of parent pool {}", idCount, parentIdPool);
575         tx.merge(CONFIGURATION, releasedIdsHolderInstanceIdentifier,
576                 releasedIdsBuilderParent.build(), true);
577         return idCount;
578     }
579
580     private long allocateIdBlockFromAvailableIdsHolder(IdLocalPool localIdPool, IdPool parentIdPool,
581             WriteTransaction tx) {
582         long idCount = 0;
583         AvailableIdsHolderBuilder availableIdsBuilderParent = idUtils.getAvailableIdsHolderBuilder(parentIdPool);
584         long end = availableIdsBuilderParent.getEnd();
585         long cur = availableIdsBuilderParent.getCursor();
586         if (!idUtils.isIdAvailable(availableIdsBuilderParent)) {
587             if (LOG.isDebugEnabled()) {
588                 LOG.debug("Ids exhausted in parent pool {}", parentIdPool);
589             }
590             return idCount;
591         }
592         // Update availableIdsHolder of Local Pool
593         idCount = Math.min(end - cur, parentIdPool.getBlockSize());
594         AvailableIdHolder availableIds = new AvailableIdHolder(idUtils, cur + 1, cur + idCount);
595         localIdPool.setAvailableIds(availableIds);
596         // Update availableIdsHolder of Global Pool
597         InstanceIdentifier<AvailableIdsHolder> availableIdsHolderInstanceIdentifier = InstanceIdentifier
598                 .builder(IdPools.class).child(IdPool.class,
599                         new IdPoolKey(parentIdPool.getPoolName())).child(AvailableIdsHolder.class).build();
600         availableIdsBuilderParent.setCursor(cur + idCount);
601         if (LOG.isDebugEnabled()) {
602             LOG.debug("Allocated {} ids from availableIds of global pool {}", idCount, parentIdPool);
603         }
604         tx.merge(CONFIGURATION, availableIdsHolderInstanceIdentifier,
605                 availableIdsBuilderParent.build(), true);
606         return idCount;
607     }
608
609     private void releaseIdFromLocalPool(String parentPoolName, String localPoolName, String idKey)
610             throws ReadFailedException, IdManagerException {
611         String idLatchKey = idUtils.getUniqueKey(parentPoolName, idKey);
612         LOG.debug("Releasing ID {} from pool {}", idKey, localPoolName);
613         java.util.Optional.ofNullable(idUtils.releaseIdLatchMap.get(idLatchKey)).ifPresent(latch -> {
614             try {
615                 latch.await(10, TimeUnit.SECONDS);
616             } catch (InterruptedException ignored) {
617                 LOG.warn("Thread interrupted while releasing id {} from id pool {}", idKey, parentPoolName);
618             } finally {
619                 idUtils.releaseIdLatchMap.remove(idLatchKey);
620             }
621         });
622         localPoolName = localPoolName.intern();
623         InstanceIdentifier<IdPool> parentIdPoolInstanceIdentifier = idUtils.getIdPoolInstance(parentPoolName);
624         IdPool parentIdPool = singleTxDB.syncRead(CONFIGURATION, parentIdPoolInstanceIdentifier);
625         List<IdEntries> idEntries = parentIdPool.getIdEntries();
626         List<IdEntries> newIdEntries = idEntries;
627         if (idEntries == null) {
628             throw new IdManagerException("Id Entries does not exist");
629         }
630         InstanceIdentifier<IdEntries> existingId = idUtils.getIdEntry(parentIdPoolInstanceIdentifier, idKey);
631         Optional<IdEntries> existingIdEntryObject = singleTxDB.syncReadOptional(CONFIGURATION, existingId);
632         if (!existingIdEntryObject.isPresent()) {
633             LOG.info("Specified Id key {} does not exist in id pool {}", idKey, parentPoolName);
634             idUtils.unlock(lockManager, idLatchKey);
635             return;
636         }
637         IdEntries existingIdEntry = existingIdEntryObject.get();
638         List<Long> idValuesList = existingIdEntry.getIdValue();
639         IdLocalPool localIdPoolCache = localPool.get(parentPoolName);
640         boolean isRemoved = newIdEntries.remove(existingIdEntry);
641         LOG.debug("The entry {} is removed {}", existingIdEntry, isRemoved);
642         updateDelayedEntriesInLocalCache(idValuesList, parentPoolName, localIdPoolCache);
643         IdHolderSyncJob poolSyncJob = new IdHolderSyncJob(localPoolName, localIdPoolCache.getReleasedIds(), broker,
644                 idUtils);
645         DataStoreJobCoordinator.getInstance().enqueueJob(localPoolName, poolSyncJob, IdUtils.RETRY_COUNT);
646         scheduleCleanUpTask(localIdPoolCache, parentPoolName, parentIdPool.getBlockSize());
647         LOG.debug("Released id ({}, {}) from pool {}", idKey, idValuesList, localPoolName);
648         // Updating id entries in the parent pool. This will be used for restart scenario
649         UpdateIdEntryJob job = new UpdateIdEntryJob(parentPoolName, localPoolName, idKey, null, broker, idUtils,
650                         lockManager);
651         DataStoreJobCoordinator.getInstance().enqueueJob(parentPoolName, job, IdUtils.RETRY_COUNT);
652     }
653
654     private void scheduleCleanUpTask(final IdLocalPool localIdPoolCache,
655             final String parentPoolName, final int blockSize) {
656         TimerTask scheduledTask = new TimerTask() {
657             @Override
658             public void run() {
659                 CleanUpJob job = new CleanUpJob(localIdPoolCache, broker, parentPoolName, blockSize, lockManager,
660                         idUtils);
661                 DataStoreJobCoordinator.getInstance().enqueueJob(localIdPoolCache.getPoolName(), job,
662                         IdUtils.RETRY_COUNT);
663             }
664         };
665         cleanJobTimer.schedule(scheduledTask, IdUtils.DEFAULT_DELAY_TIME * 1000);
666     }
667
668     private IdPool createGlobalPool(WriteTransaction tx, String poolName, long low, long high, long blockSize)
669             throws ReadFailedException {
670         IdPool idPool;
671         InstanceIdentifier<IdPool> idPoolInstanceIdentifier = idUtils.getIdPoolInstance(poolName);
672         Optional<IdPool> existingIdPool = singleTxDB.syncReadOptional(CONFIGURATION, idPoolInstanceIdentifier);
673         if (!existingIdPool.isPresent()) {
674             if (LOG.isDebugEnabled()) {
675                 LOG.debug("Creating new global pool {}", poolName);
676             }
677             idPool = idUtils.createGlobalPool(poolName, low, high, blockSize);
678             tx.put(CONFIGURATION, idPoolInstanceIdentifier, idPool, true);
679         } else {
680             idPool = existingIdPool.get();
681             if (LOG.isDebugEnabled()) {
682                 LOG.debug("GlobalPool exists {}", idPool);
683             }
684         }
685         return idPool;
686     }
687
688     private IdLocalPool createLocalPool(WriteTransaction tx, String localPoolName, IdPool idPool)
689             throws OperationFailedException, IdManagerException {
690         localPoolName = localPoolName.intern();
691         IdLocalPool idLocalPool = new IdLocalPool(idUtils, localPoolName);
692         allocateIdBlockFromParentPool(idLocalPool, idPool, tx);
693         String parentPool = idPool.getPoolName();
694         localPool.put(parentPool, idLocalPool);
695         LocalPoolCreateJob job = new LocalPoolCreateJob(idLocalPool, broker, idPool.getPoolName(),
696                 idPool.getBlockSize(), idUtils);
697         DataStoreJobCoordinator.getInstance().enqueueJob(localPoolName, job, IdUtils.RETRY_COUNT);
698         return idLocalPool;
699     }
700
701     private void deletePool(String poolName) {
702         LocalPoolDeleteJob job = new LocalPoolDeleteJob(poolName, broker, idUtils);
703         DataStoreJobCoordinator.getInstance().enqueueJob(poolName, job, IdUtils.RETRY_COUNT);
704     }
705
706     public void poolDeleted(String parentPoolName, String poolName) {
707         IdLocalPool idLocalPool = localPool.get(parentPoolName);
708         if (idLocalPool != null) {
709             if (idLocalPool.getPoolName().equals(poolName)) {
710                 localPool.remove(parentPoolName);
711             }
712         }
713     }
714
715     private void updateDelayedEntriesInLocalCache(List<Long> idsList, String parentPoolName,
716             IdLocalPool localPoolCache) {
717         for (long idValue : idsList) {
718             localPoolCache.getReleasedIds().addId(idValue);
719         }
720         localPool.put(parentPoolName, localPoolCache);
721     }
722
723     public java.util.Optional<IdLocalPool> getIdLocalPool(String parentPoolName) {
724         return java.util.Optional.ofNullable(localPool.get(parentPoolName))
725                 .map(localPool -> localPool.deepCopyOf());
726     }
727
728 }