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;
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;
77 * Special Shard for EntityOwnership.
79 * @author Thomas Pantelis
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;
91 protected EntityOwnershipShard(final Builder 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());
101 private static DatastoreContext noPersistenceDatastoreContext(final DatastoreContext datastoreContext) {
102 return DatastoreContext.newBuilderFrom(datastoreContext).persistent(false).build();
106 protected void onDatastoreContext(final DatastoreContext context) {
107 super.onDatastoreContext(noPersistenceDatastoreContext(context));
111 protected void onRecoveryComplete() {
112 super.onRecoveryComplete();
114 new CandidateListChangeListener(getSelf(), persistenceId()).init(getDataStore());
115 new EntityOwnerChangeListener(localMemberName, listenerSupport).init(getDataStore());
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);
145 private void onRemoveAllCandidates(final RemoveAllCandidates message) {
146 LOG.debug("{}: onRemoveAllCandidates: {}", persistenceId(), message);
148 removeCandidateFromEntities(message.getMemberName());
151 private void onSelectOwner(final SelectOwner selectOwner) {
152 LOG.debug("{}: onSelectOwner: {}", persistenceId(), selectOwner);
154 String currentOwner = getCurrentOwner(selectOwner.getEntityPath());
155 if (Strings.isNullOrEmpty(currentOwner)) {
156 writeNewOwner(selectOwner.getEntityPath(), newOwner(currentOwner, selectOwner.getAllCandidates(),
157 selectOwner.getOwnerSelectionStrategy()));
159 Cancellable cancellable = entityToScheduledOwnershipTask.get(selectOwner.getEntityPath());
160 if (cancellable != null) {
161 if (!cancellable.isCancelled()) {
162 cancellable.cancel();
164 entityToScheduledOwnershipTask.remove(selectOwner.getEntityPath());
169 private void onRegisterCandidateLocal(final RegisterCandidateLocal registerCandidate) {
170 LOG.debug("{}: onRegisterCandidateLocal: {}", persistenceId(), registerCandidate);
172 listenerSupport.setHasCandidateForEntity(registerCandidate.getEntity());
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 listenerSupport.unsetHasCandidateForEntity(entity);
187 YangInstanceIdentifier candidatePath = candidatePath(entity.getType(), entity.getIdentifier(),
188 localMemberName.getName());
189 commitCoordinator.commitModification(new DeleteModification(candidatePath), this);
191 getSender().tell(SuccessReply.INSTANCE, getSelf());
194 private void onRegisterListenerLocal(final RegisterListenerLocal registerListener) {
195 LOG.debug("{}: onRegisterListenerLocal: {}", persistenceId(), registerListener);
197 listenerSupport.addEntityOwnershipListener(registerListener.getEntityType(), registerListener.getListener());
199 getSender().tell(SuccessReply.INSTANCE, getSelf());
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;
208 Optional<DataContainerChild<?, ?>> possibleOwner = entityNode.getChild(ENTITY_OWNER_NODE_ID);
209 if (possibleOwner.isPresent()) {
210 isOwner = localMemberName.getName().equals(possibleOwner.get().getValue().toString());
217 DOMEntity entity = new DOMEntity(entityType,
218 (YangInstanceIdentifier) entityNode.getChild(ENTITY_ID_NODE_ID).get().getValue());
220 listenerSupport.notifyEntityOwnershipListener(entity, false, isOwner, hasOwner,
221 registerListener.getListener());
226 private void onUnregisterListenerLocal(final UnregisterListenerLocal unregisterListener) {
227 LOG.debug("{}: onUnregisterListenerLocal: {}", persistenceId(), unregisterListener);
229 listenerSupport.removeEntityOwnershipListener(unregisterListener.getEntityType(),
230 unregisterListener.getListener());
232 getSender().tell(SuccessReply.INSTANCE, getSelf());
235 void tryCommitModifications(final BatchedModifications modifications) {
237 LOG.debug("{}: Committing BatchedModifications {} locally", persistenceId(),
238 modifications.getTransactionId());
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());
246 final ActorSelection leader = getLeader();
247 if (leader != null) {
248 possiblyRemoveAllInitialCandidates(leader);
250 LOG.debug("{}: Sending BatchedModifications {} to leader {}", persistenceId(),
251 modifications.getTransactionId(), leader);
253 Future<Object> future = Patterns.ask(leader, modifications, TimeUnit.SECONDS.toMillis(
254 getDatastoreContext().getShardTransactionCommitTimeoutInSeconds()));
256 Patterns.pipe(future, getContext().dispatcher()).pipeTo(getSelf(), ActorRef.noSender());
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;
272 LOG.debug("{} - got new leader {} on startup - sending RemoveAllCandidates", persistenceId(), leader);
274 leader.tell(new RemoveAllCandidates(localMemberName), ActorRef.noSender());
279 boolean hasLeader() {
280 return getLeader() != null && (!isLeader() || isLeaderActive());
284 * Determine if we are in jeopardy based on observed RAFT state.
286 private static boolean inJeopardy(final RaftState state) {
296 throw new IllegalStateException("Unsupported RAFT state " + state);
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;
307 Optional<DataContainerChild<?, ?>> possibleOwner = entityNode.getChild(ENTITY_OWNER_NODE_ID);
308 if (possibleOwner.isPresent()) {
309 isOwner = localMemberName.getName().equals(possibleOwner.get().getValue().toString());
316 DOMEntity entity = new DOMEntity(possibleType.get().getValue().toString(),
317 (YangInstanceIdentifier) entityNode.getChild(ENTITY_ID_NODE_ID).get().getValue());
319 listenerSupport.notifyEntityOwnershipListeners(entity, isOwner, isOwner, hasOwner);
325 protected void onStateChanged() {
326 boolean isLeader = isLeader();
327 LOG.debug("{}: onStateChanged: isLeader: {}, hasLeader: {}", persistenceId(), isLeader, hasLeader());
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();
338 commitCoordinator.onStateChanged(this, isLeader);
340 super.onStateChanged();
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);
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();
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();
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());
368 // Also try to assign owners for entities that have no current owner. See explanation in onPeerUp.
370 selectNewOwnerForEntitiesOwnedBy(ownedBy);
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);
378 super.onLeaderChanged(oldLeader, newLeader);
381 private void initializeDownPeerMemberNamesFromClusterState() {
382 java.util.Optional<Cluster> cluster = getRaftActorContext().getCluster();
383 if (!cluster.isPresent()) {
387 CurrentClusterState state = cluster.get().state();
388 Set<Member> unreachable = state.getUnreachable();
391 "{}: initializeDownPeerMemberNamesFromClusterState - current downPeerMemberNames: {}, unreachable: {}",
392 persistenceId(), downPeerMemberNames, unreachable);
394 downPeerMemberNames.clear();
395 for (Member m: unreachable) {
396 downPeerMemberNames.add(MemberName.forName(m.getRoles().iterator().next()));
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()));
406 LOG.debug("{}: new downPeerMemberNames: {}", persistenceId(), downPeerMemberNames);
409 private void onCandidateRemoved(final CandidateRemoved message) {
410 LOG.debug("{}: onCandidateRemoved: {}", persistenceId(), message);
413 String currentOwner = getCurrentOwner(message.getEntityPath());
414 writeNewOwner(message.getEntityPath(),
415 newOwner(currentOwner, message.getRemainingCandidates(),
416 getEntityOwnerElectionStrategy(message.getEntityPath())));
420 private EntityOwnerSelectionStrategy getEntityOwnerElectionStrategy(final YangInstanceIdentifier entityPath) {
421 final String entityType = EntityOwnersModel.entityTypeFromEntityPath(entityPath);
422 return strategyConfig.createStrategy(entityType, entityOwnershipStatistics.byEntityType(entityType));
425 private void onCandidateAdded(final CandidateAdded message) {
430 LOG.debug("{}: onCandidateAdded: {}", persistenceId(), message);
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()));
436 final String currentOwner = getCurrentOwner(message.getEntityPath());
437 final EntityOwnerSelectionStrategy strategy = getEntityOwnerElectionStrategy(message.getEntityPath());
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;
443 LOG.debug("{}: Using strategy {} to select owner, currentOwner = {}", persistenceId(), strategy, currentOwner);
445 if (strategy.getSelectionDelayInMillis() == 0L) {
446 writeNewOwner(message.getEntityPath(), newOwner(currentOwner, message.getAllCandidates(),
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(),
455 scheduleOwnerSelection(message.getEntityPath(), message.getAllCandidates(), strategy);
459 private void onPeerDown(final PeerDown peerDown) {
460 LOG.info("{}: onPeerDown: {}", persistenceId(), peerDown);
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.
471 selectNewOwnerForEntitiesOwnedBy(ImmutableSet.of(downMemberName.getName()));
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));
484 if (!newOwner.isEmpty()) {
485 LOG.debug("{}: Found entity {}, writing new owner {}", persistenceId(), entityPath, newOwner);
487 modifications.addModification(new WriteModification(entityPath,
488 ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)));
491 LOG.debug("{}: Found entity {} but no other candidates - not clearing owner", persistenceId(),
492 entityPath, newOwner);
496 commitCoordinator.commitModifications(modifications, this);
499 private void onPeerUp(final PeerUp peerUp) {
500 LOG.debug("{}: onPeerUp: {}", persistenceId(), peerUp);
502 downPeerMemberNames.remove(peerUp.getMemberName());
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());
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(""));
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());
528 return candidateNames;
531 private void searchForEntitiesOwnedBy(final Set<String> ownedBy, final EntityWalker walker) {
532 LOG.debug("{}: Searching for entities owned by {}", persistenceId(), ownedBy);
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);
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());
554 LOG.info("{}: Found entity {}, removing candidate {}, path {}", persistenceId(), entityId,
555 member, candidatePath);
557 modifications.addModification(new DeleteModification(candidatePath));
561 commitCoordinator.commitModifications(modifications, this);
564 private static boolean hasCandidate(final MapEntryNode entity, final MemberName candidateName) {
565 return ((MapNode)entity.getChild(CANDIDATE_NODE_ID).get()).getChild(candidateNodeKey(candidateName.getName()))
569 private void searchForEntities(final EntityWalker walker) {
570 Optional<NormalizedNode<?, ?>> possibleEntityTypes = getDataStore().readNode(ENTITY_TYPES_PATH);
571 if (!possibleEntityTypes.isPresent()) {
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
582 for (MapEntryNode entity: ((MapNode) possibleEntities.get()).getValue()) {
583 walker.onEntity(entityType, entity);
588 private void writeNewOwner(final YangInstanceIdentifier entityPath, final String newOwner) {
589 LOG.debug("{}: Writing new owner {} for entity {}", persistenceId(), newOwner, entityPath);
591 commitCoordinator.commitModification(new WriteModification(entityPath.node(ENTITY_OWNER_QNAME),
592 ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)), this);
596 * Schedule a new owner selection job. Cancelling any outstanding job if it has not been cancelled.
598 private void scheduleOwnerSelection(final YangInstanceIdentifier entityPath, final Collection<String> allCandidates,
599 final EntityOwnerSelectionStrategy strategy) {
600 cancelOwnerSelectionTask(entityPath);
602 LOG.debug("{}: Scheduling owner selection after {} ms", persistenceId(), strategy.getSelectionDelayInMillis());
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());
608 entityToScheduledOwnershipTask.put(entityPath, lastScheduledTask);
611 private void cancelOwnerSelectionTask(final YangInstanceIdentifier entityPath) {
612 final Cancellable lastScheduledTask = entityToScheduledOwnershipTask.get(entityPath);
613 if (lastScheduledTask != null && !lastScheduledTask.isCancelled()) {
614 lastScheduledTask.cancel();
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()) {
624 return ownerSelectionStrategy.newOwner(currentOwner, viableCandidates);
627 private Collection<String> getViableCandidates(final Collection<String> candidates) {
628 Collection<String> viableCandidates = new ArrayList<>();
630 for (String candidate : candidates) {
631 if (!downPeerMemberNames.contains(MemberName.forName(candidate))) {
632 viableCandidates.add(candidate);
635 return viableCandidates;
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();
647 private interface EntityWalker {
648 void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode);
651 public static Builder newBuilder() {
652 return new Builder();
655 static class Builder extends Shard.AbstractBuilder<Builder, EntityOwnershipShard> {
656 private MemberName localMemberName;
657 private EntityOwnerSelectionStrategyConfig ownerSelectionStrategyConfig;
659 protected Builder() {
660 super(EntityOwnershipShard.class);
663 Builder localMemberName(final MemberName newLocalMemberName) {
665 this.localMemberName = newLocalMemberName;
669 Builder ownerSelectionStrategyConfig(final EntityOwnerSelectionStrategyConfig newOwnerSelectionStrategyConfig) {
671 this.ownerSelectionStrategyConfig = newOwnerSelectionStrategyConfig;
676 protected void verify() {
678 Preconditions.checkNotNull(localMemberName, "localMemberName should not be null");
679 Preconditions.checkNotNull(ownerSelectionStrategyConfig, "ownerSelectionStrategyConfig should not be null");