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