30fafbbb10f4e78b1a09f0a5c6ec2559a4d88bf3
[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         boolean isLeader = isLeader();
248         if(LOG.isDebugEnabled()) {
249             LOG.debug("{}: onStateChanged: isLeader: {}, hasLeader: {}", persistenceId(), isLeader, hasLeader());
250         }
251
252         commitCoordinator.onStateChanged(this, isLeader);
253     }
254
255     @Override
256     protected void onLeaderChanged(String oldLeader, String newLeader) {
257         super.onLeaderChanged(oldLeader, newLeader);
258
259         boolean isLeader = isLeader();
260         LOG.debug("{}: onLeaderChanged: oldLeader: {}, newLeader: {}, isLeader: {}", persistenceId(), oldLeader,
261                 newLeader, isLeader);
262
263         if(isLeader) {
264             // We were just elected leader. If the old leader is down, select new owners for the entities
265             // owned by the down leader.
266
267             String oldLeaderMemberName = peerIdToMemberNames.get(oldLeader);
268
269             LOG.debug("{}: oldLeaderMemberName: {}", persistenceId(), oldLeaderMemberName);
270
271             if(downPeerMemberNames.contains(oldLeaderMemberName)) {
272                 selectNewOwnerForEntitiesOwnedBy(oldLeaderMemberName);
273             }
274         } else {
275             // The leader changed - notify the coordinator to check if pending modifications need to be sent.
276             // While onStateChanged also does this, this method handles the case where the shard hears from a
277             // leader and stays in the follower state. In that case no behavior state change occurs.
278             commitCoordinator.onStateChanged(this, isLeader);
279         }
280     }
281
282     private void onCandidateRemoved(CandidateRemoved message) {
283         LOG.debug("{}: onCandidateRemoved: {}", persistenceId(), message);
284
285         if(isLeader()) {
286             String currentOwner = getCurrentOwner(message.getEntityPath());
287             if(message.getRemovedCandidate().equals(currentOwner) || message.getRemainingCandidates().size() == 0){
288                 String entityType = EntityOwnersModel.entityTypeFromEntityPath(message.getEntityPath());
289                 writeNewOwner(message.getEntityPath(),
290                         newOwner(message.getRemainingCandidates(), entityOwnershipStatistics.byEntityType(entityType),
291                                 getEntityOwnerElectionStrategy(message.getEntityPath())));
292             }
293         } else {
294             // We're not the leader. If the removed candidate is our local member then check if we actually
295             // have a local candidate registered. If we do then we must have been partitioned from the leader
296             // and the leader removed our candidate since the leader can't tell the difference between a
297             // temporary network partition and a node's process actually restarted. So, in that case, re-add
298             // our candidate.
299             if(localMemberName.equals(message.getRemovedCandidate()) &&
300                     listenerSupport.hasCandidateForEntity(createEntity(message.getEntityPath()))) {
301                 LOG.debug("Local candidate member was removed but a local candidate is registered for {}" +
302                     " - adding back local candidate", message.getEntityPath());
303
304                 commitCoordinator.commitModification(new MergeModification(
305                         candidatePath(message.getEntityPath(), localMemberName),
306                         candidateMapEntry(localMemberName)), this);
307             }
308         }
309     }
310
311     private EntityOwnerSelectionStrategy getEntityOwnerElectionStrategy(YangInstanceIdentifier entityPath) {
312         final String entityType = EntityOwnersModel.entityTypeFromEntityPath(entityPath);
313         return strategyConfig.createStrategy(entityType);
314     }
315
316     private void onCandidateAdded(CandidateAdded message) {
317         if(!isLeader()){
318             return;
319         }
320
321         LOG.debug("{}: onCandidateAdded: {}", persistenceId(), message);
322
323         // Since a node's candidate member is only added by the node itself, we can assume the node is up so
324         // remove it from the downPeerMemberNames.
325         downPeerMemberNames.remove(message.getNewCandidate());
326
327         String currentOwner = getCurrentOwner(message.getEntityPath());
328         EntityOwnerSelectionStrategy strategy = getEntityOwnerElectionStrategy(message.getEntityPath());
329         if(Strings.isNullOrEmpty(currentOwner)){
330             if(strategy.getSelectionDelayInMillis() == 0L) {
331                 String entityType = EntityOwnersModel.entityTypeFromEntityPath(message.getEntityPath());
332                 writeNewOwner(message.getEntityPath(), newOwner(message.getAllCandidates(),
333                         entityOwnershipStatistics.byEntityType(entityType), strategy));
334             } else {
335                 scheduleOwnerSelection(message.getEntityPath(), message.getAllCandidates(), strategy);
336             }
337         }
338     }
339
340     private void onPeerDown(PeerDown peerDown) {
341         LOG.info("{}: onPeerDown: {}", persistenceId(), peerDown);
342
343         String downMemberName = peerDown.getMemberName();
344         if(downPeerMemberNames.add(downMemberName) && isLeader()) {
345             // Remove the down peer as a candidate from all entities.
346             removeCandidateFromEntities(downMemberName);
347         }
348     }
349
350     private void onPeerUp(PeerUp peerUp) {
351         LOG.debug("{}: onPeerUp: {}", persistenceId(), peerUp);
352
353         peerIdToMemberNames.put(peerUp.getPeerId(), peerUp.getMemberName());
354         downPeerMemberNames.remove(peerUp.getMemberName());
355
356         // Notify the coordinator to check if pending modifications need to be sent. We do this here
357         // to handle the case where the leader's peer address isn't now yet when a prior state or
358         // leader change occurred.
359         commitCoordinator.onStateChanged(this, isLeader());
360     }
361
362     private void selectNewOwnerForEntitiesOwnedBy(String owner) {
363         final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
364         searchForEntitiesOwnedBy(owner, new EntityWalker() {
365             @Override
366             public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
367
368                 YangInstanceIdentifier entityPath = YangInstanceIdentifier.builder(ENTITY_TYPES_PATH).
369                         node(entityTypeNode.getIdentifier()).node(ENTITY_NODE_ID).node(entityNode.getIdentifier()).
370                         node(ENTITY_OWNER_NODE_ID).build();
371
372                 String entityType = EntityOwnersModel.entityTypeFromEntityPath(entityPath);
373
374                 Object newOwner = newOwner(getCandidateNames(entityNode),
375                         entityOwnershipStatistics.byEntityType(entityType),
376                         getEntityOwnerElectionStrategy(entityPath));
377
378                 LOG.debug("{}: Found entity {}, writing new owner {}", persistenceId(), entityPath, newOwner);
379
380                 modifications.addModification(new WriteModification(entityPath,
381                         ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)));
382             }
383         });
384
385         commitCoordinator.commitModifications(modifications, this);
386     }
387
388     private void removeCandidateFromEntities(final String owner) {
389         final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
390         searchForEntities(new EntityWalker() {
391             @Override
392             public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
393                 if (hasCandidate(entityNode, owner)) {
394                     YangInstanceIdentifier entityId =
395                             (YangInstanceIdentifier) entityNode.getIdentifier().getKeyValues().get(ENTITY_ID_QNAME);
396                     YangInstanceIdentifier candidatePath = candidatePath(
397                             entityTypeNode.getIdentifier().getKeyValues().get(ENTITY_TYPE_QNAME).toString(),
398                             entityId, owner);
399
400                     LOG.info("{}: Found entity {}, removing candidate {}, path {}", persistenceId(), entityId,
401                             owner, candidatePath);
402
403                     modifications.addModification(new DeleteModification(candidatePath));
404                 }
405             }
406         });
407
408         commitCoordinator.commitModifications(modifications, this);
409     }
410
411     private static boolean hasCandidate(MapEntryNode entity, String candidateName) {
412         return ((MapNode)entity.getChild(CANDIDATE_NODE_ID).get()).getChild(candidateNodeKey(candidateName)).isPresent();
413     }
414
415     private void searchForEntitiesOwnedBy(final String owner, final EntityWalker walker) {
416         Optional<NormalizedNode<?, ?>> possibleEntityTypes = getDataStore().readNode(ENTITY_TYPES_PATH);
417         if(!possibleEntityTypes.isPresent()) {
418             return;
419         }
420
421         LOG.debug("{}: Searching for entities owned by {}", persistenceId(), owner);
422
423         searchForEntities(new EntityWalker() {
424             @Override
425             public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
426                 Optional<DataContainerChild<? extends PathArgument, ?>> possibleOwner =
427                         entityNode.getChild(ENTITY_OWNER_NODE_ID);
428                 if (possibleOwner.isPresent() && owner.equals(possibleOwner.get().getValue().toString())) {
429                     walker.onEntity(entityTypeNode, entityNode);
430                 }
431             }
432         });
433     }
434
435     private void searchForEntities(EntityWalker walker) {
436         Optional<NormalizedNode<?, ?>> possibleEntityTypes = getDataStore().readNode(ENTITY_TYPES_PATH);
437         if(!possibleEntityTypes.isPresent()) {
438             return;
439         }
440
441         for(MapEntryNode entityType:  ((MapNode) possibleEntityTypes.get()).getValue()) {
442             Optional<DataContainerChild<? extends PathArgument, ?>> possibleEntities =
443                     entityType.getChild(ENTITY_NODE_ID);
444             if(!possibleEntities.isPresent()) {
445                 continue; // shouldn't happen but handle anyway
446             }
447
448             for(MapEntryNode entity:  ((MapNode) possibleEntities.get()).getValue()) {
449                 walker.onEntity(entityType, entity);
450             }
451         }
452     }
453
454     private static Collection<String> getCandidateNames(MapEntryNode entity) {
455         Collection<MapEntryNode> candidates = ((MapNode) entity.getChild(CANDIDATE_NODE_ID).get()).getValue();
456         Collection<String> candidateNames = new ArrayList<>(candidates.size());
457         for(MapEntryNode candidate: candidates) {
458             candidateNames.add(candidate.getChild(CANDIDATE_NAME_NODE_ID).get().getValue().toString());
459         }
460
461         return candidateNames;
462     }
463
464     private void writeNewOwner(YangInstanceIdentifier entityPath, String newOwner) {
465         LOG.debug("{}: Writing new owner {} for entity {}", persistenceId(), newOwner, entityPath);
466
467         commitCoordinator.commitModification(new WriteModification(entityPath.node(ENTITY_OWNER_QNAME),
468                 ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)), this);
469     }
470
471     /**
472      * Schedule a new owner selection job. Cancelling any outstanding job if it has not been cancelled.
473      *
474      * @param entityPath
475      * @param allCandidates
476      */
477     public void scheduleOwnerSelection(YangInstanceIdentifier entityPath, Collection<String> allCandidates,
478                                        EntityOwnerSelectionStrategy strategy){
479         Cancellable lastScheduledTask = entityToScheduledOwnershipTask.get(entityPath);
480         if(lastScheduledTask != null && !lastScheduledTask.isCancelled()){
481             lastScheduledTask.cancel();
482         }
483         lastScheduledTask = context().system().scheduler().scheduleOnce(
484                 FiniteDuration.apply(strategy.getSelectionDelayInMillis(), TimeUnit.MILLISECONDS)
485                 , self(), new SelectOwner(entityPath, allCandidates, strategy)
486                 , context().system().dispatcher(), self());
487
488         entityToScheduledOwnershipTask.put(entityPath, lastScheduledTask);
489     }
490
491     private String newOwner(Collection<String> candidates, Map<String, Long> statistics, EntityOwnerSelectionStrategy ownerSelectionStrategy) {
492         Collection<String> viableCandidates = getViableCandidates(candidates);
493         if(viableCandidates.size() == 0){
494             return "";
495         }
496         return ownerSelectionStrategy.newOwner(viableCandidates, statistics);
497     }
498
499     private Collection<String> getViableCandidates(Collection<String> candidates) {
500         Collection<String> viableCandidates = new ArrayList<>();
501
502         for (String candidate : candidates) {
503             if (!downPeerMemberNames.contains(candidate)) {
504                 viableCandidates.add(candidate);
505             }
506         }
507         return viableCandidates;
508     }
509
510     private String getCurrentOwner(YangInstanceIdentifier entityId) {
511         Optional<NormalizedNode<?, ?>> optionalEntityOwner = getDataStore().readNode(entityId.node(ENTITY_OWNER_QNAME));
512         if(optionalEntityOwner.isPresent()){
513             return optionalEntityOwner.get().getValue().toString();
514         }
515         return null;
516     }
517
518     private static interface EntityWalker {
519         void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode);
520     }
521
522     public static Builder newBuilder() {
523         return new Builder();
524     }
525
526     static class Builder extends Shard.AbstractBuilder<Builder, EntityOwnershipShard> {
527         private String localMemberName;
528         private EntityOwnerSelectionStrategyConfig ownerSelectionStrategyConfig;
529
530         protected Builder() {
531             super(EntityOwnershipShard.class);
532         }
533
534         Builder localMemberName(String localMemberName) {
535             checkSealed();
536             this.localMemberName = localMemberName;
537             return this;
538         }
539
540         Builder ownerSelectionStrategyConfig(EntityOwnerSelectionStrategyConfig ownerSelectionStrategyConfig){
541             checkSealed();
542             this.ownerSelectionStrategyConfig = ownerSelectionStrategyConfig;
543             return this;
544         }
545
546         @Override
547         protected void verify() {
548             super.verify();
549             Preconditions.checkNotNull(localMemberName, "localMemberName should not be null");
550             Preconditions.checkNotNull(ownerSelectionStrategyConfig, "ownerSelectionStrategyConfig should not be null");
551         }
552     }
553 }