799e11efc1c353bfd7a04cd124d6fd1c4ebf7d69
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / entityownership / EntityOwnershipShard.java
1 /*
2  * Copyright (c) 2015 Brocade Communications Systems, Inc. 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 package org.opendaylight.controller.cluster.datastore.entityownership;
9
10 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.CANDIDATE_NAME_NODE_ID;
11 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.CANDIDATE_NODE_ID;
12 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_ID_NODE_ID;
13 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_ID_QNAME;
14 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_NODE_ID;
15 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_OWNERS_PATH;
16 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_OWNER_NODE_ID;
17 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_OWNER_QNAME;
18 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_TYPES_PATH;
19 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_TYPE_NODE_ID;
20 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_TYPE_QNAME;
21 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.candidateMapEntry;
22 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.candidateNodeKey;
23 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.candidatePath;
24 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.createEntity;
25 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityOwnersWithCandidate;
26 import akka.actor.ActorRef;
27 import akka.actor.ActorSelection;
28 import akka.actor.Cancellable;
29 import akka.actor.Props;
30 import akka.pattern.Patterns;
31 import com.google.common.base.Optional;
32 import com.google.common.base.Strings;
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.HashMap;
36 import java.util.HashSet;
37 import java.util.Map;
38 import java.util.Set;
39 import java.util.concurrent.TimeUnit;
40 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
41 import org.opendaylight.controller.cluster.datastore.Shard;
42 import org.opendaylight.controller.cluster.datastore.entityownership.messages.CandidateAdded;
43 import org.opendaylight.controller.cluster.datastore.entityownership.messages.CandidateRemoved;
44 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterCandidateLocal;
45 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterListenerLocal;
46 import org.opendaylight.controller.cluster.datastore.entityownership.messages.SelectOwner;
47 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterCandidateLocal;
48 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterListenerLocal;
49 import org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.EntityOwnerSelectionStrategy;
50 import org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.EntityOwnerSelectionStrategyConfig;
51 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
52 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
53 import org.opendaylight.controller.cluster.datastore.messages.PeerDown;
54 import org.opendaylight.controller.cluster.datastore.messages.PeerUp;
55 import org.opendaylight.controller.cluster.datastore.messages.SuccessReply;
56 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
57 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
58 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
59 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
62 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
63 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
64 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
67 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
68 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
69 import scala.concurrent.Future;
70 import scala.concurrent.duration.FiniteDuration;
71
72 /**
73  * Special Shard for EntityOwnership.
74  *
75  * @author Thomas Pantelis
76  */
77 class EntityOwnershipShard extends Shard {
78     private final String localMemberName;
79     private final EntityOwnershipShardCommitCoordinator commitCoordinator;
80     private final EntityOwnershipListenerSupport listenerSupport;
81     private final Set<String> downPeerMemberNames = new HashSet<>();
82     private final Map<String, String> peerIdToMemberNames = new HashMap<>();
83     private EntityOwnerSelectionStrategyConfig strategyConfig;
84     private Map<YangInstanceIdentifier, Cancellable> entityToScheduledOwnershipTask = new HashMap<>();
85     private final EntityOwnershipStatistics entityOwnershipStatistics;
86
87     private static DatastoreContext noPersistenceDatastoreContext(DatastoreContext datastoreContext) {
88         return DatastoreContext.newBuilderFrom(datastoreContext).persistent(false).build();
89     }
90
91     protected EntityOwnershipShard(ShardIdentifier name, Map<String, String> peerAddresses,
92                                    DatastoreContext datastoreContext, SchemaContext schemaContext, String localMemberName,
93                                    EntityOwnerSelectionStrategyConfig strategyConfig) {
94         super(name, peerAddresses, noPersistenceDatastoreContext(datastoreContext), schemaContext);
95         this.localMemberName = localMemberName;
96         this.commitCoordinator = new EntityOwnershipShardCommitCoordinator(localMemberName, LOG);
97         this.listenerSupport = new EntityOwnershipListenerSupport(getContext(), persistenceId());
98         this.strategyConfig = strategyConfig;
99         this.entityOwnershipStatistics = new EntityOwnershipStatistics();
100         this.entityOwnershipStatistics.init(getDataStore());
101
102         for(String peerId: peerAddresses.keySet()) {
103             ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(peerId).build();
104             peerIdToMemberNames.put(peerId, shardId.getMemberName());
105         }
106     }
107
108     @Override
109     protected void onDatastoreContext(DatastoreContext context) {
110         super.onDatastoreContext(noPersistenceDatastoreContext(context));
111     }
112
113     @Override
114     protected void onRecoveryComplete() {
115         super.onRecoveryComplete();
116
117         new CandidateListChangeListener(getSelf(), persistenceId()).init(getDataStore());
118         new EntityOwnerChangeListener(localMemberName, listenerSupport).init(getDataStore());
119     }
120
121     @Override
122     public void onReceiveCommand(final Object message) throws Exception {
123         if(message instanceof RegisterCandidateLocal) {
124             onRegisterCandidateLocal((RegisterCandidateLocal) message);
125         } else if(message instanceof UnregisterCandidateLocal) {
126             onUnregisterCandidateLocal((UnregisterCandidateLocal)message);
127         } else if(message instanceof CandidateAdded){
128             onCandidateAdded((CandidateAdded) message);
129         } else if(message instanceof CandidateRemoved){
130             onCandidateRemoved((CandidateRemoved) message);
131         } else if(message instanceof PeerDown) {
132             onPeerDown((PeerDown) message);
133         } else if(message instanceof PeerUp) {
134             onPeerUp((PeerUp) message);
135         } else if(message instanceof RegisterListenerLocal) {
136             onRegisterListenerLocal((RegisterListenerLocal)message);
137         } else if(message instanceof UnregisterListenerLocal) {
138             onUnregisterListenerLocal((UnregisterListenerLocal) message);
139         } else if(message instanceof SelectOwner) {
140             onSelectOwner((SelectOwner) message);
141         } else if(!commitCoordinator.handleMessage(message, this)) {
142             super.onReceiveCommand(message);
143         }
144     }
145
146     private void onSelectOwner(SelectOwner selectOwner) {
147         String currentOwner = getCurrentOwner(selectOwner.getEntityPath());
148         if(Strings.isNullOrEmpty(currentOwner)) {
149             String entityType = EntityOwnersModel.entityTypeFromEntityPath(selectOwner.getEntityPath());
150             writeNewOwner(selectOwner.getEntityPath(), newOwner(selectOwner.getAllCandidates(),
151                     entityOwnershipStatistics.byEntityType(entityType),
152                     selectOwner.getOwnerSelectionStrategy()));
153
154             Cancellable cancellable = entityToScheduledOwnershipTask.get(selectOwner.getEntityPath());
155             if(cancellable != null){
156                 if(!cancellable.isCancelled()){
157                     cancellable.cancel();
158                 }
159                 entityToScheduledOwnershipTask.remove(selectOwner.getEntityPath());
160             }
161         }
162     }
163
164     private void onRegisterCandidateLocal(RegisterCandidateLocal registerCandidate) {
165         LOG.debug("{}: onRegisterCandidateLocal: {}", persistenceId(), registerCandidate);
166
167         listenerSupport.setHasCandidateForEntity(registerCandidate.getEntity());
168
169         NormalizedNode<?, ?> entityOwners = entityOwnersWithCandidate(registerCandidate.getEntity().getType(),
170                 registerCandidate.getEntity().getId(), localMemberName);
171         commitCoordinator.commitModification(new MergeModification(ENTITY_OWNERS_PATH, entityOwners), this);
172
173         getSender().tell(SuccessReply.INSTANCE, getSelf());
174     }
175
176     private void onUnregisterCandidateLocal(UnregisterCandidateLocal unregisterCandidate) {
177         LOG.debug("{}: onUnregisterCandidateLocal: {}", persistenceId(), unregisterCandidate);
178
179         Entity entity = unregisterCandidate.getEntity();
180         listenerSupport.unsetHasCandidateForEntity(entity);
181
182         YangInstanceIdentifier candidatePath = candidatePath(entity.getType(), entity.getId(), localMemberName);
183         commitCoordinator.commitModification(new DeleteModification(candidatePath), this);
184
185         getSender().tell(SuccessReply.INSTANCE, getSelf());
186     }
187
188     private void onRegisterListenerLocal(final RegisterListenerLocal registerListener) {
189         LOG.debug("{}: onRegisterListenerLocal: {}", persistenceId(), registerListener);
190
191         listenerSupport.addEntityOwnershipListener(registerListener.getEntityType(), registerListener.getListener());
192
193         getSender().tell(SuccessReply.INSTANCE, getSelf());
194
195         searchForEntitiesOwnedBy(localMemberName, new EntityWalker() {
196             @Override
197             public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
198                 Optional<DataContainerChild<? extends PathArgument, ?>> possibleType =
199                         entityTypeNode.getChild(ENTITY_TYPE_NODE_ID);
200                 String entityType = possibleType.isPresent() ? possibleType.get().getValue().toString() : null;
201                 if (registerListener.getEntityType().equals(entityType)) {
202                     Entity entity = new Entity(entityType,
203                             (YangInstanceIdentifier) entityNode.getChild(ENTITY_ID_NODE_ID).get().getValue());
204                     listenerSupport.notifyEntityOwnershipListener(entity, false, true, true, registerListener.getListener());
205                 }
206             }
207         });
208     }
209
210     private void onUnregisterListenerLocal(UnregisterListenerLocal unregisterListener) {
211         LOG.debug("{}: onUnregisterListenerLocal: {}", persistenceId(), unregisterListener);
212
213         listenerSupport.removeEntityOwnershipListener(unregisterListener.getEntityType(), unregisterListener.getListener());
214
215         getSender().tell(SuccessReply.INSTANCE, getSelf());
216     }
217
218     void tryCommitModifications(final BatchedModifications modifications) {
219         if(isLeader()) {
220             LOG.debug("{}: Committing BatchedModifications {} locally", persistenceId(), modifications.getTransactionID());
221
222             // Note that it's possible the commit won't get consensus and will timeout and not be applied
223             // to the state. However we don't need to retry it in that case b/c it will be committed to
224             // the journal first and, once a majority of followers come back on line and it is replicated,
225             // it will be applied at that point.
226             handleBatchedModificationsLocal(modifications, self());
227         } else {
228             final ActorSelection leader = getLeader();
229             if (leader != null) {
230                 if(LOG.isDebugEnabled()) {
231                     LOG.debug("{}: Sending BatchedModifications {} to leader {}", persistenceId(),
232                             modifications.getTransactionID(), leader);
233                 }
234
235                 Future<Object> future = Patterns.ask(leader, modifications, TimeUnit.SECONDS.toMillis(
236                         getDatastoreContext().getShardTransactionCommitTimeoutInSeconds()));
237
238                 Patterns.pipe(future, getContext().dispatcher()).pipeTo(getSelf(), ActorRef.noSender());
239             }
240         }
241     }
242
243     boolean hasLeader() {
244         return getLeader() != null && !isIsolatedLeader();
245     }
246
247     @Override
248     protected void onStateChanged() {
249         super.onStateChanged();
250
251         commitCoordinator.onStateChanged(this, isLeader());
252     }
253
254     @Override
255     protected void onLeaderChanged(String oldLeader, String newLeader) {
256         super.onLeaderChanged(oldLeader, newLeader);
257
258         LOG.debug("{}: onLeaderChanged: oldLeader: {}, newLeader: {}, isLeader: {}", persistenceId(), oldLeader,
259                 newLeader, isLeader());
260
261         if(isLeader()) {
262             // We were just elected leader. If the old leader is down, select new owners for the entities
263             // owned by the down leader.
264
265             String oldLeaderMemberName = peerIdToMemberNames.get(oldLeader);
266
267             LOG.debug("{}: oldLeaderMemberName: {}", persistenceId(), oldLeaderMemberName);
268
269             if(downPeerMemberNames.contains(oldLeaderMemberName)) {
270                 selectNewOwnerForEntitiesOwnedBy(oldLeaderMemberName);
271             }
272         }
273     }
274
275     private void onCandidateRemoved(CandidateRemoved message) {
276         LOG.debug("{}: onCandidateRemoved: {}", persistenceId(), message);
277
278         if(isLeader()) {
279             String currentOwner = getCurrentOwner(message.getEntityPath());
280             if(message.getRemovedCandidate().equals(currentOwner)){
281                 String entityType = EntityOwnersModel.entityTypeFromEntityPath(message.getEntityPath());
282                 writeNewOwner(message.getEntityPath(),
283                         newOwner(message.getRemainingCandidates(), entityOwnershipStatistics.byEntityType(entityType),
284                                 getEntityOwnerElectionStrategy(message.getEntityPath())));
285             }
286         } else {
287             // We're not the leader. If the removed candidate is our local member then check if we actually
288             // have a local candidate registered. If we do then we must have been partitioned from the leader
289             // and the leader removed our candidate since the leader can't tell the difference between a
290             // temporary network partition and a node's process actually restarted. So, in that case, re-add
291             // our candidate.
292             if(localMemberName.equals(message.getRemovedCandidate()) &&
293                     listenerSupport.hasCandidateForEntity(createEntity(message.getEntityPath()))) {
294                 LOG.debug("Local candidate member was removed but a local candidate is registered for {}" +
295                     " - adding back local candidate", message.getEntityPath());
296
297                 commitCoordinator.commitModification(new MergeModification(
298                         candidatePath(message.getEntityPath(), localMemberName),
299                         candidateMapEntry(localMemberName)), this);
300             }
301         }
302     }
303
304     private EntityOwnerSelectionStrategy getEntityOwnerElectionStrategy(YangInstanceIdentifier entityPath) {
305         final String entityType = EntityOwnersModel.entityTypeFromEntityPath(entityPath);
306         return strategyConfig.createStrategy(entityType);
307     }
308
309     private void onCandidateAdded(CandidateAdded message) {
310         if(!isLeader()){
311             return;
312         }
313
314         LOG.debug("{}: onCandidateAdded: {}", persistenceId(), message);
315
316         // Since a node's candidate member is only added by the node itself, we can assume the node is up so
317         // remove it from the downPeerMemberNames.
318         downPeerMemberNames.remove(message.getNewCandidate());
319
320         String currentOwner = getCurrentOwner(message.getEntityPath());
321         EntityOwnerSelectionStrategy strategy = getEntityOwnerElectionStrategy(message.getEntityPath());
322         if(Strings.isNullOrEmpty(currentOwner)){
323             if(strategy.getSelectionDelayInMillis() == 0L) {
324                 String entityType = EntityOwnersModel.entityTypeFromEntityPath(message.getEntityPath());
325                 writeNewOwner(message.getEntityPath(), newOwner(message.getAllCandidates(),
326                         entityOwnershipStatistics.byEntityType(entityType), strategy));
327             } else {
328                 scheduleOwnerSelection(message.getEntityPath(), message.getAllCandidates(), strategy);
329             }
330         }
331     }
332
333     private void onPeerDown(PeerDown peerDown) {
334         LOG.info("{}: onPeerDown: {}", persistenceId(), peerDown);
335
336         String downMemberName = peerDown.getMemberName();
337         if(downPeerMemberNames.add(downMemberName) && isLeader()) {
338             // Remove the down peer as a candidate from all entities.
339             removeCandidateFromEntities(downMemberName);
340         }
341     }
342
343     private void onPeerUp(PeerUp peerUp) {
344         LOG.debug("{}: onPeerUp: {}", persistenceId(), peerUp);
345
346         peerIdToMemberNames.put(peerUp.getPeerId(), peerUp.getMemberName());
347         downPeerMemberNames.remove(peerUp.getMemberName());
348     }
349
350     private void selectNewOwnerForEntitiesOwnedBy(String owner) {
351         final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
352         searchForEntitiesOwnedBy(owner, new EntityWalker() {
353             @Override
354             public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
355
356                 YangInstanceIdentifier entityPath = YangInstanceIdentifier.builder(ENTITY_TYPES_PATH).
357                         node(entityTypeNode.getIdentifier()).node(ENTITY_NODE_ID).node(entityNode.getIdentifier()).
358                         node(ENTITY_OWNER_NODE_ID).build();
359
360                 String entityType = EntityOwnersModel.entityTypeFromEntityPath(entityPath);
361
362                 Object newOwner = newOwner(getCandidateNames(entityNode),
363                         entityOwnershipStatistics.byEntityType(entityType),
364                         getEntityOwnerElectionStrategy(entityPath));
365
366                 LOG.debug("{}: Found entity {}, writing new owner {}", persistenceId(), entityPath, newOwner);
367
368                 modifications.addModification(new WriteModification(entityPath,
369                         ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)));
370             }
371         });
372
373         commitCoordinator.commitModifications(modifications, this);
374     }
375
376     private void removeCandidateFromEntities(final String owner) {
377         final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
378         searchForEntities(new EntityWalker() {
379             @Override
380             public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
381                 if (hasCandidate(entityNode, owner)) {
382                     YangInstanceIdentifier entityId =
383                             (YangInstanceIdentifier) entityNode.getIdentifier().getKeyValues().get(ENTITY_ID_QNAME);
384                     YangInstanceIdentifier candidatePath = candidatePath(
385                             entityTypeNode.getIdentifier().getKeyValues().get(ENTITY_TYPE_QNAME).toString(),
386                             entityId, owner);
387
388                     LOG.info("{}: Found entity {}, removing candidate {}, path {}", persistenceId(), entityId,
389                             owner, candidatePath);
390
391                     modifications.addModification(new DeleteModification(candidatePath));
392                 }
393             }
394         });
395
396         commitCoordinator.commitModifications(modifications, this);
397     }
398
399     private boolean hasCandidate(MapEntryNode entity, String candidateName) {
400         return ((MapNode)entity.getChild(CANDIDATE_NODE_ID).get()).getChild(candidateNodeKey(candidateName)).isPresent();
401     }
402
403     private void searchForEntitiesOwnedBy(final String owner, final EntityWalker walker) {
404         DataTreeSnapshot snapshot = getDataStore().getDataTree().takeSnapshot();
405         Optional<NormalizedNode<?, ?>> possibleEntityTypes = snapshot.readNode(ENTITY_TYPES_PATH);
406         if(!possibleEntityTypes.isPresent()) {
407             return;
408         }
409
410         LOG.debug("{}: Searching for entities owned by {}", persistenceId(), owner);
411
412         searchForEntities(new EntityWalker() {
413             @Override
414             public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
415                 Optional<DataContainerChild<? extends PathArgument, ?>> possibleOwner =
416                         entityNode.getChild(ENTITY_OWNER_NODE_ID);
417                 if(possibleOwner.isPresent() && owner.equals(possibleOwner.get().getValue().toString())) {
418                     walker.onEntity(entityTypeNode, entityNode);
419                 }
420             }
421         });
422     }
423
424     private void searchForEntities(EntityWalker walker) {
425         DataTreeSnapshot snapshot = getDataStore().getDataTree().takeSnapshot();
426         Optional<NormalizedNode<?, ?>> possibleEntityTypes = snapshot.readNode(ENTITY_TYPES_PATH);
427         if(!possibleEntityTypes.isPresent()) {
428             return;
429         }
430
431         for(MapEntryNode entityType:  ((MapNode) possibleEntityTypes.get()).getValue()) {
432             Optional<DataContainerChild<? extends PathArgument, ?>> possibleEntities =
433                     entityType.getChild(ENTITY_NODE_ID);
434             if(!possibleEntities.isPresent()) {
435                 continue; // shouldn't happen but handle anyway
436             }
437
438             for(MapEntryNode entity:  ((MapNode) possibleEntities.get()).getValue()) {
439                 walker.onEntity(entityType, entity);
440             }
441         }
442     }
443
444     private Collection<String> getCandidateNames(MapEntryNode entity) {
445         Collection<MapEntryNode> candidates = ((MapNode) entity.getChild(CANDIDATE_NODE_ID).get()).getValue();
446         Collection<String> candidateNames = new ArrayList<>(candidates.size());
447         for(MapEntryNode candidate: candidates) {
448             candidateNames.add(candidate.getChild(CANDIDATE_NAME_NODE_ID).get().getValue().toString());
449         }
450
451         return candidateNames;
452     }
453
454     private void writeNewOwner(YangInstanceIdentifier entityPath, String newOwner) {
455         LOG.debug("{}: Writing new owner {} for entity {}", persistenceId(), newOwner, entityPath);
456
457         commitCoordinator.commitModification(new WriteModification(entityPath.node(ENTITY_OWNER_QNAME),
458                 ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)), this);
459     }
460
461     /**
462      * Schedule a new owner selection job. Cancelling any outstanding job if it has not been cancelled.
463      *
464      * @param entityPath
465      * @param allCandidates
466      */
467     public void scheduleOwnerSelection(YangInstanceIdentifier entityPath, Collection<String> allCandidates,
468                                        EntityOwnerSelectionStrategy strategy){
469         Cancellable lastScheduledTask = entityToScheduledOwnershipTask.get(entityPath);
470         if(lastScheduledTask != null && !lastScheduledTask.isCancelled()){
471             lastScheduledTask.cancel();
472         }
473         lastScheduledTask = context().system().scheduler().scheduleOnce(
474                 FiniteDuration.apply(strategy.getSelectionDelayInMillis(), TimeUnit.MILLISECONDS)
475                 , self(), new SelectOwner(entityPath, allCandidates, strategy)
476                 , context().system().dispatcher(), self());
477
478         entityToScheduledOwnershipTask.put(entityPath, lastScheduledTask);
479     }
480
481     private String newOwner(Collection<String> candidates, Map<String, Long> statistics, EntityOwnerSelectionStrategy ownerSelectionStrategy) {
482         Collection<String> viableCandidates = getViableCandidates(candidates);
483         if(viableCandidates.size() == 0){
484             return "";
485         }
486         return ownerSelectionStrategy.newOwner(viableCandidates, statistics);
487     }
488
489     private Collection<String> getViableCandidates(Collection<String> candidates) {
490         Collection<String> viableCandidates = new ArrayList<>();
491
492         for (String candidate : candidates) {
493             if (!downPeerMemberNames.contains(candidate)) {
494                 viableCandidates.add(candidate);
495             }
496         }
497         return viableCandidates;
498     }
499
500     private String getCurrentOwner(YangInstanceIdentifier entityId) {
501         DataTreeSnapshot snapshot = getDataStore().getDataTree().takeSnapshot();
502         Optional<NormalizedNode<?, ?>> optionalEntityOwner = snapshot.readNode(entityId.node(ENTITY_OWNER_QNAME));
503         if(optionalEntityOwner.isPresent()){
504             return optionalEntityOwner.get().getValue().toString();
505         }
506         return null;
507     }
508
509     public static Props props(final ShardIdentifier name, final Map<String, String> peerAddresses,
510                               final DatastoreContext datastoreContext, final SchemaContext schemaContext,
511                               final String localMemberName, final EntityOwnerSelectionStrategyConfig strategyConfig) {
512         return Props.create(new Creator(name, peerAddresses, datastoreContext, schemaContext, localMemberName, strategyConfig));
513     }
514
515     private static class Creator extends AbstractShardCreator {
516         private static final long serialVersionUID = 1L;
517
518         private final String localMemberName;
519         private final EntityOwnerSelectionStrategyConfig strategyConfig;
520
521         Creator(final ShardIdentifier name, final Map<String, String> peerAddresses,
522                 final DatastoreContext datastoreContext, final SchemaContext schemaContext,
523                 final String localMemberName, EntityOwnerSelectionStrategyConfig strategyConfig) {
524             super(name, peerAddresses, datastoreContext, schemaContext);
525             this.localMemberName = localMemberName;
526             this.strategyConfig = strategyConfig;
527         }
528
529         @Override
530         public Shard create() throws Exception {
531             return new EntityOwnershipShard(name, peerAddresses, datastoreContext, schemaContext, localMemberName, strategyConfig);
532         }
533     }
534
535     private static interface EntityWalker {
536         void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode);
537     }
538 }