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