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