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<>();
83 private final EntityOwnershipStatistics entityOwnershipStatistics;
85 private static DatastoreContext noPersistenceDatastoreContext(DatastoreContext datastoreContext) {
86 return DatastoreContext.newBuilderFrom(datastoreContext).persistent(false).build();
89 protected EntityOwnershipShard(Builder builder) {
91 this.localMemberName = builder.localMemberName;
92 this.commitCoordinator = new EntityOwnershipShardCommitCoordinator(builder.localMemberName, LOG);
93 this.listenerSupport = new EntityOwnershipListenerSupport(getContext(), persistenceId());
94 this.strategyConfig = builder.ownerSelectionStrategyConfig;
95 this.entityOwnershipStatistics = new EntityOwnershipStatistics();
96 this.entityOwnershipStatistics.init(getDataStore());
98 for(String peerId: getRaftActorContext().getPeerIds()) {
99 ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(peerId).build();
100 peerIdToMemberNames.put(peerId, shardId.getMemberName());
105 protected void onDatastoreContext(DatastoreContext context) {
106 super.onDatastoreContext(noPersistenceDatastoreContext(context));
110 protected void onRecoveryComplete() {
111 super.onRecoveryComplete();
113 new CandidateListChangeListener(getSelf(), persistenceId()).init(getDataStore());
114 new EntityOwnerChangeListener(localMemberName, listenerSupport).init(getDataStore());
118 public void onReceiveCommand(final Object message) throws Exception {
119 if(message instanceof RegisterCandidateLocal) {
120 onRegisterCandidateLocal((RegisterCandidateLocal) message);
121 } else if(message instanceof UnregisterCandidateLocal) {
122 onUnregisterCandidateLocal((UnregisterCandidateLocal)message);
123 } else if(message instanceof CandidateAdded){
124 onCandidateAdded((CandidateAdded) message);
125 } else if(message instanceof CandidateRemoved){
126 onCandidateRemoved((CandidateRemoved) message);
127 } else if(message instanceof PeerDown) {
128 onPeerDown((PeerDown) message);
129 } else if(message instanceof PeerUp) {
130 onPeerUp((PeerUp) message);
131 } else if(message instanceof RegisterListenerLocal) {
132 onRegisterListenerLocal((RegisterListenerLocal)message);
133 } else if(message instanceof UnregisterListenerLocal) {
134 onUnregisterListenerLocal((UnregisterListenerLocal) message);
135 } else if(message instanceof SelectOwner) {
136 onSelectOwner((SelectOwner) message);
137 } else if(!commitCoordinator.handleMessage(message, this)) {
138 super.onReceiveCommand(message);
142 private void onSelectOwner(SelectOwner selectOwner) {
143 String currentOwner = getCurrentOwner(selectOwner.getEntityPath());
144 if(Strings.isNullOrEmpty(currentOwner)) {
145 writeNewOwner(selectOwner.getEntityPath(), newOwner(selectOwner.getAllCandidates(),
146 selectOwner.getOwnerSelectionStrategy()));
148 Cancellable cancellable = entityToScheduledOwnershipTask.get(selectOwner.getEntityPath());
149 if(cancellable != null){
150 if(!cancellable.isCancelled()){
151 cancellable.cancel();
153 entityToScheduledOwnershipTask.remove(selectOwner.getEntityPath());
158 private void onRegisterCandidateLocal(RegisterCandidateLocal registerCandidate) {
159 LOG.debug("{}: onRegisterCandidateLocal: {}", persistenceId(), registerCandidate);
161 listenerSupport.setHasCandidateForEntity(registerCandidate.getEntity());
163 NormalizedNode<?, ?> entityOwners = entityOwnersWithCandidate(registerCandidate.getEntity().getType(),
164 registerCandidate.getEntity().getId(), localMemberName);
165 commitCoordinator.commitModification(new MergeModification(ENTITY_OWNERS_PATH, entityOwners), this);
167 getSender().tell(SuccessReply.INSTANCE, getSelf());
170 private void onUnregisterCandidateLocal(UnregisterCandidateLocal unregisterCandidate) {
171 LOG.debug("{}: onUnregisterCandidateLocal: {}", persistenceId(), unregisterCandidate);
173 Entity entity = unregisterCandidate.getEntity();
174 listenerSupport.unsetHasCandidateForEntity(entity);
176 YangInstanceIdentifier candidatePath = candidatePath(entity.getType(), entity.getId(), localMemberName);
177 commitCoordinator.commitModification(new DeleteModification(candidatePath), this);
179 getSender().tell(SuccessReply.INSTANCE, getSelf());
182 private void onRegisterListenerLocal(final RegisterListenerLocal registerListener) {
183 LOG.debug("{}: onRegisterListenerLocal: {}", persistenceId(), registerListener);
185 listenerSupport.addEntityOwnershipListener(registerListener.getEntityType(), registerListener.getListener());
187 getSender().tell(SuccessReply.INSTANCE, getSelf());
189 searchForEntitiesOwnedBy(localMemberName, new EntityWalker() {
191 public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
192 Optional<DataContainerChild<? extends PathArgument, ?>> possibleType =
193 entityTypeNode.getChild(ENTITY_TYPE_NODE_ID);
194 String entityType = possibleType.isPresent() ? possibleType.get().getValue().toString() : null;
195 if (registerListener.getEntityType().equals(entityType)) {
196 Entity entity = new Entity(entityType,
197 (YangInstanceIdentifier) entityNode.getChild(ENTITY_ID_NODE_ID).get().getValue());
198 listenerSupport.notifyEntityOwnershipListener(entity, false, true, true, registerListener.getListener());
204 private void onUnregisterListenerLocal(UnregisterListenerLocal unregisterListener) {
205 LOG.debug("{}: onUnregisterListenerLocal: {}", persistenceId(), unregisterListener);
207 listenerSupport.removeEntityOwnershipListener(unregisterListener.getEntityType(), unregisterListener.getListener());
209 getSender().tell(SuccessReply.INSTANCE, getSelf());
212 void tryCommitModifications(final BatchedModifications modifications) {
214 LOG.debug("{}: Committing BatchedModifications {} locally", persistenceId(), modifications.getTransactionID());
216 // Note that it's possible the commit won't get consensus and will timeout and not be applied
217 // to the state. However we don't need to retry it in that case b/c it will be committed to
218 // the journal first and, once a majority of followers come back on line and it is replicated,
219 // it will be applied at that point.
220 handleBatchedModificationsLocal(modifications, self());
222 final ActorSelection leader = getLeader();
223 if (leader != null) {
224 if(LOG.isDebugEnabled()) {
225 LOG.debug("{}: Sending BatchedModifications {} to leader {}", persistenceId(),
226 modifications.getTransactionID(), leader);
229 Future<Object> future = Patterns.ask(leader, modifications, TimeUnit.SECONDS.toMillis(
230 getDatastoreContext().getShardTransactionCommitTimeoutInSeconds()));
232 Patterns.pipe(future, getContext().dispatcher()).pipeTo(getSelf(), ActorRef.noSender());
237 boolean hasLeader() {
238 return getLeader() != null && !isIsolatedLeader();
242 protected void onStateChanged() {
243 super.onStateChanged();
245 commitCoordinator.onStateChanged(this, isLeader());
249 protected void onLeaderChanged(String oldLeader, String newLeader) {
250 super.onLeaderChanged(oldLeader, newLeader);
252 LOG.debug("{}: onLeaderChanged: oldLeader: {}, newLeader: {}, isLeader: {}", persistenceId(), oldLeader,
253 newLeader, isLeader());
256 // We were just elected leader. If the old leader is down, select new owners for the entities
257 // owned by the down leader.
259 String oldLeaderMemberName = peerIdToMemberNames.get(oldLeader);
261 LOG.debug("{}: oldLeaderMemberName: {}", persistenceId(), oldLeaderMemberName);
263 if(downPeerMemberNames.contains(oldLeaderMemberName)) {
264 selectNewOwnerForEntitiesOwnedBy(oldLeaderMemberName);
269 private void onCandidateRemoved(CandidateRemoved message) {
270 LOG.debug("{}: onCandidateRemoved: {}", persistenceId(), message);
273 String currentOwner = getCurrentOwner(message.getEntityPath());
274 if(message.getRemovedCandidate().equals(currentOwner)){
275 writeNewOwner(message.getEntityPath(),
276 newOwner(message.getRemainingCandidates(), getEntityOwnerElectionStrategy(message.getEntityPath())));
279 // We're not the leader. If the removed candidate is our local member then check if we actually
280 // have a local candidate registered. If we do then we must have been partitioned from the leader
281 // and the leader removed our candidate since the leader can't tell the difference between a
282 // temporary network partition and a node's process actually restarted. So, in that case, re-add
284 if(localMemberName.equals(message.getRemovedCandidate()) &&
285 listenerSupport.hasCandidateForEntity(createEntity(message.getEntityPath()))) {
286 LOG.debug("Local candidate member was removed but a local candidate is registered for {}" +
287 " - adding back local candidate", message.getEntityPath());
289 commitCoordinator.commitModification(new MergeModification(
290 candidatePath(message.getEntityPath(), localMemberName),
291 candidateMapEntry(localMemberName)), this);
296 private EntityOwnerSelectionStrategy getEntityOwnerElectionStrategy(YangInstanceIdentifier entityPath) {
297 final String entityType = EntityOwnersModel.entityTypeFromEntityPath(entityPath);
298 return strategyConfig.createStrategy(entityType);
301 private void onCandidateAdded(CandidateAdded message) {
306 LOG.debug("{}: onCandidateAdded: {}", persistenceId(), message);
308 // Since a node's candidate member is only added by the node itself, we can assume the node is up so
309 // remove it from the downPeerMemberNames.
310 downPeerMemberNames.remove(message.getNewCandidate());
312 String currentOwner = getCurrentOwner(message.getEntityPath());
313 EntityOwnerSelectionStrategy strategy = getEntityOwnerElectionStrategy(message.getEntityPath());
314 if(Strings.isNullOrEmpty(currentOwner)){
315 if(strategy.getSelectionDelayInMillis() == 0L) {
316 writeNewOwner(message.getEntityPath(), newOwner(message.getAllCandidates(), strategy));
318 scheduleOwnerSelection(message.getEntityPath(), message.getAllCandidates(), strategy);
323 private void onPeerDown(PeerDown peerDown) {
324 LOG.info("{}: onPeerDown: {}", persistenceId(), peerDown);
326 String downMemberName = peerDown.getMemberName();
327 if(downPeerMemberNames.add(downMemberName) && isLeader()) {
328 // Remove the down peer as a candidate from all entities.
329 removeCandidateFromEntities(downMemberName);
333 private void onPeerUp(PeerUp peerUp) {
334 LOG.debug("{}: onPeerUp: {}", persistenceId(), peerUp);
336 peerIdToMemberNames.put(peerUp.getPeerId(), peerUp.getMemberName());
337 downPeerMemberNames.remove(peerUp.getMemberName());
340 private void selectNewOwnerForEntitiesOwnedBy(String owner) {
341 final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
342 searchForEntitiesOwnedBy(owner, new EntityWalker() {
344 public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
346 YangInstanceIdentifier entityPath = YangInstanceIdentifier.builder(ENTITY_TYPES_PATH).
347 node(entityTypeNode.getIdentifier()).node(ENTITY_NODE_ID).node(entityNode.getIdentifier()).
348 node(ENTITY_OWNER_NODE_ID).build();
350 Object newOwner = newOwner(getCandidateNames(entityNode), getEntityOwnerElectionStrategy(entityPath));
352 LOG.debug("{}: Found entity {}, writing new owner {}", persistenceId(), entityPath, newOwner);
354 modifications.addModification(new WriteModification(entityPath,
355 ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)));
359 commitCoordinator.commitModifications(modifications, this);
362 private void removeCandidateFromEntities(final String owner) {
363 final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
364 searchForEntities(new EntityWalker() {
366 public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
367 if (hasCandidate(entityNode, owner)) {
368 YangInstanceIdentifier entityId =
369 (YangInstanceIdentifier) entityNode.getIdentifier().getKeyValues().get(ENTITY_ID_QNAME);
370 YangInstanceIdentifier candidatePath = candidatePath(
371 entityTypeNode.getIdentifier().getKeyValues().get(ENTITY_TYPE_QNAME).toString(),
374 LOG.info("{}: Found entity {}, removing candidate {}, path {}", persistenceId(), entityId,
375 owner, candidatePath);
377 modifications.addModification(new DeleteModification(candidatePath));
382 commitCoordinator.commitModifications(modifications, this);
385 private static boolean hasCandidate(MapEntryNode entity, String candidateName) {
386 return ((MapNode)entity.getChild(CANDIDATE_NODE_ID).get()).getChild(candidateNodeKey(candidateName)).isPresent();
389 private void searchForEntitiesOwnedBy(final String owner, final EntityWalker walker) {
390 Optional<NormalizedNode<?, ?>> possibleEntityTypes = getDataStore().readNode(ENTITY_TYPES_PATH);
391 if(!possibleEntityTypes.isPresent()) {
395 LOG.debug("{}: Searching for entities owned by {}", persistenceId(), owner);
397 searchForEntities(new EntityWalker() {
399 public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
400 Optional<DataContainerChild<? extends PathArgument, ?>> possibleOwner =
401 entityNode.getChild(ENTITY_OWNER_NODE_ID);
402 if (possibleOwner.isPresent() && owner.equals(possibleOwner.get().getValue().toString())) {
403 walker.onEntity(entityTypeNode, entityNode);
409 private void searchForEntities(EntityWalker walker) {
410 Optional<NormalizedNode<?, ?>> possibleEntityTypes = getDataStore().readNode(ENTITY_TYPES_PATH);
411 if(!possibleEntityTypes.isPresent()) {
415 for(MapEntryNode entityType: ((MapNode) possibleEntityTypes.get()).getValue()) {
416 Optional<DataContainerChild<? extends PathArgument, ?>> possibleEntities =
417 entityType.getChild(ENTITY_NODE_ID);
418 if(!possibleEntities.isPresent()) {
419 continue; // shouldn't happen but handle anyway
422 for(MapEntryNode entity: ((MapNode) possibleEntities.get()).getValue()) {
423 walker.onEntity(entityType, entity);
428 private Collection<String> getCandidateNames(MapEntryNode entity) {
429 Collection<MapEntryNode> candidates = ((MapNode) entity.getChild(CANDIDATE_NODE_ID).get()).getValue();
430 Collection<String> candidateNames = new ArrayList<>(candidates.size());
431 for(MapEntryNode candidate: candidates) {
432 candidateNames.add(candidate.getChild(CANDIDATE_NAME_NODE_ID).get().getValue().toString());
435 return candidateNames;
438 private void writeNewOwner(YangInstanceIdentifier entityPath, String newOwner) {
439 LOG.debug("{}: Writing new owner {} for entity {}", persistenceId(), newOwner, entityPath);
441 commitCoordinator.commitModification(new WriteModification(entityPath.node(ENTITY_OWNER_QNAME),
442 ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)), this);
446 * Schedule a new owner selection job. Cancelling any outstanding job if it has not been cancelled.
449 * @param allCandidates
451 public void scheduleOwnerSelection(YangInstanceIdentifier entityPath, Collection<String> allCandidates,
452 EntityOwnerSelectionStrategy strategy){
453 Cancellable lastScheduledTask = entityToScheduledOwnershipTask.get(entityPath);
454 if(lastScheduledTask != null && !lastScheduledTask.isCancelled()){
455 lastScheduledTask.cancel();
457 lastScheduledTask = context().system().scheduler().scheduleOnce(
458 FiniteDuration.apply(strategy.getSelectionDelayInMillis(), TimeUnit.MILLISECONDS)
459 , self(), new SelectOwner(entityPath, allCandidates, strategy)
460 , context().system().dispatcher(), self());
462 entityToScheduledOwnershipTask.put(entityPath, lastScheduledTask);
465 private String newOwner(Collection<String> candidates, EntityOwnerSelectionStrategy ownerSelectionStrategy) {
466 Collection<String> viableCandidates = getViableCandidates(candidates);
467 if(viableCandidates.size() == 0){
470 return ownerSelectionStrategy.newOwner(viableCandidates);
473 private Collection<String> getViableCandidates(Collection<String> candidates) {
474 Collection<String> viableCandidates = new ArrayList<>();
476 for (String candidate : candidates) {
477 if (!downPeerMemberNames.contains(candidate)) {
478 viableCandidates.add(candidate);
481 return viableCandidates;
484 private String getCurrentOwner(YangInstanceIdentifier entityId) {
485 Optional<NormalizedNode<?, ?>> optionalEntityOwner = getDataStore().readNode(entityId.node(ENTITY_OWNER_QNAME));
486 if(optionalEntityOwner.isPresent()){
487 return optionalEntityOwner.get().getValue().toString();
492 private static interface EntityWalker {
493 void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode);
496 public static Builder newBuilder() {
497 return new Builder();
500 static class Builder extends Shard.AbstractBuilder<Builder, EntityOwnershipShard> {
501 private String localMemberName;
502 private EntityOwnerSelectionStrategyConfig ownerSelectionStrategyConfig;
504 protected Builder() {
505 super(EntityOwnershipShard.class);
508 Builder localMemberName(String localMemberName) {
510 this.localMemberName = localMemberName;
514 Builder ownerSelectionStrategyConfig(EntityOwnerSelectionStrategyConfig ownerSelectionStrategyConfig){
516 this.ownerSelectionStrategyConfig = ownerSelectionStrategyConfig;
521 protected void verify() {
523 Preconditions.checkNotNull(localMemberName, "localMemberName should not be null");
524 Preconditions.checkNotNull(ownerSelectionStrategyConfig, "ownerSelectionStrategyConfig should not be null");