Maintain EntityOwnershipStatistics
[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             writeNewOwner(selectOwner.getEntityPath(), newOwner(selectOwner.getAllCandidates(),
150                     selectOwner.getOwnerSelectionStrategy()));
151
152             Cancellable cancellable = entityToScheduledOwnershipTask.get(selectOwner.getEntityPath());
153             if(cancellable != null){
154                 if(!cancellable.isCancelled()){
155                     cancellable.cancel();
156                 }
157                 entityToScheduledOwnershipTask.remove(selectOwner.getEntityPath());
158             }
159         }
160     }
161
162     private void onRegisterCandidateLocal(RegisterCandidateLocal registerCandidate) {
163         LOG.debug("{}: onRegisterCandidateLocal: {}", persistenceId(), registerCandidate);
164
165         listenerSupport.setHasCandidateForEntity(registerCandidate.getEntity());
166
167         NormalizedNode<?, ?> entityOwners = entityOwnersWithCandidate(registerCandidate.getEntity().getType(),
168                 registerCandidate.getEntity().getId(), localMemberName);
169         commitCoordinator.commitModification(new MergeModification(ENTITY_OWNERS_PATH, entityOwners), this);
170
171         getSender().tell(SuccessReply.INSTANCE, getSelf());
172     }
173
174     private void onUnregisterCandidateLocal(UnregisterCandidateLocal unregisterCandidate) {
175         LOG.debug("{}: onUnregisterCandidateLocal: {}", persistenceId(), unregisterCandidate);
176
177         Entity entity = unregisterCandidate.getEntity();
178         listenerSupport.unsetHasCandidateForEntity(entity);
179
180         YangInstanceIdentifier candidatePath = candidatePath(entity.getType(), entity.getId(), localMemberName);
181         commitCoordinator.commitModification(new DeleteModification(candidatePath), this);
182
183         getSender().tell(SuccessReply.INSTANCE, getSelf());
184     }
185
186     private void onRegisterListenerLocal(final RegisterListenerLocal registerListener) {
187         LOG.debug("{}: onRegisterListenerLocal: {}", persistenceId(), registerListener);
188
189         listenerSupport.addEntityOwnershipListener(registerListener.getEntityType(), registerListener.getListener());
190
191         getSender().tell(SuccessReply.INSTANCE, getSelf());
192
193         searchForEntitiesOwnedBy(localMemberName, new EntityWalker() {
194             @Override
195             public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
196                 Optional<DataContainerChild<? extends PathArgument, ?>> possibleType =
197                         entityTypeNode.getChild(ENTITY_TYPE_NODE_ID);
198                 String entityType = possibleType.isPresent() ? possibleType.get().getValue().toString() : null;
199                 if (registerListener.getEntityType().equals(entityType)) {
200                     Entity entity = new Entity(entityType,
201                             (YangInstanceIdentifier) entityNode.getChild(ENTITY_ID_NODE_ID).get().getValue());
202                     listenerSupport.notifyEntityOwnershipListener(entity, false, true, true, registerListener.getListener());
203                 }
204             }
205         });
206     }
207
208     private void onUnregisterListenerLocal(UnregisterListenerLocal unregisterListener) {
209         LOG.debug("{}: onUnregisterListenerLocal: {}", persistenceId(), unregisterListener);
210
211         listenerSupport.removeEntityOwnershipListener(unregisterListener.getEntityType(), unregisterListener.getListener());
212
213         getSender().tell(SuccessReply.INSTANCE, getSelf());
214     }
215
216     void tryCommitModifications(final BatchedModifications modifications) {
217         if(isLeader()) {
218             LOG.debug("{}: Committing BatchedModifications {} locally", persistenceId(), modifications.getTransactionID());
219
220             // Note that it's possible the commit won't get consensus and will timeout and not be applied
221             // to the state. However we don't need to retry it in that case b/c it will be committed to
222             // the journal first and, once a majority of followers come back on line and it is replicated,
223             // it will be applied at that point.
224             handleBatchedModificationsLocal(modifications, self());
225         } else {
226             final ActorSelection leader = getLeader();
227             if (leader != null) {
228                 if(LOG.isDebugEnabled()) {
229                     LOG.debug("{}: Sending BatchedModifications {} to leader {}", persistenceId(),
230                             modifications.getTransactionID(), leader);
231                 }
232
233                 Future<Object> future = Patterns.ask(leader, modifications, TimeUnit.SECONDS.toMillis(
234                         getDatastoreContext().getShardTransactionCommitTimeoutInSeconds()));
235
236                 Patterns.pipe(future, getContext().dispatcher()).pipeTo(getSelf(), ActorRef.noSender());
237             }
238         }
239     }
240
241     boolean hasLeader() {
242         return getLeader() != null && !isIsolatedLeader();
243     }
244
245     @Override
246     protected void onStateChanged() {
247         super.onStateChanged();
248
249         commitCoordinator.onStateChanged(this, isLeader());
250     }
251
252     @Override
253     protected void onLeaderChanged(String oldLeader, String newLeader) {
254         super.onLeaderChanged(oldLeader, newLeader);
255
256         LOG.debug("{}: onLeaderChanged: oldLeader: {}, newLeader: {}, isLeader: {}", persistenceId(), oldLeader,
257                 newLeader, isLeader());
258
259         if(isLeader()) {
260             // We were just elected leader. If the old leader is down, select new owners for the entities
261             // owned by the down leader.
262
263             String oldLeaderMemberName = peerIdToMemberNames.get(oldLeader);
264
265             LOG.debug("{}: oldLeaderMemberName: {}", persistenceId(), oldLeaderMemberName);
266
267             if(downPeerMemberNames.contains(oldLeaderMemberName)) {
268                 selectNewOwnerForEntitiesOwnedBy(oldLeaderMemberName);
269             }
270         }
271     }
272
273     private void onCandidateRemoved(CandidateRemoved message) {
274         LOG.debug("{}: onCandidateRemoved: {}", persistenceId(), message);
275
276         if(isLeader()) {
277             String currentOwner = getCurrentOwner(message.getEntityPath());
278             if(message.getRemovedCandidate().equals(currentOwner)){
279                 writeNewOwner(message.getEntityPath(),
280                         newOwner(message.getRemainingCandidates(), getEntityOwnerElectionStrategy(message.getEntityPath())));
281             }
282         } else {
283             // We're not the leader. If the removed candidate is our local member then check if we actually
284             // have a local candidate registered. If we do then we must have been partitioned from the leader
285             // and the leader removed our candidate since the leader can't tell the difference between a
286             // temporary network partition and a node's process actually restarted. So, in that case, re-add
287             // our candidate.
288             if(localMemberName.equals(message.getRemovedCandidate()) &&
289                     listenerSupport.hasCandidateForEntity(createEntity(message.getEntityPath()))) {
290                 LOG.debug("Local candidate member was removed but a local candidate is registered for {}" +
291                     " - adding back local candidate", message.getEntityPath());
292
293                 commitCoordinator.commitModification(new MergeModification(
294                         candidatePath(message.getEntityPath(), localMemberName),
295                         candidateMapEntry(localMemberName)), this);
296             }
297         }
298     }
299
300     private EntityOwnerSelectionStrategy getEntityOwnerElectionStrategy(YangInstanceIdentifier entityPath) {
301         final String entityType = EntityOwnersModel.entityTypeFromEntityPath(entityPath);
302         return strategyConfig.createStrategy(entityType);
303     }
304
305     private void onCandidateAdded(CandidateAdded message) {
306         if(!isLeader()){
307             return;
308         }
309
310         LOG.debug("{}: onCandidateAdded: {}", persistenceId(), message);
311
312         // Since a node's candidate member is only added by the node itself, we can assume the node is up so
313         // remove it from the downPeerMemberNames.
314         downPeerMemberNames.remove(message.getNewCandidate());
315
316         String currentOwner = getCurrentOwner(message.getEntityPath());
317         EntityOwnerSelectionStrategy strategy = getEntityOwnerElectionStrategy(message.getEntityPath());
318         if(Strings.isNullOrEmpty(currentOwner)){
319             if(strategy.getSelectionDelayInMillis() == 0L) {
320                 writeNewOwner(message.getEntityPath(), newOwner(message.getAllCandidates(), strategy));
321             } else {
322                 scheduleOwnerSelection(message.getEntityPath(), message.getAllCandidates(), strategy);
323             }
324         }
325     }
326
327     private void onPeerDown(PeerDown peerDown) {
328         LOG.info("{}: onPeerDown: {}", persistenceId(), peerDown);
329
330         String downMemberName = peerDown.getMemberName();
331         if(downPeerMemberNames.add(downMemberName) && isLeader()) {
332             // Remove the down peer as a candidate from all entities.
333             removeCandidateFromEntities(downMemberName);
334         }
335     }
336
337     private void onPeerUp(PeerUp peerUp) {
338         LOG.debug("{}: onPeerUp: {}", persistenceId(), peerUp);
339
340         peerIdToMemberNames.put(peerUp.getPeerId(), peerUp.getMemberName());
341         downPeerMemberNames.remove(peerUp.getMemberName());
342     }
343
344     private void selectNewOwnerForEntitiesOwnedBy(String owner) {
345         final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
346         searchForEntitiesOwnedBy(owner, new EntityWalker() {
347             @Override
348             public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
349
350                 YangInstanceIdentifier entityPath = YangInstanceIdentifier.builder(ENTITY_TYPES_PATH).
351                         node(entityTypeNode.getIdentifier()).node(ENTITY_NODE_ID).node(entityNode.getIdentifier()).
352                         node(ENTITY_OWNER_NODE_ID).build();
353
354                 Object newOwner = newOwner(getCandidateNames(entityNode), getEntityOwnerElectionStrategy(entityPath));
355
356                 LOG.debug("{}: Found entity {}, writing new owner {}", persistenceId(), entityPath, newOwner);
357
358                 modifications.addModification(new WriteModification(entityPath,
359                         ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)));
360             }
361         });
362
363         commitCoordinator.commitModifications(modifications, this);
364     }
365
366     private void removeCandidateFromEntities(final String owner) {
367         final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
368         searchForEntities(new EntityWalker() {
369             @Override
370             public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
371                 if (hasCandidate(entityNode, owner)) {
372                     YangInstanceIdentifier entityId =
373                             (YangInstanceIdentifier) entityNode.getIdentifier().getKeyValues().get(ENTITY_ID_QNAME);
374                     YangInstanceIdentifier candidatePath = candidatePath(
375                             entityTypeNode.getIdentifier().getKeyValues().get(ENTITY_TYPE_QNAME).toString(),
376                             entityId, owner);
377
378                     LOG.info("{}: Found entity {}, removing candidate {}, path {}", persistenceId(), entityId,
379                             owner, candidatePath);
380
381                     modifications.addModification(new DeleteModification(candidatePath));
382                 }
383             }
384         });
385
386         commitCoordinator.commitModifications(modifications, this);
387     }
388
389     private boolean hasCandidate(MapEntryNode entity, String candidateName) {
390         return ((MapNode)entity.getChild(CANDIDATE_NODE_ID).get()).getChild(candidateNodeKey(candidateName)).isPresent();
391     }
392
393     private void searchForEntitiesOwnedBy(final String owner, final EntityWalker walker) {
394         DataTreeSnapshot snapshot = getDataStore().getDataTree().takeSnapshot();
395         Optional<NormalizedNode<?, ?>> possibleEntityTypes = snapshot.readNode(ENTITY_TYPES_PATH);
396         if(!possibleEntityTypes.isPresent()) {
397             return;
398         }
399
400         LOG.debug("{}: Searching for entities owned by {}", persistenceId(), owner);
401
402         searchForEntities(new EntityWalker() {
403             @Override
404             public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
405                 Optional<DataContainerChild<? extends PathArgument, ?>> possibleOwner =
406                         entityNode.getChild(ENTITY_OWNER_NODE_ID);
407                 if(possibleOwner.isPresent() && owner.equals(possibleOwner.get().getValue().toString())) {
408                     walker.onEntity(entityTypeNode, entityNode);
409                 }
410             }
411         });
412     }
413
414     private void searchForEntities(EntityWalker walker) {
415         DataTreeSnapshot snapshot = getDataStore().getDataTree().takeSnapshot();
416         Optional<NormalizedNode<?, ?>> possibleEntityTypes = snapshot.readNode(ENTITY_TYPES_PATH);
417         if(!possibleEntityTypes.isPresent()) {
418             return;
419         }
420
421         for(MapEntryNode entityType:  ((MapNode) possibleEntityTypes.get()).getValue()) {
422             Optional<DataContainerChild<? extends PathArgument, ?>> possibleEntities =
423                     entityType.getChild(ENTITY_NODE_ID);
424             if(!possibleEntities.isPresent()) {
425                 continue; // shouldn't happen but handle anyway
426             }
427
428             for(MapEntryNode entity:  ((MapNode) possibleEntities.get()).getValue()) {
429                 walker.onEntity(entityType, entity);
430             }
431         }
432     }
433
434     private Collection<String> getCandidateNames(MapEntryNode entity) {
435         Collection<MapEntryNode> candidates = ((MapNode) entity.getChild(CANDIDATE_NODE_ID).get()).getValue();
436         Collection<String> candidateNames = new ArrayList<>(candidates.size());
437         for(MapEntryNode candidate: candidates) {
438             candidateNames.add(candidate.getChild(CANDIDATE_NAME_NODE_ID).get().getValue().toString());
439         }
440
441         return candidateNames;
442     }
443
444     private void writeNewOwner(YangInstanceIdentifier entityPath, String newOwner) {
445         LOG.debug("{}: Writing new owner {} for entity {}", persistenceId(), newOwner, entityPath);
446
447         commitCoordinator.commitModification(new WriteModification(entityPath.node(ENTITY_OWNER_QNAME),
448                 ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)), this);
449     }
450
451     /**
452      * Schedule a new owner selection job. Cancelling any outstanding job if it has not been cancelled.
453      *
454      * @param entityPath
455      * @param allCandidates
456      */
457     public void scheduleOwnerSelection(YangInstanceIdentifier entityPath, Collection<String> allCandidates,
458                                        EntityOwnerSelectionStrategy strategy){
459         Cancellable lastScheduledTask = entityToScheduledOwnershipTask.get(entityPath);
460         if(lastScheduledTask != null && !lastScheduledTask.isCancelled()){
461             lastScheduledTask.cancel();
462         }
463         lastScheduledTask = context().system().scheduler().scheduleOnce(
464                 FiniteDuration.apply(strategy.getSelectionDelayInMillis(), TimeUnit.MILLISECONDS)
465                 , self(), new SelectOwner(entityPath, allCandidates, strategy)
466                 , context().system().dispatcher(), self());
467
468         entityToScheduledOwnershipTask.put(entityPath, lastScheduledTask);
469     }
470
471     private String newOwner(Collection<String> candidates, EntityOwnerSelectionStrategy ownerSelectionStrategy) {
472         Collection<String> viableCandidates = getViableCandidates(candidates);
473         if(viableCandidates.size() == 0){
474             return "";
475         }
476         return ownerSelectionStrategy.newOwner(viableCandidates);
477     }
478
479     private Collection<String> getViableCandidates(Collection<String> candidates) {
480         Collection<String> viableCandidates = new ArrayList<>();
481
482         for (String candidate : candidates) {
483             if (!downPeerMemberNames.contains(candidate)) {
484                 viableCandidates.add(candidate);
485             }
486         }
487         return viableCandidates;
488     }
489
490     private String getCurrentOwner(YangInstanceIdentifier entityId) {
491         DataTreeSnapshot snapshot = getDataStore().getDataTree().takeSnapshot();
492         Optional<NormalizedNode<?, ?>> optionalEntityOwner = snapshot.readNode(entityId.node(ENTITY_OWNER_QNAME));
493         if(optionalEntityOwner.isPresent()){
494             return optionalEntityOwner.get().getValue().toString();
495         }
496         return null;
497     }
498
499     public static Props props(final ShardIdentifier name, final Map<String, String> peerAddresses,
500                               final DatastoreContext datastoreContext, final SchemaContext schemaContext,
501                               final String localMemberName, final EntityOwnerSelectionStrategyConfig strategyConfig) {
502         return Props.create(new Creator(name, peerAddresses, datastoreContext, schemaContext, localMemberName, strategyConfig));
503     }
504
505     private static class Creator extends AbstractShardCreator {
506         private static final long serialVersionUID = 1L;
507
508         private final String localMemberName;
509         private final EntityOwnerSelectionStrategyConfig strategyConfig;
510
511         Creator(final ShardIdentifier name, final Map<String, String> peerAddresses,
512                 final DatastoreContext datastoreContext, final SchemaContext schemaContext,
513                 final String localMemberName, EntityOwnerSelectionStrategyConfig strategyConfig) {
514             super(name, peerAddresses, datastoreContext, schemaContext);
515             this.localMemberName = localMemberName;
516             this.strategyConfig = strategyConfig;
517         }
518
519         @Override
520         public Shard create() throws Exception {
521             return new EntityOwnershipShard(name, peerAddresses, datastoreContext, schemaContext, localMemberName, strategyConfig);
522         }
523     }
524
525     private static interface EntityWalker {
526         void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode);
527     }
528 }