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.annotations.VisibleForTesting;
31 import com.google.common.base.Optional;
32 import com.google.common.base.Preconditions;
33 import com.google.common.base.Strings;
34 import java.util.ArrayList;
35 import java.util.Collection;
36 import java.util.HashMap;
37 import java.util.HashSet;
40 import java.util.concurrent.TimeUnit;
41 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
42 import org.opendaylight.controller.cluster.datastore.Shard;
43 import org.opendaylight.controller.cluster.datastore.entityownership.messages.CandidateAdded;
44 import org.opendaylight.controller.cluster.datastore.entityownership.messages.CandidateRemoved;
45 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterCandidateLocal;
46 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterListenerLocal;
47 import org.opendaylight.controller.cluster.datastore.entityownership.messages.SelectOwner;
48 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterCandidateLocal;
49 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterListenerLocal;
50 import org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.EntityOwnerSelectionStrategy;
51 import org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.EntityOwnerSelectionStrategyConfig;
52 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
53 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
54 import org.opendaylight.controller.cluster.datastore.messages.PeerDown;
55 import org.opendaylight.controller.cluster.datastore.messages.PeerUp;
56 import org.opendaylight.controller.cluster.datastore.messages.SuccessReply;
57 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
58 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
59 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
60 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
63 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
64 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
67 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
68 import scala.concurrent.Future;
69 import scala.concurrent.duration.FiniteDuration;
72 * Special Shard for EntityOwnership.
74 * @author Thomas Pantelis
76 class EntityOwnershipShard extends Shard {
77 private final String localMemberName;
78 private final EntityOwnershipShardCommitCoordinator commitCoordinator;
79 private final EntityOwnershipListenerSupport listenerSupport;
80 private final Set<String> downPeerMemberNames = new HashSet<>();
81 private final Map<String, String> peerIdToMemberNames = new HashMap<>();
82 private EntityOwnerSelectionStrategyConfig strategyConfig;
83 private Map<YangInstanceIdentifier, Cancellable> entityToScheduledOwnershipTask = new HashMap<>();
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 = EntityOwnerSelectionStrategyConfig.newBuilder().build();
96 for(String peerId: getRaftActorContext().getPeerIds()) {
97 ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(peerId).build();
98 peerIdToMemberNames.put(peerId, shardId.getMemberName());
103 protected void onDatastoreContext(DatastoreContext context) {
104 super.onDatastoreContext(noPersistenceDatastoreContext(context));
108 protected void onRecoveryComplete() {
109 super.onRecoveryComplete();
111 new CandidateListChangeListener(getSelf(), persistenceId()).init(getDataStore());
112 new EntityOwnerChangeListener(localMemberName, listenerSupport).init(getDataStore());
116 public void onReceiveCommand(final Object message) throws Exception {
117 if(message instanceof RegisterCandidateLocal) {
118 onRegisterCandidateLocal((RegisterCandidateLocal) message);
119 } else if(message instanceof UnregisterCandidateLocal) {
120 onUnregisterCandidateLocal((UnregisterCandidateLocal)message);
121 } else if(message instanceof CandidateAdded){
122 onCandidateAdded((CandidateAdded) message);
123 } else if(message instanceof CandidateRemoved){
124 onCandidateRemoved((CandidateRemoved) message);
125 } else if(message instanceof PeerDown) {
126 onPeerDown((PeerDown) message);
127 } else if(message instanceof PeerUp) {
128 onPeerUp((PeerUp) message);
129 } else if(message instanceof RegisterListenerLocal) {
130 onRegisterListenerLocal((RegisterListenerLocal)message);
131 } else if(message instanceof UnregisterListenerLocal) {
132 onUnregisterListenerLocal((UnregisterListenerLocal) message);
133 } else if(message instanceof SelectOwner) {
134 onSelectOwner((SelectOwner) message);
135 } else if(!commitCoordinator.handleMessage(message, this)) {
136 super.onReceiveCommand(message);
140 private void onSelectOwner(SelectOwner selectOwner) {
141 String currentOwner = getCurrentOwner(selectOwner.getEntityPath());
142 if(Strings.isNullOrEmpty(currentOwner)) {
143 writeNewOwner(selectOwner.getEntityPath(), newOwner(selectOwner.getAllCandidates(),
144 selectOwner.getOwnerSelectionStrategy()));
146 Cancellable cancellable = entityToScheduledOwnershipTask.get(selectOwner.getEntityPath());
147 if(cancellable != null){
148 if(!cancellable.isCancelled()){
149 cancellable.cancel();
151 entityToScheduledOwnershipTask.remove(selectOwner.getEntityPath());
156 private void onRegisterCandidateLocal(RegisterCandidateLocal registerCandidate) {
157 LOG.debug("{}: onRegisterCandidateLocal: {}", persistenceId(), registerCandidate);
159 listenerSupport.setHasCandidateForEntity(registerCandidate.getEntity());
161 NormalizedNode<?, ?> entityOwners = entityOwnersWithCandidate(registerCandidate.getEntity().getType(),
162 registerCandidate.getEntity().getId(), localMemberName);
163 commitCoordinator.commitModification(new MergeModification(ENTITY_OWNERS_PATH, entityOwners), this);
165 getSender().tell(SuccessReply.INSTANCE, getSelf());
168 private void onUnregisterCandidateLocal(UnregisterCandidateLocal unregisterCandidate) {
169 LOG.debug("{}: onUnregisterCandidateLocal: {}", persistenceId(), unregisterCandidate);
171 Entity entity = unregisterCandidate.getEntity();
172 listenerSupport.unsetHasCandidateForEntity(entity);
174 YangInstanceIdentifier candidatePath = candidatePath(entity.getType(), entity.getId(), localMemberName);
175 commitCoordinator.commitModification(new DeleteModification(candidatePath), this);
177 getSender().tell(SuccessReply.INSTANCE, getSelf());
180 private void onRegisterListenerLocal(final RegisterListenerLocal registerListener) {
181 LOG.debug("{}: onRegisterListenerLocal: {}", persistenceId(), registerListener);
183 listenerSupport.addEntityOwnershipListener(registerListener.getEntityType(), registerListener.getListener());
185 getSender().tell(SuccessReply.INSTANCE, getSelf());
187 searchForEntitiesOwnedBy(localMemberName, new EntityWalker() {
189 public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
190 Optional<DataContainerChild<? extends PathArgument, ?>> possibleType =
191 entityTypeNode.getChild(ENTITY_TYPE_NODE_ID);
192 String entityType = possibleType.isPresent() ? possibleType.get().getValue().toString() : null;
193 if (registerListener.getEntityType().equals(entityType)) {
194 Entity entity = new Entity(entityType,
195 (YangInstanceIdentifier) entityNode.getChild(ENTITY_ID_NODE_ID).get().getValue());
196 listenerSupport.notifyEntityOwnershipListener(entity, false, true, true, registerListener.getListener());
202 private void onUnregisterListenerLocal(UnregisterListenerLocal unregisterListener) {
203 LOG.debug("{}: onUnregisterListenerLocal: {}", persistenceId(), unregisterListener);
205 listenerSupport.removeEntityOwnershipListener(unregisterListener.getEntityType(), unregisterListener.getListener());
207 getSender().tell(SuccessReply.INSTANCE, getSelf());
210 void tryCommitModifications(final BatchedModifications modifications) {
212 LOG.debug("{}: Committing BatchedModifications {} locally", persistenceId(), modifications.getTransactionID());
214 // Note that it's possible the commit won't get consensus and will timeout and not be applied
215 // to the state. However we don't need to retry it in that case b/c it will be committed to
216 // the journal first and, once a majority of followers come back on line and it is replicated,
217 // it will be applied at that point.
218 handleBatchedModificationsLocal(modifications, self());
220 final ActorSelection leader = getLeader();
221 if (leader != null) {
222 if(LOG.isDebugEnabled()) {
223 LOG.debug("{}: Sending BatchedModifications {} to leader {}", persistenceId(),
224 modifications.getTransactionID(), leader);
227 Future<Object> future = Patterns.ask(leader, modifications, TimeUnit.SECONDS.toMillis(
228 getDatastoreContext().getShardTransactionCommitTimeoutInSeconds()));
230 Patterns.pipe(future, getContext().dispatcher()).pipeTo(getSelf(), ActorRef.noSender());
235 boolean hasLeader() {
236 return getLeader() != null && !isIsolatedLeader();
240 protected void onStateChanged() {
241 super.onStateChanged();
243 commitCoordinator.onStateChanged(this, isLeader());
247 protected void onLeaderChanged(String oldLeader, String newLeader) {
248 super.onLeaderChanged(oldLeader, newLeader);
250 LOG.debug("{}: onLeaderChanged: oldLeader: {}, newLeader: {}, isLeader: {}", persistenceId(), oldLeader,
251 newLeader, isLeader());
254 // We were just elected leader. If the old leader is down, select new owners for the entities
255 // owned by the down leader.
257 String oldLeaderMemberName = peerIdToMemberNames.get(oldLeader);
259 LOG.debug("{}: oldLeaderMemberName: {}", persistenceId(), oldLeaderMemberName);
261 if(downPeerMemberNames.contains(oldLeaderMemberName)) {
262 selectNewOwnerForEntitiesOwnedBy(oldLeaderMemberName);
267 private void onCandidateRemoved(CandidateRemoved message) {
268 LOG.debug("{}: onCandidateRemoved: {}", persistenceId(), message);
271 String currentOwner = getCurrentOwner(message.getEntityPath());
272 if(message.getRemovedCandidate().equals(currentOwner)){
273 writeNewOwner(message.getEntityPath(),
274 newOwner(message.getRemainingCandidates(), getEntityOwnerElectionStrategy(message.getEntityPath())));
277 // We're not the leader. If the removed candidate is our local member then check if we actually
278 // have a local candidate registered. If we do then we must have been partitioned from the leader
279 // and the leader removed our candidate since the leader can't tell the difference between a
280 // temporary network partition and a node's process actually restarted. So, in that case, re-add
282 if(localMemberName.equals(message.getRemovedCandidate()) &&
283 listenerSupport.hasCandidateForEntity(createEntity(message.getEntityPath()))) {
284 LOG.debug("Local candidate member was removed but a local candidate is registered for {}" +
285 " - adding back local candidate", message.getEntityPath());
287 commitCoordinator.commitModification(new MergeModification(
288 candidatePath(message.getEntityPath(), localMemberName),
289 candidateMapEntry(localMemberName)), this);
294 private EntityOwnerSelectionStrategy getEntityOwnerElectionStrategy(YangInstanceIdentifier entityPath) {
295 final String entityType = EntityOwnersModel.entityTypeFromEntityPath(entityPath);
296 return strategyConfig.createStrategy(entityType);
299 private void onCandidateAdded(CandidateAdded message) {
304 LOG.debug("{}: onCandidateAdded: {}", persistenceId(), message);
306 // Since a node's candidate member is only added by the node itself, we can assume the node is up so
307 // remove it from the downPeerMemberNames.
308 downPeerMemberNames.remove(message.getNewCandidate());
310 String currentOwner = getCurrentOwner(message.getEntityPath());
311 EntityOwnerSelectionStrategy strategy = getEntityOwnerElectionStrategy(message.getEntityPath());
312 if(Strings.isNullOrEmpty(currentOwner)){
313 if(strategy.getSelectionDelayInMillis() == 0L) {
314 writeNewOwner(message.getEntityPath(), newOwner(message.getAllCandidates(), strategy));
316 scheduleOwnerSelection(message.getEntityPath(), message.getAllCandidates(), strategy);
321 private void onPeerDown(PeerDown peerDown) {
322 LOG.info("{}: onPeerDown: {}", persistenceId(), peerDown);
324 String downMemberName = peerDown.getMemberName();
325 if(downPeerMemberNames.add(downMemberName) && isLeader()) {
326 // Remove the down peer as a candidate from all entities.
327 removeCandidateFromEntities(downMemberName);
331 private void onPeerUp(PeerUp peerUp) {
332 LOG.debug("{}: onPeerUp: {}", persistenceId(), peerUp);
334 peerIdToMemberNames.put(peerUp.getPeerId(), peerUp.getMemberName());
335 downPeerMemberNames.remove(peerUp.getMemberName());
338 private void selectNewOwnerForEntitiesOwnedBy(String owner) {
339 final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
340 searchForEntitiesOwnedBy(owner, new EntityWalker() {
342 public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
344 YangInstanceIdentifier entityPath = YangInstanceIdentifier.builder(ENTITY_TYPES_PATH).
345 node(entityTypeNode.getIdentifier()).node(ENTITY_NODE_ID).node(entityNode.getIdentifier()).
346 node(ENTITY_OWNER_NODE_ID).build();
348 Object newOwner = newOwner(getCandidateNames(entityNode), getEntityOwnerElectionStrategy(entityPath));
350 LOG.debug("{}: Found entity {}, writing new owner {}", persistenceId(), entityPath, newOwner);
352 modifications.addModification(new WriteModification(entityPath,
353 ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)));
357 commitCoordinator.commitModifications(modifications, this);
360 private void removeCandidateFromEntities(final String owner) {
361 final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
362 searchForEntities(new EntityWalker() {
364 public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
365 if (hasCandidate(entityNode, owner)) {
366 YangInstanceIdentifier entityId =
367 (YangInstanceIdentifier) entityNode.getIdentifier().getKeyValues().get(ENTITY_ID_QNAME);
368 YangInstanceIdentifier candidatePath = candidatePath(
369 entityTypeNode.getIdentifier().getKeyValues().get(ENTITY_TYPE_QNAME).toString(),
372 LOG.info("{}: Found entity {}, removing candidate {}, path {}", persistenceId(), entityId,
373 owner, candidatePath);
375 modifications.addModification(new DeleteModification(candidatePath));
380 commitCoordinator.commitModifications(modifications, this);
383 private static boolean hasCandidate(MapEntryNode entity, String candidateName) {
384 return ((MapNode)entity.getChild(CANDIDATE_NODE_ID).get()).getChild(candidateNodeKey(candidateName)).isPresent();
387 private void searchForEntitiesOwnedBy(final String owner, final EntityWalker walker) {
388 Optional<NormalizedNode<?, ?>> possibleEntityTypes = getDataStore().readNode(ENTITY_TYPES_PATH);
389 if(!possibleEntityTypes.isPresent()) {
393 LOG.debug("{}: Searching for entities owned by {}", persistenceId(), owner);
395 searchForEntities(new EntityWalker() {
397 public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
398 Optional<DataContainerChild<? extends PathArgument, ?>> possibleOwner =
399 entityNode.getChild(ENTITY_OWNER_NODE_ID);
400 if(possibleOwner.isPresent() && owner.equals(possibleOwner.get().getValue().toString())) {
401 walker.onEntity(entityTypeNode, entityNode);
407 private void searchForEntities(EntityWalker walker) {
408 Optional<NormalizedNode<?, ?>> possibleEntityTypes = getDataStore().readNode(ENTITY_TYPES_PATH);
409 if(!possibleEntityTypes.isPresent()) {
413 for(MapEntryNode entityType: ((MapNode) possibleEntityTypes.get()).getValue()) {
414 Optional<DataContainerChild<? extends PathArgument, ?>> possibleEntities =
415 entityType.getChild(ENTITY_NODE_ID);
416 if(!possibleEntities.isPresent()) {
417 continue; // shouldn't happen but handle anyway
420 for(MapEntryNode entity: ((MapNode) possibleEntities.get()).getValue()) {
421 walker.onEntity(entityType, entity);
426 private Collection<String> getCandidateNames(MapEntryNode entity) {
427 Collection<MapEntryNode> candidates = ((MapNode) entity.getChild(CANDIDATE_NODE_ID).get()).getValue();
428 Collection<String> candidateNames = new ArrayList<>(candidates.size());
429 for(MapEntryNode candidate: candidates) {
430 candidateNames.add(candidate.getChild(CANDIDATE_NAME_NODE_ID).get().getValue().toString());
433 return candidateNames;
436 private void writeNewOwner(YangInstanceIdentifier entityPath, String newOwner) {
437 LOG.debug("{}: Writing new owner {} for entity {}", persistenceId(), newOwner, entityPath);
439 commitCoordinator.commitModification(new WriteModification(entityPath.node(ENTITY_OWNER_QNAME),
440 ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)), this);
444 * Schedule a new owner selection job. Cancelling any outstanding job if it has not been cancelled.
447 * @param allCandidates
449 public void scheduleOwnerSelection(YangInstanceIdentifier entityPath, Collection<String> allCandidates,
450 EntityOwnerSelectionStrategy strategy){
451 Cancellable lastScheduledTask = entityToScheduledOwnershipTask.get(entityPath);
452 if(lastScheduledTask != null && !lastScheduledTask.isCancelled()){
453 lastScheduledTask.cancel();
455 lastScheduledTask = context().system().scheduler().scheduleOnce(
456 FiniteDuration.apply(strategy.getSelectionDelayInMillis(), TimeUnit.MILLISECONDS)
457 , self(), new SelectOwner(entityPath, allCandidates, strategy)
458 , context().system().dispatcher(), self());
460 entityToScheduledOwnershipTask.put(entityPath, lastScheduledTask);
463 private String newOwner(Collection<String> candidates, EntityOwnerSelectionStrategy ownerSelectionStrategy) {
464 Collection<String> viableCandidates = getViableCandidates(candidates);
465 if(viableCandidates.size() == 0){
468 return ownerSelectionStrategy.newOwner(viableCandidates);
471 private Collection<String> getViableCandidates(Collection<String> candidates) {
472 Collection<String> viableCandidates = new ArrayList<>();
474 for (String candidate : candidates) {
475 if (!downPeerMemberNames.contains(candidate)) {
476 viableCandidates.add(candidate);
479 return viableCandidates;
482 private String getCurrentOwner(YangInstanceIdentifier entityId) {
483 Optional<NormalizedNode<?, ?>> optionalEntityOwner = getDataStore().readNode(entityId.node(ENTITY_OWNER_QNAME));
484 if(optionalEntityOwner.isPresent()){
485 return optionalEntityOwner.get().getValue().toString();
490 private static interface EntityWalker {
491 void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode);
495 void addEntityOwnerSelectionStrategy(String entityType,
496 Class<? extends EntityOwnerSelectionStrategy> clazz,
498 EntityOwnerSelectionStrategyConfig config = EntityOwnerSelectionStrategyConfig.newBuilder()
499 .addStrategy(entityType, clazz, delay).build();
500 this.strategyConfig = config;
503 public static Builder newBuilder() {
504 return new Builder();
507 static class Builder extends Shard.AbstractBuilder<Builder, EntityOwnershipShard> {
508 private String localMemberName;
510 protected Builder() {
511 super(EntityOwnershipShard.class);
514 Builder localMemberName(String localMemberName) {
516 this.localMemberName = localMemberName;
521 protected void verify() {
523 Preconditions.checkNotNull(localMemberName, "localMemberName should not be null");