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.pattern.Patterns;
29 import com.google.common.annotations.VisibleForTesting;
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.EntityOwnerSelectionStrategyWrapper;
51 import org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.FirstCandidateSelectionStrategy;
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;
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 Map<String, EntityOwnerSelectionStrategyWrapper> ownerSelectionStrategies = new HashMap<>();
82 private final EntityOwnerSelectionStrategyWrapper defaultEntityOwnerSelectionStrategy;
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.defaultEntityOwnerSelectionStrategy =
94 createEntityOwnerSelectionStrategyWrapper(FirstCandidateSelectionStrategy.INSTANCE);
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()));
148 private void onRegisterCandidateLocal(RegisterCandidateLocal registerCandidate) {
149 LOG.debug("{}: onRegisterCandidateLocal: {}", persistenceId(), registerCandidate);
151 listenerSupport.setHasCandidateForEntity(registerCandidate.getEntity());
153 NormalizedNode<?, ?> entityOwners = entityOwnersWithCandidate(registerCandidate.getEntity().getType(),
154 registerCandidate.getEntity().getId(), localMemberName);
155 commitCoordinator.commitModification(new MergeModification(ENTITY_OWNERS_PATH, entityOwners), this);
157 getSender().tell(SuccessReply.INSTANCE, getSelf());
160 private void onUnregisterCandidateLocal(UnregisterCandidateLocal unregisterCandidate) {
161 LOG.debug("{}: onUnregisterCandidateLocal: {}", persistenceId(), unregisterCandidate);
163 Entity entity = unregisterCandidate.getEntity();
164 listenerSupport.unsetHasCandidateForEntity(entity);
166 YangInstanceIdentifier candidatePath = candidatePath(entity.getType(), entity.getId(), localMemberName);
167 commitCoordinator.commitModification(new DeleteModification(candidatePath), this);
169 getSender().tell(SuccessReply.INSTANCE, getSelf());
172 private void onRegisterListenerLocal(final RegisterListenerLocal registerListener) {
173 LOG.debug("{}: onRegisterListenerLocal: {}", persistenceId(), registerListener);
175 listenerSupport.addEntityOwnershipListener(registerListener.getEntityType(), registerListener.getListener());
177 getSender().tell(SuccessReply.INSTANCE, getSelf());
179 searchForEntitiesOwnedBy(localMemberName, new EntityWalker() {
181 public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
182 Optional<DataContainerChild<? extends PathArgument, ?>> possibleType =
183 entityTypeNode.getChild(ENTITY_TYPE_NODE_ID);
184 String entityType = possibleType.isPresent() ? possibleType.get().getValue().toString() : null;
185 if (registerListener.getEntityType().equals(entityType)) {
186 Entity entity = new Entity(entityType,
187 (YangInstanceIdentifier) entityNode.getChild(ENTITY_ID_NODE_ID).get().getValue());
188 listenerSupport.notifyEntityOwnershipListener(entity, false, true, true, registerListener.getListener());
194 private void onUnregisterListenerLocal(UnregisterListenerLocal unregisterListener) {
195 LOG.debug("{}: onUnregisterListenerLocal: {}", persistenceId(), unregisterListener);
197 listenerSupport.removeEntityOwnershipListener(unregisterListener.getEntityType(), unregisterListener.getListener());
199 getSender().tell(SuccessReply.INSTANCE, getSelf());
202 void tryCommitModifications(final BatchedModifications modifications) {
204 LOG.debug("{}: Committing BatchedModifications {} locally", persistenceId(), modifications.getTransactionID());
206 // Note that it's possible the commit won't get consensus and will timeout and not be applied
207 // to the state. However we don't need to retry it in that case b/c it will be committed to
208 // the journal first and, once a majority of followers come back on line and it is replicated,
209 // it will be applied at that point.
210 handleBatchedModificationsLocal(modifications, self());
212 final ActorSelection leader = getLeader();
213 if (leader != null) {
214 if(LOG.isDebugEnabled()) {
215 LOG.debug("{}: Sending BatchedModifications {} to leader {}", persistenceId(),
216 modifications.getTransactionID(), leader);
219 Future<Object> future = Patterns.ask(leader, modifications, TimeUnit.SECONDS.toMillis(
220 getDatastoreContext().getShardTransactionCommitTimeoutInSeconds()));
222 Patterns.pipe(future, getContext().dispatcher()).pipeTo(getSelf(), ActorRef.noSender());
227 boolean hasLeader() {
228 return getLeader() != null && !isIsolatedLeader();
232 protected void onStateChanged() {
233 super.onStateChanged();
235 commitCoordinator.onStateChanged(this, isLeader());
239 protected void onLeaderChanged(String oldLeader, String newLeader) {
240 super.onLeaderChanged(oldLeader, newLeader);
242 LOG.debug("{}: onLeaderChanged: oldLeader: {}, newLeader: {}, isLeader: {}", persistenceId(), oldLeader,
243 newLeader, isLeader());
246 // We were just elected leader. If the old leader is down, select new owners for the entities
247 // owned by the down leader.
249 String oldLeaderMemberName = peerIdToMemberNames.get(oldLeader);
251 LOG.debug("{}: oldLeaderMemberName: {}", persistenceId(), oldLeaderMemberName);
253 if(downPeerMemberNames.contains(oldLeaderMemberName)) {
254 selectNewOwnerForEntitiesOwnedBy(oldLeaderMemberName);
259 private void onCandidateRemoved(CandidateRemoved message) {
260 LOG.debug("{}: onCandidateRemoved: {}", persistenceId(), message);
263 String currentOwner = getCurrentOwner(message.getEntityPath());
264 if(message.getRemovedCandidate().equals(currentOwner)){
265 writeNewOwner(message.getEntityPath(),
266 newOwner(message.getRemainingCandidates(), getEntityOwnerElectionStrategyWrapper(message.getEntityPath())));
269 // We're not the leader. If the removed candidate is our local member then check if we actually
270 // have a local candidate registered. If we do then we must have been partitioned from the leader
271 // and the leader removed our candidate since the leader can't tell the difference between a
272 // temporary network partition and a node's process actually restarted. So, in that case, re-add
274 if(localMemberName.equals(message.getRemovedCandidate()) &&
275 listenerSupport.hasCandidateForEntity(createEntity(message.getEntityPath()))) {
276 LOG.debug("Local candidate member was removed but a local candidate is registered for {}" +
277 " - adding back local candidate", message.getEntityPath());
279 commitCoordinator.commitModification(new MergeModification(
280 candidatePath(message.getEntityPath(), localMemberName),
281 candidateMapEntry(localMemberName)), this);
286 private EntityOwnerSelectionStrategyWrapper getEntityOwnerElectionStrategyWrapper(YangInstanceIdentifier entityPath) {
287 String entityType = EntityOwnersModel.entityTypeFromEntityPath(entityPath);
288 EntityOwnerSelectionStrategyWrapper entityOwnerSelectionStrategy = ownerSelectionStrategies.get(entityType);
290 if(entityOwnerSelectionStrategy == null){
291 entityOwnerSelectionStrategy = defaultEntityOwnerSelectionStrategy;
292 ownerSelectionStrategies.put(entityType, entityOwnerSelectionStrategy);
295 return entityOwnerSelectionStrategy;
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 if(Strings.isNullOrEmpty(currentOwner)){
311 EntityOwnerSelectionStrategyWrapper strategy = getEntityOwnerElectionStrategyWrapper(message.getEntityPath());
312 if(strategy.selectionDelayInMillis() == 0L) {
313 writeNewOwner(message.getEntityPath(), newOwner(message.getAllCandidates(), strategy));
315 strategy.scheduleOwnerSelection(message.getEntityPath(), message.getAllCandidates());
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), getEntityOwnerElectionStrategyWrapper(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 static 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);
442 private String newOwner(Collection<String> candidates, EntityOwnerSelectionStrategy ownerSelectionStrategy) {
443 Collection<String> viableCandidates = getViableCandidates(candidates);
444 if(viableCandidates.size() == 0){
447 return ownerSelectionStrategy.newOwner(viableCandidates);
450 private Collection<String> getViableCandidates(Collection<String> candidates) {
451 Collection<String> viableCandidates = new ArrayList<>();
453 for (String candidate : candidates) {
454 if (!downPeerMemberNames.contains(candidate)) {
455 viableCandidates.add(candidate);
458 return viableCandidates;
461 private String getCurrentOwner(YangInstanceIdentifier entityId) {
462 Optional<NormalizedNode<?, ?>> optionalEntityOwner = getDataStore().readNode(entityId.node(ENTITY_OWNER_QNAME));
463 if(optionalEntityOwner.isPresent()){
464 return optionalEntityOwner.get().getValue().toString();
469 private static interface EntityWalker {
470 void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode);
473 private EntityOwnerSelectionStrategyWrapper createEntityOwnerSelectionStrategyWrapper(EntityOwnerSelectionStrategy entityOwnerSelectionStrategy){
474 return new EntityOwnerSelectionStrategyWrapper(context().system().scheduler(), self(),
475 context().system().dispatcher(), entityOwnerSelectionStrategy);
479 void addEntityOwnerSelectionStrategy(String entityType, Class<? extends EntityOwnerSelectionStrategy> ownerSelectionStrategyClass){
481 EntityOwnerSelectionStrategyWrapper strategy =
482 createEntityOwnerSelectionStrategyWrapper(ownerSelectionStrategyClass.newInstance());
483 ownerSelectionStrategies.put(entityType, strategy);
484 } catch (InstantiationException | IllegalAccessException e) {
485 LOG.error("Exception occurred when adding election strategy", e);
489 public static Builder newBuilder() {
490 return new Builder();
493 static class Builder extends Shard.AbstractBuilder<Builder, EntityOwnershipShard> {
494 private String localMemberName;
496 protected Builder() {
497 super(EntityOwnershipShard.class);
500 Builder localMemberName(String localMemberName) {
502 this.localMemberName = localMemberName;
507 protected void verify() {
509 Preconditions.checkNotNull(localMemberName, "localMemberName should not be null");