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