BUG 4554 : Ownership is not cleared when all candidates are removed
[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.base.Optional;
31 import com.google.common.base.Preconditions;
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.impl.schema.ImmutableNodes;
67 import scala.concurrent.Future;
68 import scala.concurrent.duration.FiniteDuration;
69
70 /**
71  * Special Shard for EntityOwnership.
72  *
73  * @author Thomas Pantelis
74  */
75 class EntityOwnershipShard extends Shard {
76     private final String localMemberName;
77     private final EntityOwnershipShardCommitCoordinator commitCoordinator;
78     private final EntityOwnershipListenerSupport listenerSupport;
79     private final Set<String> downPeerMemberNames = new HashSet<>();
80     private final Map<String, String> peerIdToMemberNames = new HashMap<>();
81     private final EntityOwnerSelectionStrategyConfig strategyConfig;
82     private final Map<YangInstanceIdentifier, Cancellable> entityToScheduledOwnershipTask = new HashMap<>();
83     private final EntityOwnershipStatistics entityOwnershipStatistics;
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 = builder.ownerSelectionStrategyConfig;
95         this.entityOwnershipStatistics = new EntityOwnershipStatistics();
96         this.entityOwnershipStatistics.init(getDataStore());
97
98         for(String peerId: getRaftActorContext().getPeerIds()) {
99             ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(peerId).build();
100             peerIdToMemberNames.put(peerId, shardId.getMemberName());
101         }
102     }
103
104     @Override
105     protected void onDatastoreContext(DatastoreContext context) {
106         super.onDatastoreContext(noPersistenceDatastoreContext(context));
107     }
108
109     @Override
110     protected void onRecoveryComplete() {
111         super.onRecoveryComplete();
112
113         new CandidateListChangeListener(getSelf(), persistenceId()).init(getDataStore());
114         new EntityOwnerChangeListener(localMemberName, listenerSupport).init(getDataStore());
115     }
116
117     @Override
118     public void onReceiveCommand(final Object message) throws Exception {
119         if(message instanceof RegisterCandidateLocal) {
120             onRegisterCandidateLocal((RegisterCandidateLocal) message);
121         } else if(message instanceof UnregisterCandidateLocal) {
122             onUnregisterCandidateLocal((UnregisterCandidateLocal)message);
123         } else if(message instanceof CandidateAdded){
124             onCandidateAdded((CandidateAdded) message);
125         } else if(message instanceof CandidateRemoved){
126             onCandidateRemoved((CandidateRemoved) message);
127         } else if(message instanceof PeerDown) {
128             onPeerDown((PeerDown) message);
129         } else if(message instanceof PeerUp) {
130             onPeerUp((PeerUp) message);
131         } else if(message instanceof RegisterListenerLocal) {
132             onRegisterListenerLocal((RegisterListenerLocal)message);
133         } else if(message instanceof UnregisterListenerLocal) {
134             onUnregisterListenerLocal((UnregisterListenerLocal) message);
135         } else if(message instanceof SelectOwner) {
136             onSelectOwner((SelectOwner) message);
137         } else if(!commitCoordinator.handleMessage(message, this)) {
138             super.onReceiveCommand(message);
139         }
140     }
141
142     private void onSelectOwner(SelectOwner selectOwner) {
143         String currentOwner = getCurrentOwner(selectOwner.getEntityPath());
144         if(Strings.isNullOrEmpty(currentOwner)) {
145             String entityType = EntityOwnersModel.entityTypeFromEntityPath(selectOwner.getEntityPath());
146             writeNewOwner(selectOwner.getEntityPath(), newOwner(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         searchForEntitiesOwnedBy(localMemberName, new EntityWalker() {
192             @Override
193             public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
194                 Optional<DataContainerChild<? extends PathArgument, ?>> possibleType =
195                         entityTypeNode.getChild(ENTITY_TYPE_NODE_ID);
196                 String entityType = possibleType.isPresent() ? possibleType.get().getValue().toString() : null;
197                 if (registerListener.getEntityType().equals(entityType)) {
198                     Entity entity = new Entity(entityType,
199                             (YangInstanceIdentifier) entityNode.getChild(ENTITY_ID_NODE_ID).get().getValue());
200                     listenerSupport.notifyEntityOwnershipListener(entity, false, true, true, registerListener.getListener());
201                 }
202             }
203         });
204     }
205
206     private void onUnregisterListenerLocal(UnregisterListenerLocal unregisterListener) {
207         LOG.debug("{}: onUnregisterListenerLocal: {}", persistenceId(), unregisterListener);
208
209         listenerSupport.removeEntityOwnershipListener(unregisterListener.getEntityType(), unregisterListener.getListener());
210
211         getSender().tell(SuccessReply.INSTANCE, getSelf());
212     }
213
214     void tryCommitModifications(final BatchedModifications modifications) {
215         if(isLeader()) {
216             LOG.debug("{}: Committing BatchedModifications {} locally", persistenceId(), modifications.getTransactionID());
217
218             // Note that it's possible the commit won't get consensus and will timeout and not be applied
219             // to the state. However we don't need to retry it in that case b/c it will be committed to
220             // the journal first and, once a majority of followers come back on line and it is replicated,
221             // it will be applied at that point.
222             handleBatchedModificationsLocal(modifications, self());
223         } else {
224             final ActorSelection leader = getLeader();
225             if (leader != null) {
226                 if(LOG.isDebugEnabled()) {
227                     LOG.debug("{}: Sending BatchedModifications {} to leader {}", persistenceId(),
228                             modifications.getTransactionID(), leader);
229                 }
230
231                 Future<Object> future = Patterns.ask(leader, modifications, TimeUnit.SECONDS.toMillis(
232                         getDatastoreContext().getShardTransactionCommitTimeoutInSeconds()));
233
234                 Patterns.pipe(future, getContext().dispatcher()).pipeTo(getSelf(), ActorRef.noSender());
235             }
236         }
237     }
238
239     boolean hasLeader() {
240         return getLeader() != null && !isIsolatedLeader();
241     }
242
243     @Override
244     protected void onStateChanged() {
245         super.onStateChanged();
246
247         commitCoordinator.onStateChanged(this, isLeader());
248     }
249
250     @Override
251     protected void onLeaderChanged(String oldLeader, String newLeader) {
252         super.onLeaderChanged(oldLeader, newLeader);
253
254         LOG.debug("{}: onLeaderChanged: oldLeader: {}, newLeader: {}, isLeader: {}", persistenceId(), oldLeader,
255                 newLeader, isLeader());
256
257         if(isLeader()) {
258             // We were just elected leader. If the old leader is down, select new owners for the entities
259             // owned by the down leader.
260
261             String oldLeaderMemberName = peerIdToMemberNames.get(oldLeader);
262
263             LOG.debug("{}: oldLeaderMemberName: {}", persistenceId(), oldLeaderMemberName);
264
265             if(downPeerMemberNames.contains(oldLeaderMemberName)) {
266                 selectNewOwnerForEntitiesOwnedBy(oldLeaderMemberName);
267             }
268         }
269     }
270
271     private void onCandidateRemoved(CandidateRemoved message) {
272         LOG.debug("{}: onCandidateRemoved: {}", persistenceId(), message);
273
274         if(isLeader()) {
275             String currentOwner = getCurrentOwner(message.getEntityPath());
276             if(message.getRemovedCandidate().equals(currentOwner) || message.getRemainingCandidates().size() == 0){
277                 String entityType = EntityOwnersModel.entityTypeFromEntityPath(message.getEntityPath());
278                 writeNewOwner(message.getEntityPath(),
279                         newOwner(message.getRemainingCandidates(), entityOwnershipStatistics.byEntityType(entityType),
280                                 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                 String entityType = EntityOwnersModel.entityTypeFromEntityPath(message.getEntityPath());
321                 writeNewOwner(message.getEntityPath(), newOwner(message.getAllCandidates(),
322                         entityOwnershipStatistics.byEntityType(entityType), strategy));
323             } else {
324                 scheduleOwnerSelection(message.getEntityPath(), message.getAllCandidates(), strategy);
325             }
326         }
327     }
328
329     private void onPeerDown(PeerDown peerDown) {
330         LOG.info("{}: onPeerDown: {}", persistenceId(), peerDown);
331
332         String downMemberName = peerDown.getMemberName();
333         if(downPeerMemberNames.add(downMemberName) && isLeader()) {
334             // Remove the down peer as a candidate from all entities.
335             removeCandidateFromEntities(downMemberName);
336         }
337     }
338
339     private void onPeerUp(PeerUp peerUp) {
340         LOG.debug("{}: onPeerUp: {}", persistenceId(), peerUp);
341
342         peerIdToMemberNames.put(peerUp.getPeerId(), peerUp.getMemberName());
343         downPeerMemberNames.remove(peerUp.getMemberName());
344     }
345
346     private void selectNewOwnerForEntitiesOwnedBy(String owner) {
347         final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
348         searchForEntitiesOwnedBy(owner, new EntityWalker() {
349             @Override
350             public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
351
352                 YangInstanceIdentifier entityPath = YangInstanceIdentifier.builder(ENTITY_TYPES_PATH).
353                         node(entityTypeNode.getIdentifier()).node(ENTITY_NODE_ID).node(entityNode.getIdentifier()).
354                         node(ENTITY_OWNER_NODE_ID).build();
355
356                 String entityType = EntityOwnersModel.entityTypeFromEntityPath(entityPath);
357
358                 Object newOwner = newOwner(getCandidateNames(entityNode),
359                         entityOwnershipStatistics.byEntityType(entityType),
360                         getEntityOwnerElectionStrategy(entityPath));
361
362                 LOG.debug("{}: Found entity {}, writing new owner {}", persistenceId(), entityPath, newOwner);
363
364                 modifications.addModification(new WriteModification(entityPath,
365                         ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)));
366             }
367         });
368
369         commitCoordinator.commitModifications(modifications, this);
370     }
371
372     private void removeCandidateFromEntities(final String owner) {
373         final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
374         searchForEntities(new EntityWalker() {
375             @Override
376             public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
377                 if (hasCandidate(entityNode, owner)) {
378                     YangInstanceIdentifier entityId =
379                             (YangInstanceIdentifier) entityNode.getIdentifier().getKeyValues().get(ENTITY_ID_QNAME);
380                     YangInstanceIdentifier candidatePath = candidatePath(
381                             entityTypeNode.getIdentifier().getKeyValues().get(ENTITY_TYPE_QNAME).toString(),
382                             entityId, owner);
383
384                     LOG.info("{}: Found entity {}, removing candidate {}, path {}", persistenceId(), entityId,
385                             owner, candidatePath);
386
387                     modifications.addModification(new DeleteModification(candidatePath));
388                 }
389             }
390         });
391
392         commitCoordinator.commitModifications(modifications, this);
393     }
394
395     private static boolean hasCandidate(MapEntryNode entity, String candidateName) {
396         return ((MapNode)entity.getChild(CANDIDATE_NODE_ID).get()).getChild(candidateNodeKey(candidateName)).isPresent();
397     }
398
399     private void searchForEntitiesOwnedBy(final String owner, final EntityWalker walker) {
400         Optional<NormalizedNode<?, ?>> possibleEntityTypes = getDataStore().readNode(ENTITY_TYPES_PATH);
401         if(!possibleEntityTypes.isPresent()) {
402             return;
403         }
404
405         LOG.debug("{}: Searching for entities owned by {}", persistenceId(), owner);
406
407         searchForEntities(new EntityWalker() {
408             @Override
409             public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
410                 Optional<DataContainerChild<? extends PathArgument, ?>> possibleOwner =
411                         entityNode.getChild(ENTITY_OWNER_NODE_ID);
412                 if (possibleOwner.isPresent() && owner.equals(possibleOwner.get().getValue().toString())) {
413                     walker.onEntity(entityTypeNode, entityNode);
414                 }
415             }
416         });
417     }
418
419     private void searchForEntities(EntityWalker walker) {
420         Optional<NormalizedNode<?, ?>> possibleEntityTypes = getDataStore().readNode(ENTITY_TYPES_PATH);
421         if(!possibleEntityTypes.isPresent()) {
422             return;
423         }
424
425         for(MapEntryNode entityType:  ((MapNode) possibleEntityTypes.get()).getValue()) {
426             Optional<DataContainerChild<? extends PathArgument, ?>> possibleEntities =
427                     entityType.getChild(ENTITY_NODE_ID);
428             if(!possibleEntities.isPresent()) {
429                 continue; // shouldn't happen but handle anyway
430             }
431
432             for(MapEntryNode entity:  ((MapNode) possibleEntities.get()).getValue()) {
433                 walker.onEntity(entityType, entity);
434             }
435         }
436     }
437
438     private Collection<String> getCandidateNames(MapEntryNode entity) {
439         Collection<MapEntryNode> candidates = ((MapNode) entity.getChild(CANDIDATE_NODE_ID).get()).getValue();
440         Collection<String> candidateNames = new ArrayList<>(candidates.size());
441         for(MapEntryNode candidate: candidates) {
442             candidateNames.add(candidate.getChild(CANDIDATE_NAME_NODE_ID).get().getValue().toString());
443         }
444
445         return candidateNames;
446     }
447
448     private void writeNewOwner(YangInstanceIdentifier entityPath, String newOwner) {
449         LOG.debug("{}: Writing new owner {} for entity {}", persistenceId(), newOwner, entityPath);
450
451         commitCoordinator.commitModification(new WriteModification(entityPath.node(ENTITY_OWNER_QNAME),
452                 ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)), this);
453     }
454
455     /**
456      * Schedule a new owner selection job. Cancelling any outstanding job if it has not been cancelled.
457      *
458      * @param entityPath
459      * @param allCandidates
460      */
461     public void scheduleOwnerSelection(YangInstanceIdentifier entityPath, Collection<String> allCandidates,
462                                        EntityOwnerSelectionStrategy strategy){
463         Cancellable lastScheduledTask = entityToScheduledOwnershipTask.get(entityPath);
464         if(lastScheduledTask != null && !lastScheduledTask.isCancelled()){
465             lastScheduledTask.cancel();
466         }
467         lastScheduledTask = context().system().scheduler().scheduleOnce(
468                 FiniteDuration.apply(strategy.getSelectionDelayInMillis(), TimeUnit.MILLISECONDS)
469                 , self(), new SelectOwner(entityPath, allCandidates, strategy)
470                 , context().system().dispatcher(), self());
471
472         entityToScheduledOwnershipTask.put(entityPath, lastScheduledTask);
473     }
474
475     private String newOwner(Collection<String> candidates, Map<String, Long> statistics, EntityOwnerSelectionStrategy ownerSelectionStrategy) {
476         Collection<String> viableCandidates = getViableCandidates(candidates);
477         if(viableCandidates.size() == 0){
478             return "";
479         }
480         return ownerSelectionStrategy.newOwner(viableCandidates, statistics);
481     }
482
483     private Collection<String> getViableCandidates(Collection<String> candidates) {
484         Collection<String> viableCandidates = new ArrayList<>();
485
486         for (String candidate : candidates) {
487             if (!downPeerMemberNames.contains(candidate)) {
488                 viableCandidates.add(candidate);
489             }
490         }
491         return viableCandidates;
492     }
493
494     private String getCurrentOwner(YangInstanceIdentifier entityId) {
495         Optional<NormalizedNode<?, ?>> optionalEntityOwner = getDataStore().readNode(entityId.node(ENTITY_OWNER_QNAME));
496         if(optionalEntityOwner.isPresent()){
497             return optionalEntityOwner.get().getValue().toString();
498         }
499         return null;
500     }
501
502     private static interface EntityWalker {
503         void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode);
504     }
505
506     public static Builder newBuilder() {
507         return new Builder();
508     }
509
510     static class Builder extends Shard.AbstractBuilder<Builder, EntityOwnershipShard> {
511         private String localMemberName;
512         private EntityOwnerSelectionStrategyConfig ownerSelectionStrategyConfig;
513
514         protected Builder() {
515             super(EntityOwnershipShard.class);
516         }
517
518         Builder localMemberName(String localMemberName) {
519             checkSealed();
520             this.localMemberName = localMemberName;
521             return this;
522         }
523
524         Builder ownerSelectionStrategyConfig(EntityOwnerSelectionStrategyConfig ownerSelectionStrategyConfig){
525             checkSealed();
526             this.ownerSelectionStrategyConfig = ownerSelectionStrategyConfig;
527             return this;
528         }
529
530         @Override
531         protected void verify() {
532             super.verify();
533             Preconditions.checkNotNull(localMemberName, "localMemberName should not be null");
534             Preconditions.checkNotNull(ownerSelectionStrategyConfig, "ownerSelectionStrategyConfig should not be null");
535         }
536     }
537 }