e57874a3ad58d7c5559a174549e3ded2817d7001
[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.candidateNodeKey;
22 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.candidatePath;
23 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityOwnersWithCandidate;
24
25 import akka.actor.ActorRef;
26 import akka.actor.ActorSelection;
27 import akka.actor.Cancellable;
28 import akka.cluster.Cluster;
29 import akka.cluster.ClusterEvent.CurrentClusterState;
30 import akka.cluster.Member;
31 import akka.cluster.MemberStatus;
32 import akka.pattern.Patterns;
33 import com.google.common.base.Optional;
34 import com.google.common.base.Preconditions;
35 import com.google.common.base.Strings;
36 import com.google.common.collect.ImmutableSet;
37 import java.util.ArrayList;
38 import java.util.Collection;
39 import java.util.HashMap;
40 import java.util.HashSet;
41 import java.util.Map;
42 import java.util.Set;
43 import java.util.concurrent.TimeUnit;
44 import org.opendaylight.controller.cluster.access.concepts.MemberName;
45 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
46 import org.opendaylight.controller.cluster.datastore.Shard;
47 import org.opendaylight.controller.cluster.datastore.entityownership.messages.CandidateAdded;
48 import org.opendaylight.controller.cluster.datastore.entityownership.messages.CandidateRemoved;
49 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterCandidateLocal;
50 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterListenerLocal;
51 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RemoveAllCandidates;
52 import org.opendaylight.controller.cluster.datastore.entityownership.messages.SelectOwner;
53 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterCandidateLocal;
54 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterListenerLocal;
55 import org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.EntityOwnerSelectionStrategy;
56 import org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.EntityOwnerSelectionStrategyConfig;
57 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
58 import org.opendaylight.controller.cluster.datastore.messages.PeerDown;
59 import org.opendaylight.controller.cluster.datastore.messages.PeerUp;
60 import org.opendaylight.controller.cluster.datastore.messages.SuccessReply;
61 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
62 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
63 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
64 import org.opendaylight.controller.cluster.raft.RaftState;
65 import org.opendaylight.mdsal.eos.dom.api.DOMEntity;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
68 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
69 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
70 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
72 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
73 import scala.concurrent.Future;
74 import scala.concurrent.duration.FiniteDuration;
75
76 /**
77  * Special Shard for EntityOwnership.
78  *
79  * @author Thomas Pantelis
80  */
81 class EntityOwnershipShard extends Shard {
82     private final MemberName localMemberName;
83     private final EntityOwnershipShardCommitCoordinator commitCoordinator;
84     private final EntityOwnershipListenerSupport listenerSupport;
85     private final Set<MemberName> downPeerMemberNames = new HashSet<>();
86     private final EntityOwnerSelectionStrategyConfig strategyConfig;
87     private final Map<YangInstanceIdentifier, Cancellable> entityToScheduledOwnershipTask = new HashMap<>();
88     private final EntityOwnershipStatistics entityOwnershipStatistics;
89     private boolean removeAllInitialCandidates = true;
90
91     protected EntityOwnershipShard(final Builder builder) {
92         super(builder);
93         this.localMemberName = builder.localMemberName;
94         this.commitCoordinator = new EntityOwnershipShardCommitCoordinator(builder.localMemberName, LOG);
95         this.listenerSupport = new EntityOwnershipListenerSupport(getContext(), persistenceId());
96         this.strategyConfig = builder.ownerSelectionStrategyConfig;
97         this.entityOwnershipStatistics = new EntityOwnershipStatistics();
98         this.entityOwnershipStatistics.init(getDataStore());
99     }
100
101     private static DatastoreContext noPersistenceDatastoreContext(final DatastoreContext datastoreContext) {
102         return DatastoreContext.newBuilderFrom(datastoreContext).persistent(false).build();
103     }
104
105     @Override
106     protected void onDatastoreContext(final DatastoreContext context) {
107         super.onDatastoreContext(noPersistenceDatastoreContext(context));
108     }
109
110     @Override
111     protected void onRecoveryComplete() {
112         super.onRecoveryComplete();
113
114         new CandidateListChangeListener(getSelf(), persistenceId()).init(getDataStore());
115         new EntityOwnerChangeListener(localMemberName, listenerSupport).init(getDataStore());
116     }
117
118     @Override
119     public void handleNonRaftCommand(final Object message) {
120         if (message instanceof RegisterCandidateLocal) {
121             onRegisterCandidateLocal((RegisterCandidateLocal) message);
122         } else if (message instanceof UnregisterCandidateLocal) {
123             onUnregisterCandidateLocal((UnregisterCandidateLocal) message);
124         } else if (message instanceof CandidateAdded) {
125             onCandidateAdded((CandidateAdded) message);
126         } else if (message instanceof CandidateRemoved) {
127             onCandidateRemoved((CandidateRemoved) message);
128         } else if (message instanceof PeerDown) {
129             onPeerDown((PeerDown) message);
130         } else if (message instanceof PeerUp) {
131             onPeerUp((PeerUp) message);
132         } else if (message instanceof RegisterListenerLocal) {
133             onRegisterListenerLocal((RegisterListenerLocal) message);
134         } else if (message instanceof UnregisterListenerLocal) {
135             onUnregisterListenerLocal((UnregisterListenerLocal) message);
136         } else if (message instanceof SelectOwner) {
137             onSelectOwner((SelectOwner) message);
138         } else if (message instanceof RemoveAllCandidates) {
139             onRemoveAllCandidates((RemoveAllCandidates) message);
140         } else if (!commitCoordinator.handleMessage(message, this)) {
141             super.handleNonRaftCommand(message);
142         }
143     }
144
145     private void onRemoveAllCandidates(final RemoveAllCandidates message) {
146         LOG.debug("{}: onRemoveAllCandidates: {}", persistenceId(), message);
147
148         removeCandidateFromEntities(message.getMemberName());
149     }
150
151     private void onSelectOwner(final SelectOwner selectOwner) {
152         LOG.debug("{}: onSelectOwner: {}", persistenceId(), selectOwner);
153
154         String currentOwner = getCurrentOwner(selectOwner.getEntityPath());
155         if (Strings.isNullOrEmpty(currentOwner)) {
156             writeNewOwner(selectOwner.getEntityPath(), newOwner(currentOwner, selectOwner.getAllCandidates(),
157                     selectOwner.getOwnerSelectionStrategy()));
158
159             Cancellable cancellable = entityToScheduledOwnershipTask.get(selectOwner.getEntityPath());
160             if (cancellable != null) {
161                 if (!cancellable.isCancelled()) {
162                     cancellable.cancel();
163                 }
164                 entityToScheduledOwnershipTask.remove(selectOwner.getEntityPath());
165             }
166         }
167     }
168
169     private void onRegisterCandidateLocal(final RegisterCandidateLocal registerCandidate) {
170         LOG.debug("{}: onRegisterCandidateLocal: {}", persistenceId(), registerCandidate);
171
172         listenerSupport.setHasCandidateForEntity(registerCandidate.getEntity());
173
174         NormalizedNode<?, ?> entityOwners = entityOwnersWithCandidate(registerCandidate.getEntity().getType(),
175                 registerCandidate.getEntity().getIdentifier(), localMemberName.getName());
176         commitCoordinator.commitModification(new MergeModification(ENTITY_OWNERS_PATH, entityOwners), this);
177
178         getSender().tell(SuccessReply.INSTANCE, getSelf());
179     }
180
181     private void onUnregisterCandidateLocal(final UnregisterCandidateLocal unregisterCandidate) {
182         LOG.debug("{}: onUnregisterCandidateLocal: {}", persistenceId(), unregisterCandidate);
183
184         DOMEntity entity = unregisterCandidate.getEntity();
185         listenerSupport.unsetHasCandidateForEntity(entity);
186
187         YangInstanceIdentifier candidatePath = candidatePath(entity.getType(), entity.getIdentifier(),
188                 localMemberName.getName());
189         commitCoordinator.commitModification(new DeleteModification(candidatePath), this);
190
191         getSender().tell(SuccessReply.INSTANCE, getSelf());
192     }
193
194     private void onRegisterListenerLocal(final RegisterListenerLocal registerListener) {
195         LOG.debug("{}: onRegisterListenerLocal: {}", persistenceId(), registerListener);
196
197         listenerSupport.addEntityOwnershipListener(registerListener.getEntityType(), registerListener.getListener());
198
199         getSender().tell(SuccessReply.INSTANCE, getSelf());
200
201         searchForEntities((entityTypeNode, entityNode) -> {
202             Optional<DataContainerChild<?, ?>> possibleType = entityTypeNode.getChild(ENTITY_TYPE_NODE_ID);
203             String entityType = possibleType.isPresent() ? possibleType.get().getValue().toString() : null;
204             if (registerListener.getEntityType().equals(entityType)) {
205                 final boolean hasOwner;
206                 final boolean isOwner;
207
208                 Optional<DataContainerChild<?, ?>> possibleOwner = entityNode.getChild(ENTITY_OWNER_NODE_ID);
209                 if (possibleOwner.isPresent()) {
210                     isOwner = localMemberName.getName().equals(possibleOwner.get().getValue().toString());
211                     hasOwner = true;
212                 } else {
213                     isOwner = false;
214                     hasOwner = false;
215                 }
216
217                 DOMEntity entity = new DOMEntity(entityType,
218                     (YangInstanceIdentifier) entityNode.getChild(ENTITY_ID_NODE_ID).get().getValue());
219
220                 listenerSupport.notifyEntityOwnershipListener(entity, false, isOwner, hasOwner,
221                     registerListener.getListener());
222             }
223         });
224     }
225
226     private void onUnregisterListenerLocal(final UnregisterListenerLocal unregisterListener) {
227         LOG.debug("{}: onUnregisterListenerLocal: {}", persistenceId(), unregisterListener);
228
229         listenerSupport.removeEntityOwnershipListener(unregisterListener.getEntityType(),
230                 unregisterListener.getListener());
231
232         getSender().tell(SuccessReply.INSTANCE, getSelf());
233     }
234
235     void tryCommitModifications(final BatchedModifications modifications) {
236         if (isLeader()) {
237             LOG.debug("{}: Committing BatchedModifications {} locally", persistenceId(),
238                     modifications.getTransactionId());
239
240             // Note that it's possible the commit won't get consensus and will timeout and not be applied
241             // to the state. However we don't need to retry it in that case b/c it will be committed to
242             // the journal first and, once a majority of followers come back on line and it is replicated,
243             // it will be applied at that point.
244             handleBatchedModificationsLocal(modifications, self());
245         } else {
246             final ActorSelection leader = getLeader();
247             if (leader != null) {
248                 possiblyRemoveAllInitialCandidates(leader);
249
250                 LOG.debug("{}: Sending BatchedModifications {} to leader {}", persistenceId(),
251                         modifications.getTransactionId(), leader);
252
253                 Future<Object> future = Patterns.ask(leader, modifications, TimeUnit.SECONDS.toMillis(
254                         getDatastoreContext().getShardTransactionCommitTimeoutInSeconds()));
255
256                 Patterns.pipe(future, getContext().dispatcher()).pipeTo(getSelf(), ActorRef.noSender());
257             }
258         }
259     }
260
261     void possiblyRemoveAllInitialCandidates(final ActorSelection leader) {
262         // The following handles removing all candidates on startup when re-joining with a remote leader. When a
263         // follower is detected as down, the leader will re-assign new owners to entities that were owned by the
264         // down member but doesn't remove the down member as a candidate, as the down node may actually be isolated
265         // and still running. Therefore on startup we send an initial message to the remote leader to remove any
266         // potential stale candidates we had previously registered, as it's possible a candidate may not be
267         // registered by a client in the new incarnation. We have to send the RemoveAllCandidates message prior to any
268         // pending registrations.
269         if (removeAllInitialCandidates && leader != null) {
270             removeAllInitialCandidates = false;
271             if (!isLeader()) {
272                 LOG.debug("{} - got new leader {} on startup - sending RemoveAllCandidates", persistenceId(), leader);
273
274                 leader.tell(new RemoveAllCandidates(localMemberName), ActorRef.noSender());
275             }
276         }
277     }
278
279     boolean hasLeader() {
280         return getLeader() != null && (!isLeader() || isLeaderActive());
281     }
282
283     /**
284      * Determine if we are in jeopardy based on observed RAFT state.
285      */
286     private static boolean inJeopardy(final RaftState state) {
287         switch (state) {
288             case Candidate:
289             case Follower:
290             case Leader:
291             case PreLeader:
292                 return false;
293             case IsolatedLeader:
294                 return true;
295             default:
296                 throw new IllegalStateException("Unsupported RAFT state " + state);
297         }
298     }
299
300     private void notifyAllListeners() {
301         searchForEntities((entityTypeNode, entityNode) -> {
302             Optional<DataContainerChild<?, ?>> possibleType = entityTypeNode.getChild(ENTITY_TYPE_NODE_ID);
303             if (possibleType.isPresent()) {
304                 final boolean hasOwner;
305                 final boolean isOwner;
306
307                 Optional<DataContainerChild<?, ?>> possibleOwner = entityNode.getChild(ENTITY_OWNER_NODE_ID);
308                 if (possibleOwner.isPresent()) {
309                     isOwner = localMemberName.getName().equals(possibleOwner.get().getValue().toString());
310                     hasOwner = true;
311                 } else {
312                     isOwner = false;
313                     hasOwner = false;
314                 }
315
316                 DOMEntity entity = new DOMEntity(possibleType.get().getValue().toString(),
317                     (YangInstanceIdentifier) entityNode.getChild(ENTITY_ID_NODE_ID).get().getValue());
318
319                 listenerSupport.notifyEntityOwnershipListeners(entity, isOwner, isOwner, hasOwner);
320             }
321         });
322     }
323
324     @Override
325     protected void onStateChanged() {
326         boolean isLeader = isLeader();
327         LOG.debug("{}: onStateChanged: isLeader: {}, hasLeader: {}", persistenceId(), isLeader, hasLeader());
328
329         // Examine current RAFT state to see if we are in jeopardy, potentially notifying all listeners
330         final boolean inJeopardy = inJeopardy(getRaftState());
331         final boolean wasInJeopardy = listenerSupport.setInJeopardy(inJeopardy);
332         if (inJeopardy != wasInJeopardy) {
333             LOG.debug("{}: {} jeopardy state, notifying all listeners", persistenceId(),
334                 inJeopardy ? "entered" : "left");
335             notifyAllListeners();
336         }
337
338         commitCoordinator.onStateChanged(this, isLeader);
339
340         super.onStateChanged();
341     }
342
343     @Override
344     protected void onLeaderChanged(final String oldLeader, final String newLeader) {
345         boolean isLeader = isLeader();
346         LOG.debug("{}: onLeaderChanged: oldLeader: {}, newLeader: {}, isLeader: {}", persistenceId(), oldLeader,
347                 newLeader, isLeader);
348
349         if (isLeader) {
350
351             // Re-initialize the downPeerMemberNames from the current akka Cluster state. The previous leader, if any,
352             // is most likely down however it's possible we haven't received the PeerDown message yet.
353             initializeDownPeerMemberNamesFromClusterState();
354
355             // Clear all existing strategies so that they get re-created when we call createStrategy again
356             // This allows the strategies to be re-initialized with existing statistics maintained by
357             // EntityOwnershipStatistics
358             strategyConfig.clearStrategies();
359
360             // Re-assign owners for all members that are known to be down. In a cluster which has greater than
361             // 3 nodes it is possible for some node beside the leader being down when the leadership transitions
362             // it makes sense to use this event to re-assign owners for those downed nodes.
363             Set<String> ownedBy = new HashSet<>(downPeerMemberNames.size() + 1);
364             for (MemberName downPeerName : downPeerMemberNames) {
365                 ownedBy.add(downPeerName.getName());
366             }
367
368             // Also try to assign owners for entities that have no current owner. See explanation in onPeerUp.
369             ownedBy.add("");
370             selectNewOwnerForEntitiesOwnedBy(ownedBy);
371         } else {
372             // The leader changed - notify the coordinator to check if pending modifications need to be sent.
373             // While onStateChanged also does this, this method handles the case where the shard hears from a
374             // leader and stays in the follower state. In that case no behavior state change occurs.
375             commitCoordinator.onStateChanged(this, isLeader);
376         }
377
378         super.onLeaderChanged(oldLeader, newLeader);
379     }
380
381     private void initializeDownPeerMemberNamesFromClusterState() {
382         java.util.Optional<Cluster> cluster = getRaftActorContext().getCluster();
383         if (!cluster.isPresent()) {
384             return;
385         }
386
387         CurrentClusterState state = cluster.get().state();
388         Set<Member> unreachable = state.getUnreachable();
389
390         LOG.debug(
391             "{}: initializeDownPeerMemberNamesFromClusterState - current downPeerMemberNames: {}, unreachable: {}",
392             persistenceId(), downPeerMemberNames, unreachable);
393
394         downPeerMemberNames.clear();
395         for (Member m: unreachable) {
396             downPeerMemberNames.add(MemberName.forName(m.getRoles().iterator().next()));
397         }
398
399         for (Member m: state.getMembers()) {
400             if (m.status() != MemberStatus.up() && m.status() != MemberStatus.weaklyUp()) {
401                 LOG.debug("{}: Adding down member with status {}", persistenceId(), m.status());
402                 downPeerMemberNames.add(MemberName.forName(m.getRoles().iterator().next()));
403             }
404         }
405
406         LOG.debug("{}: new downPeerMemberNames: {}", persistenceId(), downPeerMemberNames);
407     }
408
409     private void onCandidateRemoved(final CandidateRemoved message) {
410         LOG.debug("{}: onCandidateRemoved: {}", persistenceId(), message);
411
412         if (isLeader()) {
413             String currentOwner = getCurrentOwner(message.getEntityPath());
414             writeNewOwner(message.getEntityPath(),
415                     newOwner(currentOwner, message.getRemainingCandidates(),
416                             getEntityOwnerElectionStrategy(message.getEntityPath())));
417         }
418     }
419
420     private EntityOwnerSelectionStrategy getEntityOwnerElectionStrategy(final YangInstanceIdentifier entityPath) {
421         final String entityType = EntityOwnersModel.entityTypeFromEntityPath(entityPath);
422         return strategyConfig.createStrategy(entityType, entityOwnershipStatistics.byEntityType(entityType));
423     }
424
425     private void onCandidateAdded(final CandidateAdded message) {
426         if (!isLeader()) {
427             return;
428         }
429
430         LOG.debug("{}: onCandidateAdded: {}", persistenceId(), message);
431
432         // Since a node's candidate member is only added by the node itself, we can assume the node is up so
433         // remove it from the downPeerMemberNames.
434         downPeerMemberNames.remove(MemberName.forName(message.getNewCandidate()));
435
436         final String currentOwner = getCurrentOwner(message.getEntityPath());
437         final EntityOwnerSelectionStrategy strategy = getEntityOwnerElectionStrategy(message.getEntityPath());
438
439         // Available members is all the known peers - the number of peers that are down + self
440         // So if there are 2 peers and 1 is down then availableMembers will be 2
441         final int availableMembers = getRaftActorContext().getPeerIds().size() - downPeerMemberNames.size() + 1;
442
443         LOG.debug("{}: Using strategy {} to select owner, currentOwner = {}", persistenceId(), strategy, currentOwner);
444
445         if (strategy.getSelectionDelayInMillis() == 0L) {
446             writeNewOwner(message.getEntityPath(), newOwner(currentOwner, message.getAllCandidates(),
447                     strategy));
448         } else if (message.getAllCandidates().size() == availableMembers) {
449             LOG.debug("{}: Received the maximum candidates requests : {} writing new owner",
450                     persistenceId(), availableMembers);
451             cancelOwnerSelectionTask(message.getEntityPath());
452             writeNewOwner(message.getEntityPath(), newOwner(currentOwner, message.getAllCandidates(),
453                     strategy));
454         } else {
455             scheduleOwnerSelection(message.getEntityPath(), message.getAllCandidates(), strategy);
456         }
457     }
458
459     private void onPeerDown(final PeerDown peerDown) {
460         LOG.info("{}: onPeerDown: {}", persistenceId(), peerDown);
461
462         MemberName downMemberName = peerDown.getMemberName();
463         if (downPeerMemberNames.add(downMemberName) && isLeader()) {
464             // Select new owners for entities owned by the down peer and which have other candidates. For an entity for
465             // which the down peer is the only candidate, we leave it as the owner and don't clear it. This is done to
466             // handle the case where the peer member process is actually still running but the node is partitioned.
467             // When the partition is healed, the peer just remains as the owner. If the peer process actually restarted,
468             // it will first remove all its candidates on startup. If another candidate is registered during the time
469             // the peer is down, the new candidate will be selected as the new owner.
470
471             selectNewOwnerForEntitiesOwnedBy(ImmutableSet.of(downMemberName.getName()));
472         }
473     }
474
475     private void selectNewOwnerForEntitiesOwnedBy(final Set<String> ownedBy) {
476         final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
477         searchForEntitiesOwnedBy(ownedBy, (entityTypeNode, entityNode) -> {
478             YangInstanceIdentifier entityPath = YangInstanceIdentifier.builder(ENTITY_TYPES_PATH)
479                     .node(entityTypeNode.getIdentifier()).node(ENTITY_NODE_ID).node(entityNode.getIdentifier())
480                     .node(ENTITY_OWNER_NODE_ID).build();
481             String newOwner = newOwner(getCurrentOwner(entityPath), getCandidateNames(entityNode),
482                     getEntityOwnerElectionStrategy(entityPath));
483
484             if (!newOwner.isEmpty()) {
485                 LOG.debug("{}: Found entity {}, writing new owner {}", persistenceId(), entityPath, newOwner);
486
487                 modifications.addModification(new WriteModification(entityPath,
488                         ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)));
489
490             } else {
491                 LOG.debug("{}: Found entity {} but no other candidates - not clearing owner", persistenceId(),
492                         entityPath, newOwner);
493             }
494         });
495
496         commitCoordinator.commitModifications(modifications, this);
497     }
498
499     private void onPeerUp(final PeerUp peerUp) {
500         LOG.debug("{}: onPeerUp: {}", persistenceId(), peerUp);
501
502         downPeerMemberNames.remove(peerUp.getMemberName());
503
504         // Notify the coordinator to check if pending modifications need to be sent. We do this here
505         // to handle the case where the leader's peer address isn't known yet when a prior state or
506         // leader change occurred.
507         commitCoordinator.onStateChanged(this, isLeader());
508
509         if (isLeader()) {
510             // Try to assign owners for entities that have no current owner. It's possible the peer that is now up
511             // had previously registered as a candidate and was the only candidate but the owner write tx couldn't be
512             // committed due to a leader change. Eg, the leader is able to successfully commit the candidate add tx but
513             // becomes isolated before it can commit the owner change and switches to follower. The majority partition
514             // with a new leader has the candidate but the entity has no owner. When the partition is healed and the
515             // previously isolated leader reconnects, we'll receive onPeerUp and, if there's still no owner, the
516             // previous leader will gain ownership.
517             selectNewOwnerForEntitiesOwnedBy(ImmutableSet.of(""));
518         }
519     }
520
521     private static Collection<String> getCandidateNames(final MapEntryNode entity) {
522         Collection<MapEntryNode> candidates = ((MapNode)entity.getChild(CANDIDATE_NODE_ID).get()).getValue();
523         Collection<String> candidateNames = new ArrayList<>(candidates.size());
524         for (MapEntryNode candidate: candidates) {
525             candidateNames.add(candidate.getChild(CANDIDATE_NAME_NODE_ID).get().getValue().toString());
526         }
527
528         return candidateNames;
529     }
530
531     private void searchForEntitiesOwnedBy(final Set<String> ownedBy, final EntityWalker walker) {
532         LOG.debug("{}: Searching for entities owned by {}", persistenceId(), ownedBy);
533
534         searchForEntities((entityTypeNode, entityNode) -> {
535             Optional<DataContainerChild<? extends PathArgument, ?>> possibleOwner =
536                     entityNode.getChild(ENTITY_OWNER_NODE_ID);
537             String currentOwner = possibleOwner.isPresent() ? possibleOwner.get().getValue().toString() : "";
538             if (ownedBy.contains(currentOwner)) {
539                 walker.onEntity(entityTypeNode, entityNode);
540             }
541         });
542     }
543
544     private void removeCandidateFromEntities(final MemberName member) {
545         final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
546         searchForEntities((entityTypeNode, entityNode) -> {
547             if (hasCandidate(entityNode, member)) {
548                 YangInstanceIdentifier entityId =
549                         (YangInstanceIdentifier) entityNode.getIdentifier().getKeyValues().get(ENTITY_ID_QNAME);
550                 YangInstanceIdentifier candidatePath = candidatePath(
551                         entityTypeNode.getIdentifier().getKeyValues().get(ENTITY_TYPE_QNAME).toString(),
552                         entityId, member.getName());
553
554                 LOG.info("{}: Found entity {}, removing candidate {}, path {}", persistenceId(), entityId,
555                         member, candidatePath);
556
557                 modifications.addModification(new DeleteModification(candidatePath));
558             }
559         });
560
561         commitCoordinator.commitModifications(modifications, this);
562     }
563
564     private static boolean hasCandidate(final MapEntryNode entity, final MemberName candidateName) {
565         return ((MapNode)entity.getChild(CANDIDATE_NODE_ID).get()).getChild(candidateNodeKey(candidateName.getName()))
566                 .isPresent();
567     }
568
569     private void searchForEntities(final EntityWalker walker) {
570         Optional<NormalizedNode<?, ?>> possibleEntityTypes = getDataStore().readNode(ENTITY_TYPES_PATH);
571         if (!possibleEntityTypes.isPresent()) {
572             return;
573         }
574
575         for (MapEntryNode entityType:  ((MapNode) possibleEntityTypes.get()).getValue()) {
576             Optional<DataContainerChild<?, ?>> possibleEntities = entityType.getChild(ENTITY_NODE_ID);
577             if (!possibleEntities.isPresent()) {
578                 // shouldn't happen but handle anyway
579                 continue;
580             }
581
582             for (MapEntryNode entity:  ((MapNode) possibleEntities.get()).getValue()) {
583                 walker.onEntity(entityType, entity);
584             }
585         }
586     }
587
588     private void writeNewOwner(final YangInstanceIdentifier entityPath, final String newOwner) {
589         LOG.debug("{}: Writing new owner {} for entity {}", persistenceId(), newOwner, entityPath);
590
591         commitCoordinator.commitModification(new WriteModification(entityPath.node(ENTITY_OWNER_QNAME),
592                 ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)), this);
593     }
594
595     /**
596      * Schedule a new owner selection job. Cancelling any outstanding job if it has not been cancelled.
597      */
598     private void scheduleOwnerSelection(final YangInstanceIdentifier entityPath, final Collection<String> allCandidates,
599                                        final EntityOwnerSelectionStrategy strategy) {
600         cancelOwnerSelectionTask(entityPath);
601
602         LOG.debug("{}: Scheduling owner selection after {} ms", persistenceId(), strategy.getSelectionDelayInMillis());
603
604         final Cancellable lastScheduledTask = context().system().scheduler().scheduleOnce(
605                 FiniteDuration.apply(strategy.getSelectionDelayInMillis(), TimeUnit.MILLISECONDS), self(),
606                 new SelectOwner(entityPath, allCandidates, strategy), context().system().dispatcher(), self());
607
608         entityToScheduledOwnershipTask.put(entityPath, lastScheduledTask);
609     }
610
611     private void cancelOwnerSelectionTask(final YangInstanceIdentifier entityPath) {
612         final Cancellable lastScheduledTask = entityToScheduledOwnershipTask.get(entityPath);
613         if (lastScheduledTask != null && !lastScheduledTask.isCancelled()) {
614             lastScheduledTask.cancel();
615         }
616     }
617
618     private String newOwner(final String currentOwner, final Collection<String> candidates,
619             final EntityOwnerSelectionStrategy ownerSelectionStrategy) {
620         Collection<String> viableCandidates = getViableCandidates(candidates);
621         if (viableCandidates.isEmpty()) {
622             return "";
623         }
624         return ownerSelectionStrategy.newOwner(currentOwner, viableCandidates);
625     }
626
627     private Collection<String> getViableCandidates(final Collection<String> candidates) {
628         Collection<String> viableCandidates = new ArrayList<>();
629
630         for (String candidate : candidates) {
631             if (!downPeerMemberNames.contains(MemberName.forName(candidate))) {
632                 viableCandidates.add(candidate);
633             }
634         }
635         return viableCandidates;
636     }
637
638     private String getCurrentOwner(final YangInstanceIdentifier entityId) {
639         Optional<NormalizedNode<?, ?>> optionalEntityOwner = getDataStore().readNode(entityId.node(ENTITY_OWNER_QNAME));
640         if (optionalEntityOwner.isPresent()) {
641             return optionalEntityOwner.get().getValue().toString();
642         }
643         return null;
644     }
645
646     @FunctionalInterface
647     private interface EntityWalker {
648         void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode);
649     }
650
651     public static Builder newBuilder() {
652         return new Builder();
653     }
654
655     static class Builder extends Shard.AbstractBuilder<Builder, EntityOwnershipShard> {
656         private MemberName localMemberName;
657         private EntityOwnerSelectionStrategyConfig ownerSelectionStrategyConfig;
658
659         protected Builder() {
660             super(EntityOwnershipShard.class);
661         }
662
663         Builder localMemberName(final MemberName newLocalMemberName) {
664             checkSealed();
665             this.localMemberName = newLocalMemberName;
666             return this;
667         }
668
669         Builder ownerSelectionStrategyConfig(final EntityOwnerSelectionStrategyConfig newOwnerSelectionStrategyConfig) {
670             checkSealed();
671             this.ownerSelectionStrategyConfig = newOwnerSelectionStrategyConfig;
672             return this;
673         }
674
675         @Override
676         protected void verify() {
677             super.verify();
678             Preconditions.checkNotNull(localMemberName, "localMemberName should not be null");
679             Preconditions.checkNotNull(ownerSelectionStrategyConfig, "ownerSelectionStrategyConfig should not be null");
680         }
681     }
682 }