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