8726dc5bd343f203b71ba38b77eb7e0136ad0823
[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.access.concepts.MemberName;
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.cluster.raft.RaftState;
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.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 MemberName localMemberName;
77     private final EntityOwnershipShardCommitCoordinator commitCoordinator;
78     private final EntityOwnershipListenerSupport listenerSupport;
79     private final Set<MemberName> downPeerMemberNames = new HashSet<>();
80     private final Map<String, MemberName> 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.fromShardIdString(peerId);
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 handleNonRaftCommand(final Object message) {
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.handleNonRaftCommand(message);
139         }
140     }
141
142     private void onSelectOwner(SelectOwner selectOwner) {
143         LOG.debug("{}: onSelectOwner: {}", persistenceId(), selectOwner);
144
145         String currentOwner = getCurrentOwner(selectOwner.getEntityPath());
146         if(Strings.isNullOrEmpty(currentOwner)) {
147             String entityType = EntityOwnersModel.entityTypeFromEntityPath(selectOwner.getEntityPath());
148             writeNewOwner(selectOwner.getEntityPath(), newOwner(currentOwner, selectOwner.getAllCandidates(),
149                     entityOwnershipStatistics.byEntityType(entityType),
150                     selectOwner.getOwnerSelectionStrategy()));
151
152             Cancellable cancellable = entityToScheduledOwnershipTask.get(selectOwner.getEntityPath());
153             if(cancellable != null){
154                 if(!cancellable.isCancelled()){
155                     cancellable.cancel();
156                 }
157                 entityToScheduledOwnershipTask.remove(selectOwner.getEntityPath());
158             }
159         }
160     }
161
162     private void onRegisterCandidateLocal(RegisterCandidateLocal registerCandidate) {
163         LOG.debug("{}: onRegisterCandidateLocal: {}", persistenceId(), registerCandidate);
164
165         listenerSupport.setHasCandidateForEntity(registerCandidate.getEntity());
166
167         NormalizedNode<?, ?> entityOwners = entityOwnersWithCandidate(registerCandidate.getEntity().getType(),
168                 registerCandidate.getEntity().getId(), localMemberName.getName());
169         commitCoordinator.commitModification(new MergeModification(ENTITY_OWNERS_PATH, entityOwners), this);
170
171         getSender().tell(SuccessReply.INSTANCE, getSelf());
172     }
173
174     private void onUnregisterCandidateLocal(UnregisterCandidateLocal unregisterCandidate) {
175         LOG.debug("{}: onUnregisterCandidateLocal: {}", persistenceId(), unregisterCandidate);
176
177         Entity entity = unregisterCandidate.getEntity();
178         listenerSupport.unsetHasCandidateForEntity(entity);
179
180         YangInstanceIdentifier candidatePath = candidatePath(entity.getType(), entity.getId(), localMemberName.getName());
181         commitCoordinator.commitModification(new DeleteModification(candidatePath), this);
182
183         getSender().tell(SuccessReply.INSTANCE, getSelf());
184     }
185
186     private void onRegisterListenerLocal(final RegisterListenerLocal registerListener) {
187         LOG.debug("{}: onRegisterListenerLocal: {}", persistenceId(), registerListener);
188
189         listenerSupport.addEntityOwnershipListener(registerListener.getEntityType(), registerListener.getListener());
190
191         getSender().tell(SuccessReply.INSTANCE, getSelf());
192
193         searchForEntities((entityTypeNode, 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.getName().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     private void onUnregisterListenerLocal(UnregisterListenerLocal unregisterListener) {
219         LOG.debug("{}: onUnregisterListenerLocal: {}", persistenceId(), unregisterListener);
220
221         listenerSupport.removeEntityOwnershipListener(unregisterListener.getEntityType(), unregisterListener.getListener());
222
223         getSender().tell(SuccessReply.INSTANCE, getSelf());
224     }
225
226     void tryCommitModifications(final BatchedModifications modifications) {
227         if(isLeader()) {
228             LOG.debug("{}: Committing BatchedModifications {} locally", persistenceId(), modifications.getTransactionID());
229
230             // Note that it's possible the commit won't get consensus and will timeout and not be applied
231             // to the state. However we don't need to retry it in that case b/c it will be committed to
232             // the journal first and, once a majority of followers come back on line and it is replicated,
233             // it will be applied at that point.
234             handleBatchedModificationsLocal(modifications, self());
235         } else {
236             final ActorSelection leader = getLeader();
237             if (leader != null) {
238                 if(LOG.isDebugEnabled()) {
239                     LOG.debug("{}: Sending BatchedModifications {} to leader {}", persistenceId(),
240                             modifications.getTransactionID(), leader);
241                 }
242
243                 Future<Object> future = Patterns.ask(leader, modifications, TimeUnit.SECONDS.toMillis(
244                         getDatastoreContext().getShardTransactionCommitTimeoutInSeconds()));
245
246                 Patterns.pipe(future, getContext().dispatcher()).pipeTo(getSelf(), ActorRef.noSender());
247             }
248         }
249     }
250
251     boolean hasLeader() {
252         return getLeader() != null && !isIsolatedLeader();
253     }
254
255     /**
256      * Determine if we are in jeopardy based on observed RAFT state.
257      */
258     private static boolean inJeopardy(final RaftState state) {
259         switch (state) {
260             case Candidate:
261             case Follower:
262             case Leader:
263                 return false;
264             case IsolatedLeader:
265                 return true;
266         }
267         throw new IllegalStateException("Unsupported RAFT state " + state);
268     }
269
270     private void notifyAllListeners() {
271         searchForEntities((entityTypeNode, entityNode) -> {
272             Optional<DataContainerChild<?, ?>> possibleType = entityTypeNode.getChild(ENTITY_TYPE_NODE_ID);
273             if (possibleType.isPresent()) {
274                 final boolean hasOwner;
275                 final boolean isOwner;
276
277                 Optional<DataContainerChild<?, ?>> possibleOwner = entityNode.getChild(ENTITY_OWNER_NODE_ID);
278                 if (possibleOwner.isPresent()) {
279                     isOwner = localMemberName.getName().equals(possibleOwner.get().getValue().toString());
280                     hasOwner = true;
281                 } else {
282                     isOwner = false;
283                     hasOwner = false;
284                 }
285
286                 Entity entity = new Entity(possibleType.get().getValue().toString(),
287                     (YangInstanceIdentifier) entityNode.getChild(ENTITY_ID_NODE_ID).get().getValue());
288
289                 listenerSupport.notifyEntityOwnershipListeners(entity, isOwner, isOwner, hasOwner);
290             }
291         });
292     }
293
294     @Override
295     protected void onStateChanged() {
296         super.onStateChanged();
297
298         boolean isLeader = isLeader();
299         LOG.debug("{}: onStateChanged: isLeader: {}, hasLeader: {}", persistenceId(), isLeader, hasLeader());
300
301         // Examine current RAFT state to see if we are in jeopardy, potentially notifying all listeners
302         final boolean inJeopardy = inJeopardy(getRaftState());
303         final boolean wasInJeopardy = listenerSupport.setInJeopardy(inJeopardy);
304         if (inJeopardy != wasInJeopardy) {
305             LOG.debug("{}: {} jeopardy state, notifying all listeners", persistenceId(),
306                 inJeopardy ? "entered" : "left");
307             notifyAllListeners();
308         }
309
310         commitCoordinator.onStateChanged(this, isLeader);
311     }
312
313     @Override
314     protected void onLeaderChanged(String oldLeader, String newLeader) {
315         super.onLeaderChanged(oldLeader, newLeader);
316
317         boolean isLeader = isLeader();
318         LOG.debug("{}: onLeaderChanged: oldLeader: {}, newLeader: {}, isLeader: {}", persistenceId(), oldLeader,
319                 newLeader, isLeader);
320
321         if (isLeader) {
322
323             // Clear all existing strategies so that they get re-created when we call createStrategy again
324             // This allows the strategies to be re-initialized with existing statistics maintained by
325             // EntityOwnershipStatistics
326             strategyConfig.clearStrategies();
327
328             // Remove the candidates for all members that are known to be down. In a cluster which has greater than
329             // 3 nodes it is possible for a some node beside the leader being down when the leadership transitions
330             // it makes sense to use this event to remove all the candidates for those downed nodes
331             for (MemberName downPeerName : downPeerMemberNames) {
332                 removeCandidateFromEntities(downPeerName);
333             }
334         } else {
335             // The leader changed - notify the coordinator to check if pending modifications need to be sent.
336             // While onStateChanged also does this, this method handles the case where the shard hears from a
337             // leader and stays in the follower state. In that case no behavior state change occurs.
338             commitCoordinator.onStateChanged(this, isLeader);
339         }
340     }
341
342     private void onCandidateRemoved(CandidateRemoved message) {
343         LOG.debug("{}: onCandidateRemoved: {}", persistenceId(), message);
344
345         if(isLeader()) {
346             String currentOwner = getCurrentOwner(message.getEntityPath());
347             if(message.getRemovedCandidate().equals(currentOwner) || message.getRemainingCandidates().size() == 0){
348                 String entityType = EntityOwnersModel.entityTypeFromEntityPath(message.getEntityPath());
349                 writeNewOwner(message.getEntityPath(),
350                         newOwner(currentOwner, message.getRemainingCandidates(), entityOwnershipStatistics.byEntityType(entityType),
351                                 getEntityOwnerElectionStrategy(message.getEntityPath())));
352             }
353         } else {
354             // We're not the leader. If the removed candidate is our local member then check if we actually
355             // have a local candidate registered. If we do then we must have been partitioned from the leader
356             // and the leader removed our candidate since the leader can't tell the difference between a
357             // temporary network partition and a node's process actually restarted. So, in that case, re-add
358             // our candidate.
359             if(localMemberName.getName().equals(message.getRemovedCandidate()) &&
360                     listenerSupport.hasCandidateForEntity(createEntity(message.getEntityPath()))) {
361                 LOG.debug("Local candidate member was removed but a local candidate is registered for {}" +
362                     " - adding back local candidate", message.getEntityPath());
363
364                 commitCoordinator.commitModification(new MergeModification(
365                         candidatePath(message.getEntityPath(), localMemberName.getName()),
366                         candidateMapEntry(localMemberName.getName())), this);
367             }
368         }
369     }
370
371     private EntityOwnerSelectionStrategy getEntityOwnerElectionStrategy(YangInstanceIdentifier entityPath) {
372         final String entityType = EntityOwnersModel.entityTypeFromEntityPath(entityPath);
373         return strategyConfig.createStrategy(entityType, entityOwnershipStatistics.byEntityType(entityType));
374     }
375
376     private void onCandidateAdded(CandidateAdded message) {
377         if(!isLeader()){
378             return;
379         }
380
381         LOG.debug("{}: onCandidateAdded: {}", persistenceId(), message);
382
383         // Since a node's candidate member is only added by the node itself, we can assume the node is up so
384         // remove it from the downPeerMemberNames.
385         downPeerMemberNames.remove(message.getNewCandidate());
386
387         final String currentOwner = getCurrentOwner(message.getEntityPath());
388         final EntityOwnerSelectionStrategy strategy = getEntityOwnerElectionStrategy(message.getEntityPath());
389         final String entityType = EntityOwnersModel.entityTypeFromEntityPath(message.getEntityPath());
390
391         // Available members is all the known peers - the number of peers that are down + self
392         // So if there are 2 peers and 1 is down then availableMembers will be 2
393         final int availableMembers = (peerIdToMemberNames.size() - downPeerMemberNames.size()) + 1;
394
395         LOG.debug("{}: Using strategy {} to select owner, currentOwner = {}", persistenceId(), strategy, currentOwner);
396
397         if(!message.getAllCandidates().contains(currentOwner)){
398             if(strategy.getSelectionDelayInMillis() == 0L) {
399                 writeNewOwner(message.getEntityPath(), newOwner(currentOwner, message.getAllCandidates(),
400                         entityOwnershipStatistics.byEntityType(entityType), strategy));
401             } else if(message.getAllCandidates().size() == availableMembers) {
402                 LOG.debug("{}: Received the maximum candidates requests : {} writing new owner",
403                         persistenceId(), availableMembers);
404                 cancelOwnerSelectionTask(message.getEntityPath());
405                 writeNewOwner(message.getEntityPath(), newOwner(currentOwner, message.getAllCandidates(),
406                         entityOwnershipStatistics.byEntityType(entityType), strategy));
407             } else {
408                 scheduleOwnerSelection(message.getEntityPath(), message.getAllCandidates(), strategy);
409             }
410         }
411     }
412
413     private void onPeerDown(PeerDown peerDown) {
414         LOG.info("{}: onPeerDown: {}", persistenceId(), peerDown);
415
416         MemberName downMemberName = peerDown.getMemberName();
417         if(downPeerMemberNames.add(downMemberName) && isLeader()) {
418             // Remove the down peer as a candidate from all entities.
419             removeCandidateFromEntities(downMemberName);
420         }
421     }
422
423     private void onPeerUp(PeerUp peerUp) {
424         LOG.debug("{}: onPeerUp: {}", persistenceId(), peerUp);
425
426         peerIdToMemberNames.put(peerUp.getPeerId(), peerUp.getMemberName());
427         downPeerMemberNames.remove(peerUp.getMemberName());
428
429         // Notify the coordinator to check if pending modifications need to be sent. We do this here
430         // to handle the case where the leader's peer address isn't now yet when a prior state or
431         // leader change occurred.
432         commitCoordinator.onStateChanged(this, isLeader());
433     }
434
435     private void removeCandidateFromEntities(final MemberName owner) {
436         final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
437         searchForEntities((entityTypeNode, entityNode) -> {
438             if (hasCandidate(entityNode, owner)) {
439                 YangInstanceIdentifier entityId =
440                         (YangInstanceIdentifier) entityNode.getIdentifier().getKeyValues().get(ENTITY_ID_QNAME);
441                 YangInstanceIdentifier candidatePath = candidatePath(
442                         entityTypeNode.getIdentifier().getKeyValues().get(ENTITY_TYPE_QNAME).toString(),
443                         entityId, owner.getName());
444
445                 LOG.info("{}: Found entity {}, removing candidate {}, path {}", persistenceId(), entityId,
446                         owner, candidatePath);
447
448                 modifications.addModification(new DeleteModification(candidatePath));
449             }
450         });
451
452         commitCoordinator.commitModifications(modifications, this);
453     }
454
455     private static boolean hasCandidate(MapEntryNode entity, MemberName candidateName) {
456         return ((MapNode)entity.getChild(CANDIDATE_NODE_ID).get()).getChild(candidateNodeKey(candidateName.getName()))
457                 .isPresent();
458     }
459
460     private void searchForEntities(EntityWalker walker) {
461         Optional<NormalizedNode<?, ?>> possibleEntityTypes = getDataStore().readNode(ENTITY_TYPES_PATH);
462         if(!possibleEntityTypes.isPresent()) {
463             return;
464         }
465
466         for(MapEntryNode entityType:  ((MapNode) possibleEntityTypes.get()).getValue()) {
467             Optional<DataContainerChild<?, ?>> possibleEntities = entityType.getChild(ENTITY_NODE_ID);
468             if(!possibleEntities.isPresent()) {
469                 // shouldn't happen but handle anyway
470                 continue;
471             }
472
473             for(MapEntryNode entity:  ((MapNode) possibleEntities.get()).getValue()) {
474                 walker.onEntity(entityType, entity);
475             }
476         }
477     }
478
479     private void writeNewOwner(YangInstanceIdentifier entityPath, String newOwner) {
480         LOG.debug("{}: Writing new owner {} for entity {}", persistenceId(), newOwner, entityPath);
481
482         commitCoordinator.commitModification(new WriteModification(entityPath.node(ENTITY_OWNER_QNAME),
483                 ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)), this);
484     }
485
486     /**
487      * Schedule a new owner selection job. Cancelling any outstanding job if it has not been cancelled.
488      *
489      * @param entityPath
490      * @param allCandidates
491      */
492     public void scheduleOwnerSelection(YangInstanceIdentifier entityPath, Collection<String> allCandidates,
493                                        EntityOwnerSelectionStrategy strategy){
494         cancelOwnerSelectionTask(entityPath);
495
496         LOG.debug("{}: Scheduling owner selection after {} ms", persistenceId(), strategy.getSelectionDelayInMillis());
497
498         final Cancellable lastScheduledTask = context().system().scheduler().scheduleOnce(
499                 FiniteDuration.apply(strategy.getSelectionDelayInMillis(), TimeUnit.MILLISECONDS)
500                 , self(), new SelectOwner(entityPath, allCandidates, strategy)
501                 , context().system().dispatcher(), self());
502
503         entityToScheduledOwnershipTask.put(entityPath, lastScheduledTask);
504     }
505
506     private void cancelOwnerSelectionTask(YangInstanceIdentifier entityPath){
507         final Cancellable lastScheduledTask = entityToScheduledOwnershipTask.get(entityPath);
508         if(lastScheduledTask != null && !lastScheduledTask.isCancelled()){
509             lastScheduledTask.cancel();
510         }
511     }
512
513     private String newOwner(String currentOwner, Collection<String> candidates, Map<String, Long> statistics, EntityOwnerSelectionStrategy ownerSelectionStrategy) {
514         Collection<String> viableCandidates = getViableCandidates(candidates);
515         if(viableCandidates.size() == 0){
516             return "";
517         }
518         return ownerSelectionStrategy.newOwner(currentOwner, viableCandidates);
519     }
520
521     private Collection<String> getViableCandidates(Collection<String> candidates) {
522         Collection<String> viableCandidates = new ArrayList<>();
523
524         for (String candidate : candidates) {
525             if (!downPeerMemberNames.contains(candidate)) {
526                 viableCandidates.add(candidate);
527             }
528         }
529         return viableCandidates;
530     }
531
532     private String getCurrentOwner(YangInstanceIdentifier entityId) {
533         Optional<NormalizedNode<?, ?>> optionalEntityOwner = getDataStore().readNode(entityId.node(ENTITY_OWNER_QNAME));
534         if(optionalEntityOwner.isPresent()){
535             return optionalEntityOwner.get().getValue().toString();
536         }
537         return null;
538     }
539
540     private static interface EntityWalker {
541         void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode);
542     }
543
544     public static Builder newBuilder() {
545         return new Builder();
546     }
547
548     static class Builder extends Shard.AbstractBuilder<Builder, EntityOwnershipShard> {
549         private MemberName localMemberName;
550         private EntityOwnerSelectionStrategyConfig ownerSelectionStrategyConfig;
551
552         protected Builder() {
553             super(EntityOwnershipShard.class);
554         }
555
556         Builder localMemberName(MemberName localMemberName) {
557             checkSealed();
558             this.localMemberName = localMemberName;
559             return this;
560         }
561
562         Builder ownerSelectionStrategyConfig(EntityOwnerSelectionStrategyConfig ownerSelectionStrategyConfig){
563             checkSealed();
564             this.ownerSelectionStrategyConfig = ownerSelectionStrategyConfig;
565             return this;
566         }
567
568         @Override
569         protected void verify() {
570             super.verify();
571             Preconditions.checkNotNull(localMemberName, "localMemberName should not be null");
572             Preconditions.checkNotNull(ownerSelectionStrategyConfig, "ownerSelectionStrategyConfig should not be null");
573         }
574     }
575 }