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.candidateMapEntry;
22 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.candidateNodeKey;
23 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.candidatePath;
24 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.createEntity;
25 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityOwnersWithCandidate;
26 import akka.actor.ActorRef;
27 import akka.actor.ActorSelection;
28 import akka.actor.Cancellable;
29 import akka.pattern.Patterns;
30 import com.google.common.base.Optional;
31 import com.google.common.base.Preconditions;
32 import com.google.common.base.Strings;
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.HashMap;
36 import java.util.HashSet;
39 import java.util.concurrent.TimeUnit;
40 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
41 import org.opendaylight.controller.cluster.datastore.Shard;
42 import org.opendaylight.controller.cluster.datastore.entityownership.messages.CandidateAdded;
43 import org.opendaylight.controller.cluster.datastore.entityownership.messages.CandidateRemoved;
44 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterCandidateLocal;
45 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterListenerLocal;
46 import org.opendaylight.controller.cluster.datastore.entityownership.messages.SelectOwner;
47 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterCandidateLocal;
48 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterListenerLocal;
49 import org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.EntityOwnerSelectionStrategy;
50 import org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.EntityOwnerSelectionStrategyConfig;
51 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
52 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
53 import org.opendaylight.controller.cluster.datastore.messages.PeerDown;
54 import org.opendaylight.controller.cluster.datastore.messages.PeerUp;
55 import org.opendaylight.controller.cluster.datastore.messages.SuccessReply;
56 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
57 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
58 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
59 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
62 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
63 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
64 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
66 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
67 import scala.concurrent.Future;
68 import scala.concurrent.duration.FiniteDuration;
71 * Special Shard for EntityOwnership.
73 * @author Thomas Pantelis
75 class EntityOwnershipShard extends Shard {
76 private final String localMemberName;
77 private final EntityOwnershipShardCommitCoordinator commitCoordinator;
78 private final EntityOwnershipListenerSupport listenerSupport;
79 private final Set<String> downPeerMemberNames = new HashSet<>();
80 private final Map<String, String> peerIdToMemberNames = new HashMap<>();
81 private final EntityOwnerSelectionStrategyConfig strategyConfig;
82 private final Map<YangInstanceIdentifier, Cancellable> entityToScheduledOwnershipTask = new HashMap<>();
84 private static DatastoreContext noPersistenceDatastoreContext(DatastoreContext datastoreContext) {
85 return DatastoreContext.newBuilderFrom(datastoreContext).persistent(false).build();
88 protected EntityOwnershipShard(Builder builder) {
90 this.localMemberName = builder.localMemberName;
91 this.commitCoordinator = new EntityOwnershipShardCommitCoordinator(builder.localMemberName, LOG);
92 this.listenerSupport = new EntityOwnershipListenerSupport(getContext(), persistenceId());
93 this.strategyConfig = builder.ownerSelectionStrategyConfig;
95 for(String peerId: getRaftActorContext().getPeerIds()) {
96 ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(peerId).build();
97 peerIdToMemberNames.put(peerId, shardId.getMemberName());
102 protected void onDatastoreContext(DatastoreContext context) {
103 super.onDatastoreContext(noPersistenceDatastoreContext(context));
107 protected void onRecoveryComplete() {
108 super.onRecoveryComplete();
110 new CandidateListChangeListener(getSelf(), persistenceId()).init(getDataStore());
111 new EntityOwnerChangeListener(localMemberName, listenerSupport).init(getDataStore());
115 public void onReceiveCommand(final Object message) throws Exception {
116 if(message instanceof RegisterCandidateLocal) {
117 onRegisterCandidateLocal((RegisterCandidateLocal) message);
118 } else if(message instanceof UnregisterCandidateLocal) {
119 onUnregisterCandidateLocal((UnregisterCandidateLocal)message);
120 } else if(message instanceof CandidateAdded){
121 onCandidateAdded((CandidateAdded) message);
122 } else if(message instanceof CandidateRemoved){
123 onCandidateRemoved((CandidateRemoved) message);
124 } else if(message instanceof PeerDown) {
125 onPeerDown((PeerDown) message);
126 } else if(message instanceof PeerUp) {
127 onPeerUp((PeerUp) message);
128 } else if(message instanceof RegisterListenerLocal) {
129 onRegisterListenerLocal((RegisterListenerLocal)message);
130 } else if(message instanceof UnregisterListenerLocal) {
131 onUnregisterListenerLocal((UnregisterListenerLocal) message);
132 } else if(message instanceof SelectOwner) {
133 onSelectOwner((SelectOwner) message);
134 } else if(!commitCoordinator.handleMessage(message, this)) {
135 super.onReceiveCommand(message);
139 private void onSelectOwner(SelectOwner selectOwner) {
140 String currentOwner = getCurrentOwner(selectOwner.getEntityPath());
141 if(Strings.isNullOrEmpty(currentOwner)) {
142 writeNewOwner(selectOwner.getEntityPath(), newOwner(selectOwner.getAllCandidates(),
143 selectOwner.getOwnerSelectionStrategy()));
145 Cancellable cancellable = entityToScheduledOwnershipTask.get(selectOwner.getEntityPath());
146 if(cancellable != null){
147 if(!cancellable.isCancelled()){
148 cancellable.cancel();
150 entityToScheduledOwnershipTask.remove(selectOwner.getEntityPath());
155 private void onRegisterCandidateLocal(RegisterCandidateLocal registerCandidate) {
156 LOG.debug("{}: onRegisterCandidateLocal: {}", persistenceId(), registerCandidate);
158 listenerSupport.setHasCandidateForEntity(registerCandidate.getEntity());
160 NormalizedNode<?, ?> entityOwners = entityOwnersWithCandidate(registerCandidate.getEntity().getType(),
161 registerCandidate.getEntity().getId(), localMemberName);
162 commitCoordinator.commitModification(new MergeModification(ENTITY_OWNERS_PATH, entityOwners), this);
164 getSender().tell(SuccessReply.INSTANCE, getSelf());
167 private void onUnregisterCandidateLocal(UnregisterCandidateLocal unregisterCandidate) {
168 LOG.debug("{}: onUnregisterCandidateLocal: {}", persistenceId(), unregisterCandidate);
170 Entity entity = unregisterCandidate.getEntity();
171 listenerSupport.unsetHasCandidateForEntity(entity);
173 YangInstanceIdentifier candidatePath = candidatePath(entity.getType(), entity.getId(), localMemberName);
174 commitCoordinator.commitModification(new DeleteModification(candidatePath), this);
176 getSender().tell(SuccessReply.INSTANCE, getSelf());
179 private void onRegisterListenerLocal(final RegisterListenerLocal registerListener) {
180 LOG.debug("{}: onRegisterListenerLocal: {}", persistenceId(), registerListener);
182 listenerSupport.addEntityOwnershipListener(registerListener.getEntityType(), registerListener.getListener());
184 getSender().tell(SuccessReply.INSTANCE, getSelf());
186 searchForEntitiesOwnedBy(localMemberName, new EntityWalker() {
188 public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
189 Optional<DataContainerChild<? extends PathArgument, ?>> possibleType =
190 entityTypeNode.getChild(ENTITY_TYPE_NODE_ID);
191 String entityType = possibleType.isPresent() ? possibleType.get().getValue().toString() : null;
192 if (registerListener.getEntityType().equals(entityType)) {
193 Entity entity = new Entity(entityType,
194 (YangInstanceIdentifier) entityNode.getChild(ENTITY_ID_NODE_ID).get().getValue());
195 listenerSupport.notifyEntityOwnershipListener(entity, false, true, true, registerListener.getListener());
201 private void onUnregisterListenerLocal(UnregisterListenerLocal unregisterListener) {
202 LOG.debug("{}: onUnregisterListenerLocal: {}", persistenceId(), unregisterListener);
204 listenerSupport.removeEntityOwnershipListener(unregisterListener.getEntityType(), unregisterListener.getListener());
206 getSender().tell(SuccessReply.INSTANCE, getSelf());
209 void tryCommitModifications(final BatchedModifications modifications) {
211 LOG.debug("{}: Committing BatchedModifications {} locally", persistenceId(), modifications.getTransactionID());
213 // Note that it's possible the commit won't get consensus and will timeout and not be applied
214 // to the state. However we don't need to retry it in that case b/c it will be committed to
215 // the journal first and, once a majority of followers come back on line and it is replicated,
216 // it will be applied at that point.
217 handleBatchedModificationsLocal(modifications, self());
219 final ActorSelection leader = getLeader();
220 if (leader != null) {
221 if(LOG.isDebugEnabled()) {
222 LOG.debug("{}: Sending BatchedModifications {} to leader {}", persistenceId(),
223 modifications.getTransactionID(), leader);
226 Future<Object> future = Patterns.ask(leader, modifications, TimeUnit.SECONDS.toMillis(
227 getDatastoreContext().getShardTransactionCommitTimeoutInSeconds()));
229 Patterns.pipe(future, getContext().dispatcher()).pipeTo(getSelf(), ActorRef.noSender());
234 boolean hasLeader() {
235 return getLeader() != null && !isIsolatedLeader();
239 protected void onStateChanged() {
240 super.onStateChanged();
242 commitCoordinator.onStateChanged(this, isLeader());
246 protected void onLeaderChanged(String oldLeader, String newLeader) {
247 super.onLeaderChanged(oldLeader, newLeader);
249 LOG.debug("{}: onLeaderChanged: oldLeader: {}, newLeader: {}, isLeader: {}", persistenceId(), oldLeader,
250 newLeader, isLeader());
253 // We were just elected leader. If the old leader is down, select new owners for the entities
254 // owned by the down leader.
256 String oldLeaderMemberName = peerIdToMemberNames.get(oldLeader);
258 LOG.debug("{}: oldLeaderMemberName: {}", persistenceId(), oldLeaderMemberName);
260 if(downPeerMemberNames.contains(oldLeaderMemberName)) {
261 selectNewOwnerForEntitiesOwnedBy(oldLeaderMemberName);
266 private void onCandidateRemoved(CandidateRemoved message) {
267 LOG.debug("{}: onCandidateRemoved: {}", persistenceId(), message);
270 String currentOwner = getCurrentOwner(message.getEntityPath());
271 if(message.getRemovedCandidate().equals(currentOwner)){
272 writeNewOwner(message.getEntityPath(),
273 newOwner(message.getRemainingCandidates(), getEntityOwnerElectionStrategy(message.getEntityPath())));
276 // We're not the leader. If the removed candidate is our local member then check if we actually
277 // have a local candidate registered. If we do then we must have been partitioned from the leader
278 // and the leader removed our candidate since the leader can't tell the difference between a
279 // temporary network partition and a node's process actually restarted. So, in that case, re-add
281 if(localMemberName.equals(message.getRemovedCandidate()) &&
282 listenerSupport.hasCandidateForEntity(createEntity(message.getEntityPath()))) {
283 LOG.debug("Local candidate member was removed but a local candidate is registered for {}" +
284 " - adding back local candidate", message.getEntityPath());
286 commitCoordinator.commitModification(new MergeModification(
287 candidatePath(message.getEntityPath(), localMemberName),
288 candidateMapEntry(localMemberName)), this);
293 private EntityOwnerSelectionStrategy getEntityOwnerElectionStrategy(YangInstanceIdentifier entityPath) {
294 final String entityType = EntityOwnersModel.entityTypeFromEntityPath(entityPath);
295 return strategyConfig.createStrategy(entityType);
298 private void onCandidateAdded(CandidateAdded message) {
303 LOG.debug("{}: onCandidateAdded: {}", persistenceId(), message);
305 // Since a node's candidate member is only added by the node itself, we can assume the node is up so
306 // remove it from the downPeerMemberNames.
307 downPeerMemberNames.remove(message.getNewCandidate());
309 String currentOwner = getCurrentOwner(message.getEntityPath());
310 EntityOwnerSelectionStrategy strategy = getEntityOwnerElectionStrategy(message.getEntityPath());
311 if(Strings.isNullOrEmpty(currentOwner)){
312 if(strategy.getSelectionDelayInMillis() == 0L) {
313 writeNewOwner(message.getEntityPath(), newOwner(message.getAllCandidates(), strategy));
315 scheduleOwnerSelection(message.getEntityPath(), message.getAllCandidates(), strategy);
320 private void onPeerDown(PeerDown peerDown) {
321 LOG.info("{}: onPeerDown: {}", persistenceId(), peerDown);
323 String downMemberName = peerDown.getMemberName();
324 if(downPeerMemberNames.add(downMemberName) && isLeader()) {
325 // Remove the down peer as a candidate from all entities.
326 removeCandidateFromEntities(downMemberName);
330 private void onPeerUp(PeerUp peerUp) {
331 LOG.debug("{}: onPeerUp: {}", persistenceId(), peerUp);
333 peerIdToMemberNames.put(peerUp.getPeerId(), peerUp.getMemberName());
334 downPeerMemberNames.remove(peerUp.getMemberName());
337 private void selectNewOwnerForEntitiesOwnedBy(String owner) {
338 final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
339 searchForEntitiesOwnedBy(owner, new EntityWalker() {
341 public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
343 YangInstanceIdentifier entityPath = YangInstanceIdentifier.builder(ENTITY_TYPES_PATH).
344 node(entityTypeNode.getIdentifier()).node(ENTITY_NODE_ID).node(entityNode.getIdentifier()).
345 node(ENTITY_OWNER_NODE_ID).build();
347 Object newOwner = newOwner(getCandidateNames(entityNode), getEntityOwnerElectionStrategy(entityPath));
349 LOG.debug("{}: Found entity {}, writing new owner {}", persistenceId(), entityPath, newOwner);
351 modifications.addModification(new WriteModification(entityPath,
352 ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)));
356 commitCoordinator.commitModifications(modifications, this);
359 private void removeCandidateFromEntities(final String owner) {
360 final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
361 searchForEntities(new EntityWalker() {
363 public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
364 if (hasCandidate(entityNode, owner)) {
365 YangInstanceIdentifier entityId =
366 (YangInstanceIdentifier) entityNode.getIdentifier().getKeyValues().get(ENTITY_ID_QNAME);
367 YangInstanceIdentifier candidatePath = candidatePath(
368 entityTypeNode.getIdentifier().getKeyValues().get(ENTITY_TYPE_QNAME).toString(),
371 LOG.info("{}: Found entity {}, removing candidate {}, path {}", persistenceId(), entityId,
372 owner, candidatePath);
374 modifications.addModification(new DeleteModification(candidatePath));
379 commitCoordinator.commitModifications(modifications, this);
382 private static boolean hasCandidate(MapEntryNode entity, String candidateName) {
383 return ((MapNode)entity.getChild(CANDIDATE_NODE_ID).get()).getChild(candidateNodeKey(candidateName)).isPresent();
386 private void searchForEntitiesOwnedBy(final String owner, final EntityWalker walker) {
387 Optional<NormalizedNode<?, ?>> possibleEntityTypes = getDataStore().readNode(ENTITY_TYPES_PATH);
388 if(!possibleEntityTypes.isPresent()) {
392 LOG.debug("{}: Searching for entities owned by {}", persistenceId(), owner);
394 searchForEntities(new EntityWalker() {
396 public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
397 Optional<DataContainerChild<? extends PathArgument, ?>> possibleOwner =
398 entityNode.getChild(ENTITY_OWNER_NODE_ID);
399 if (possibleOwner.isPresent() && owner.equals(possibleOwner.get().getValue().toString())) {
400 walker.onEntity(entityTypeNode, entityNode);
406 private void searchForEntities(EntityWalker walker) {
407 Optional<NormalizedNode<?, ?>> possibleEntityTypes = getDataStore().readNode(ENTITY_TYPES_PATH);
408 if(!possibleEntityTypes.isPresent()) {
412 for(MapEntryNode entityType: ((MapNode) possibleEntityTypes.get()).getValue()) {
413 Optional<DataContainerChild<? extends PathArgument, ?>> possibleEntities =
414 entityType.getChild(ENTITY_NODE_ID);
415 if(!possibleEntities.isPresent()) {
416 continue; // shouldn't happen but handle anyway
419 for(MapEntryNode entity: ((MapNode) possibleEntities.get()).getValue()) {
420 walker.onEntity(entityType, entity);
425 private Collection<String> getCandidateNames(MapEntryNode entity) {
426 Collection<MapEntryNode> candidates = ((MapNode) entity.getChild(CANDIDATE_NODE_ID).get()).getValue();
427 Collection<String> candidateNames = new ArrayList<>(candidates.size());
428 for(MapEntryNode candidate: candidates) {
429 candidateNames.add(candidate.getChild(CANDIDATE_NAME_NODE_ID).get().getValue().toString());
432 return candidateNames;
435 private void writeNewOwner(YangInstanceIdentifier entityPath, String newOwner) {
436 LOG.debug("{}: Writing new owner {} for entity {}", persistenceId(), newOwner, entityPath);
438 commitCoordinator.commitModification(new WriteModification(entityPath.node(ENTITY_OWNER_QNAME),
439 ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)), this);
443 * Schedule a new owner selection job. Cancelling any outstanding job if it has not been cancelled.
446 * @param allCandidates
448 public void scheduleOwnerSelection(YangInstanceIdentifier entityPath, Collection<String> allCandidates,
449 EntityOwnerSelectionStrategy strategy){
450 Cancellable lastScheduledTask = entityToScheduledOwnershipTask.get(entityPath);
451 if(lastScheduledTask != null && !lastScheduledTask.isCancelled()){
452 lastScheduledTask.cancel();
454 lastScheduledTask = context().system().scheduler().scheduleOnce(
455 FiniteDuration.apply(strategy.getSelectionDelayInMillis(), TimeUnit.MILLISECONDS)
456 , self(), new SelectOwner(entityPath, allCandidates, strategy)
457 , context().system().dispatcher(), self());
459 entityToScheduledOwnershipTask.put(entityPath, lastScheduledTask);
462 private String newOwner(Collection<String> candidates, EntityOwnerSelectionStrategy ownerSelectionStrategy) {
463 Collection<String> viableCandidates = getViableCandidates(candidates);
464 if(viableCandidates.size() == 0){
467 return ownerSelectionStrategy.newOwner(viableCandidates);
470 private Collection<String> getViableCandidates(Collection<String> candidates) {
471 Collection<String> viableCandidates = new ArrayList<>();
473 for (String candidate : candidates) {
474 if (!downPeerMemberNames.contains(candidate)) {
475 viableCandidates.add(candidate);
478 return viableCandidates;
481 private String getCurrentOwner(YangInstanceIdentifier entityId) {
482 Optional<NormalizedNode<?, ?>> optionalEntityOwner = getDataStore().readNode(entityId.node(ENTITY_OWNER_QNAME));
483 if(optionalEntityOwner.isPresent()){
484 return optionalEntityOwner.get().getValue().toString();
489 private static interface EntityWalker {
490 void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode);
493 public static Builder newBuilder() {
494 return new Builder();
497 static class Builder extends Shard.AbstractBuilder<Builder, EntityOwnershipShard> {
498 private String localMemberName;
499 private EntityOwnerSelectionStrategyConfig ownerSelectionStrategyConfig;
501 protected Builder() {
502 super(EntityOwnershipShard.class);
505 Builder localMemberName(String localMemberName) {
507 this.localMemberName = localMemberName;
511 Builder ownerSelectionStrategyConfig(EntityOwnerSelectionStrategyConfig ownerSelectionStrategyConfig){
513 this.ownerSelectionStrategyConfig = ownerSelectionStrategyConfig;
518 protected void verify() {
520 Preconditions.checkNotNull(localMemberName, "localMemberName should not be null");
521 Preconditions.checkNotNull(ownerSelectionStrategyConfig, "ownerSelectionStrategyConfig should not be null");