2 * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.cluster.datastore.entityownership;
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;
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;
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;
79 * Special Shard for EntityOwnership.
81 * @author Thomas Pantelis
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;
93 protected EntityOwnershipShard(final Builder 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());
103 private static DatastoreContext noPersistenceDatastoreContext(final DatastoreContext datastoreContext) {
104 return DatastoreContext.newBuilderFrom(datastoreContext).persistent(false).build();
108 protected void onDatastoreContext(final DatastoreContext context) {
109 super.onDatastoreContext(noPersistenceDatastoreContext(context));
113 protected void onRecoveryComplete() {
114 super.onRecoveryComplete();
116 new CandidateListChangeListener(getSelf(), persistenceId()).init(getDataStore());
117 new EntityOwnerChangeListener(localMemberName, listenerSupport).init(getDataStore());
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);
147 private void onRemoveAllCandidates(final RemoveAllCandidates message) {
148 LOG.debug("{}: onRemoveAllCandidates: {}", persistenceId(), message);
150 removeCandidateFromEntities(message.getMemberName());
153 private void onSelectOwner(final SelectOwner selectOwner) {
154 LOG.debug("{}: onSelectOwner: {}", persistenceId(), selectOwner);
156 String currentOwner = getCurrentOwner(selectOwner.getEntityPath());
157 if (Strings.isNullOrEmpty(currentOwner)) {
158 writeNewOwner(selectOwner.getEntityPath(), newOwner(currentOwner, selectOwner.getAllCandidates(),
159 selectOwner.getOwnerSelectionStrategy()));
161 Cancellable cancellable = entityToScheduledOwnershipTask.get(selectOwner.getEntityPath());
162 if (cancellable != null) {
163 if (!cancellable.isCancelled()) {
164 cancellable.cancel();
166 entityToScheduledOwnershipTask.remove(selectOwner.getEntityPath());
171 private void onRegisterCandidateLocal(final RegisterCandidateLocal registerCandidate) {
172 LOG.debug("{}: onRegisterCandidateLocal: {}", persistenceId(), registerCandidate);
174 NormalizedNode<?, ?> entityOwners = entityOwnersWithCandidate(registerCandidate.getEntity().getType(),
175 registerCandidate.getEntity().getIdentifier(), localMemberName.getName());
176 commitCoordinator.commitModification(new MergeModification(ENTITY_OWNERS_PATH, entityOwners), this);
178 getSender().tell(SuccessReply.INSTANCE, getSelf());
181 private void onUnregisterCandidateLocal(final UnregisterCandidateLocal unregisterCandidate) {
182 LOG.debug("{}: onUnregisterCandidateLocal: {}", persistenceId(), unregisterCandidate);
184 DOMEntity entity = unregisterCandidate.getEntity();
185 YangInstanceIdentifier candidatePath = candidatePath(entity.getType(), entity.getIdentifier(),
186 localMemberName.getName());
187 commitCoordinator.commitModification(new DeleteModification(candidatePath), this);
189 getSender().tell(SuccessReply.INSTANCE, getSelf());
192 private void onRegisterListenerLocal(final RegisterListenerLocal registerListener) {
193 LOG.debug("{}: onRegisterListenerLocal: {}", persistenceId(), registerListener);
195 listenerSupport.addEntityOwnershipListener(registerListener.getEntityType(), registerListener.getListener());
197 getSender().tell(SuccessReply.INSTANCE, getSelf());
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;
206 Optional<DataContainerChild<?, ?>> possibleOwner = entityNode.getChild(ENTITY_OWNER_NODE_ID);
207 if (possibleOwner.isPresent()) {
208 isOwner = localMemberName.getName().equals(possibleOwner.get().getValue().toString());
215 DOMEntity entity = new DOMEntity(entityType,
216 (YangInstanceIdentifier) entityNode.getChild(ENTITY_ID_NODE_ID).get().getValue());
218 listenerSupport.notifyEntityOwnershipListener(entity, false, isOwner, hasOwner,
219 registerListener.getListener());
224 private void onUnregisterListenerLocal(final UnregisterListenerLocal unregisterListener) {
225 LOG.debug("{}: onUnregisterListenerLocal: {}", persistenceId(), unregisterListener);
227 listenerSupport.removeEntityOwnershipListener(unregisterListener.getEntityType(),
228 unregisterListener.getListener());
230 getSender().tell(SuccessReply.INSTANCE, getSelf());
233 void tryCommitModifications(final BatchedModifications modifications) {
235 LOG.debug("{}: Committing BatchedModifications {} locally", persistenceId(),
236 modifications.getTransactionId());
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());
244 final ActorSelection leader = getLeader();
245 if (leader != null) {
246 possiblyRemoveAllInitialCandidates(leader);
248 LOG.debug("{}: Sending BatchedModifications {} to leader {}", persistenceId(),
249 modifications.getTransactionId(), leader);
251 Future<Object> future = Patterns.ask(leader, modifications, TimeUnit.SECONDS.toMillis(
252 getDatastoreContext().getShardTransactionCommitTimeoutInSeconds()));
254 Patterns.pipe(future, getContext().dispatcher()).pipeTo(getSelf(), ActorRef.noSender());
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;
270 LOG.debug("{} - got new leader {} on startup - sending RemoveAllCandidates", persistenceId(), leader);
272 leader.tell(new RemoveAllCandidates(localMemberName), ActorRef.noSender());
277 boolean hasLeader() {
278 return getLeader() != null && (!isLeader() || isLeaderActive());
282 * Determine if we are in jeopardy based on observed RAFT state.
284 private static boolean inJeopardy(final RaftState state) {
294 throw new IllegalStateException("Unsupported RAFT state " + state);
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;
305 Optional<DataContainerChild<?, ?>> possibleOwner = entityNode.getChild(ENTITY_OWNER_NODE_ID);
306 if (possibleOwner.isPresent()) {
307 isOwner = localMemberName.getName().equals(possibleOwner.get().getValue().toString());
314 DOMEntity entity = new DOMEntity(possibleType.get().getValue().toString(),
315 (YangInstanceIdentifier) entityNode.getChild(ENTITY_ID_NODE_ID).get().getValue());
317 listenerSupport.notifyEntityOwnershipListeners(entity, isOwner, isOwner, hasOwner);
323 protected void onStateChanged() {
324 boolean isLeader = isLeader();
325 LOG.debug("{}: onStateChanged: isLeader: {}, hasLeader: {}", persistenceId(), isLeader, hasLeader());
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();
336 commitCoordinator.onStateChanged(this, isLeader);
338 super.onStateChanged();
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);
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();
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();
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());
366 // Also try to assign owners for entities that have no current owner. See explanation in onPeerUp.
368 selectNewOwnerForEntitiesOwnedBy(ownedBy);
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);
376 super.onLeaderChanged(oldLeader, newLeader);
379 private void initializeDownPeerMemberNamesFromClusterState() {
380 java.util.Optional<Cluster> cluster = getRaftActorContext().getCluster();
381 if (!cluster.isPresent()) {
385 CurrentClusterState state = cluster.get().state();
386 Set<Member> unreachable = state.getUnreachable();
389 "{}: initializeDownPeerMemberNamesFromClusterState - current downPeerMemberNames: {}, unreachable: {}",
390 persistenceId(), downPeerMemberNames, unreachable);
392 downPeerMemberNames.clear();
393 for (Member m: unreachable) {
394 downPeerMemberNames.add(MemberName.forName(m.getRoles().iterator().next()));
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()));
404 LOG.debug("{}: new downPeerMemberNames: {}", persistenceId(), downPeerMemberNames);
407 private void onCandidateRemoved(final CandidateRemoved message) {
408 LOG.debug("{}: onCandidateRemoved: {}", persistenceId(), message);
411 String currentOwner = getCurrentOwner(message.getEntityPath());
412 writeNewOwner(message.getEntityPath(),
413 newOwner(currentOwner, message.getRemainingCandidates(),
414 getEntityOwnerElectionStrategy(message.getEntityPath())));
418 private EntityOwnerSelectionStrategy getEntityOwnerElectionStrategy(final YangInstanceIdentifier entityPath) {
419 final String entityType = EntityOwnersModel.entityTypeFromEntityPath(entityPath);
420 return strategyConfig.createStrategy(entityType, entityOwnershipStatistics.byEntityType(entityType));
423 private void onCandidateAdded(final CandidateAdded message) {
428 LOG.debug("{}: onCandidateAdded: {}", persistenceId(), message);
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()));
434 final String currentOwner = getCurrentOwner(message.getEntityPath());
435 final EntityOwnerSelectionStrategy strategy = getEntityOwnerElectionStrategy(message.getEntityPath());
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;
441 LOG.debug("{}: Using strategy {} to select owner, currentOwner = {}", persistenceId(), strategy, currentOwner);
443 if (strategy.getSelectionDelayInMillis() == 0L) {
444 writeNewOwner(message.getEntityPath(), newOwner(currentOwner, message.getAllCandidates(),
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(),
453 scheduleOwnerSelection(message.getEntityPath(), message.getAllCandidates(), strategy);
457 private void onPeerDown(final PeerDown peerDown) {
458 LOG.info("{}: onPeerDown: {}", persistenceId(), peerDown);
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.
469 selectNewOwnerForEntitiesOwnedBy(ImmutableSet.of(downMemberName.getName()));
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));
482 if (!newOwner.isEmpty()) {
483 LOG.debug("{}: Found entity {}, writing new owner {}", persistenceId(), entityPath, newOwner);
485 modifications.add(new WriteModification(entityPath,
486 ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)));
489 LOG.debug("{}: Found entity {} but no other candidates - not clearing owner", persistenceId(),
490 entityPath, newOwner);
494 commitCoordinator.commitModifications(modifications, this);
497 private void onPeerUp(final PeerUp peerUp) {
498 LOG.debug("{}: onPeerUp: {}", persistenceId(), peerUp);
500 downPeerMemberNames.remove(peerUp.getMemberName());
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());
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(""));
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());
526 return candidateNames;
529 private void searchForEntitiesOwnedBy(final Set<String> ownedBy, final EntityWalker walker) {
530 LOG.debug("{}: Searching for entities owned by {}", persistenceId(), ownedBy);
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);
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());
552 LOG.info("{}: Found entity {}, removing candidate {}, path {}", persistenceId(), entityId,
553 member, candidatePath);
555 modifications.add(new DeleteModification(candidatePath));
559 commitCoordinator.commitModifications(modifications, this);
562 private static boolean hasCandidate(final MapEntryNode entity, final MemberName candidateName) {
563 return ((MapNode)entity.getChild(CANDIDATE_NODE_ID).get()).getChild(candidateNodeKey(candidateName.getName()))
567 private void searchForEntities(final EntityWalker walker) {
568 Optional<NormalizedNode<?, ?>> possibleEntityTypes = getDataStore().readNode(ENTITY_TYPES_PATH);
569 if (!possibleEntityTypes.isPresent()) {
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
580 for (MapEntryNode entity: ((MapNode) possibleEntities.get()).getValue()) {
581 walker.onEntity(entityType, entity);
586 private void writeNewOwner(final YangInstanceIdentifier entityPath, final String newOwner) {
587 LOG.debug("{}: Writing new owner {} for entity {}", persistenceId(), newOwner, entityPath);
589 commitCoordinator.commitModification(new WriteModification(entityPath.node(ENTITY_OWNER_QNAME),
590 ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)), this);
594 * Schedule a new owner selection job. Cancelling any outstanding job if it has not been cancelled.
596 private void scheduleOwnerSelection(final YangInstanceIdentifier entityPath, final Collection<String> allCandidates,
597 final EntityOwnerSelectionStrategy strategy) {
598 cancelOwnerSelectionTask(entityPath);
600 LOG.debug("{}: Scheduling owner selection after {} ms", persistenceId(), strategy.getSelectionDelayInMillis());
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());
606 entityToScheduledOwnershipTask.put(entityPath, lastScheduledTask);
609 private void cancelOwnerSelectionTask(final YangInstanceIdentifier entityPath) {
610 final Cancellable lastScheduledTask = entityToScheduledOwnershipTask.get(entityPath);
611 if (lastScheduledTask != null && !lastScheduledTask.isCancelled()) {
612 lastScheduledTask.cancel();
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()) {
622 return ownerSelectionStrategy.newOwner(currentOwner, viableCandidates);
625 private Collection<String> getViableCandidates(final Collection<String> candidates) {
626 Collection<String> viableCandidates = new ArrayList<>();
628 for (String candidate : candidates) {
629 if (!downPeerMemberNames.contains(MemberName.forName(candidate))) {
630 viableCandidates.add(candidate);
633 return viableCandidates;
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();
645 private interface EntityWalker {
646 void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode);
649 public static Builder newBuilder() {
650 return new Builder();
653 static class Builder extends Shard.AbstractBuilder<Builder, EntityOwnershipShard> {
654 private MemberName localMemberName;
655 private EntityOwnerSelectionStrategyConfig ownerSelectionStrategyConfig;
657 protected Builder() {
658 super(EntityOwnershipShard.class);
661 Builder localMemberName(final MemberName newLocalMemberName) {
663 this.localMemberName = newLocalMemberName;
667 Builder ownerSelectionStrategyConfig(final EntityOwnerSelectionStrategyConfig newOwnerSelectionStrategyConfig) {
669 this.ownerSelectionStrategyConfig = newOwnerSelectionStrategyConfig;
674 protected void verify() {
676 Preconditions.checkNotNull(localMemberName, "localMemberName should not be null");
677 Preconditions.checkNotNull(ownerSelectionStrategyConfig, "ownerSelectionStrategyConfig should not be null");