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.Props;
29 import akka.pattern.Patterns;
30 import com.google.common.base.Optional;
31 import com.google.common.base.Strings;
32 import java.util.ArrayList;
33 import java.util.Collection;
34 import java.util.HashMap;
35 import java.util.HashSet;
38 import java.util.concurrent.TimeUnit;
39 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
40 import org.opendaylight.controller.cluster.datastore.Shard;
41 import org.opendaylight.controller.cluster.datastore.entityownership.messages.CandidateAdded;
42 import org.opendaylight.controller.cluster.datastore.entityownership.messages.CandidateRemoved;
43 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterCandidateLocal;
44 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterListenerLocal;
45 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterCandidateLocal;
46 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterListenerLocal;
47 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
48 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
49 import org.opendaylight.controller.cluster.datastore.messages.PeerDown;
50 import org.opendaylight.controller.cluster.datastore.messages.PeerUp;
51 import org.opendaylight.controller.cluster.datastore.messages.SuccessReply;
52 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
53 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
54 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
55 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
56 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
58 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
59 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
62 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
63 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
64 import scala.concurrent.Future;
67 * Special Shard for EntityOwnership.
69 * @author Thomas Pantelis
71 class EntityOwnershipShard extends Shard {
72 private final String localMemberName;
73 private final EntityOwnershipShardCommitCoordinator commitCoordinator;
74 private final EntityOwnershipListenerSupport listenerSupport;
75 private final Set<String> downPeerMemberNames = new HashSet<>();
76 private final Map<String, String> peerIdToMemberNames = new HashMap<>();
78 private static DatastoreContext noPersistenceDatastoreContext(DatastoreContext datastoreContext) {
79 return DatastoreContext.newBuilderFrom(datastoreContext).persistent(false).build();
82 protected EntityOwnershipShard(ShardIdentifier name, Map<String, String> peerAddresses,
83 DatastoreContext datastoreContext, SchemaContext schemaContext, String localMemberName) {
84 super(name, peerAddresses, noPersistenceDatastoreContext(datastoreContext), schemaContext);
85 this.localMemberName = localMemberName;
86 this.commitCoordinator = new EntityOwnershipShardCommitCoordinator(localMemberName, LOG);
87 this.listenerSupport = new EntityOwnershipListenerSupport(getContext(), persistenceId());
89 for(String peerId: peerAddresses.keySet()) {
90 ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(peerId).build();
91 peerIdToMemberNames.put(peerId, shardId.getMemberName());
96 protected void onDatastoreContext(DatastoreContext context) {
97 super.onDatastoreContext(noPersistenceDatastoreContext(context));
101 protected void onRecoveryComplete() {
102 super.onRecoveryComplete();
104 new CandidateListChangeListener(getSelf(), persistenceId()).init(getDataStore());
105 new EntityOwnerChangeListener(localMemberName, listenerSupport).init(getDataStore());
109 public void onReceiveCommand(final Object message) throws Exception {
110 if(message instanceof RegisterCandidateLocal) {
111 onRegisterCandidateLocal((RegisterCandidateLocal)message);
112 } else if(message instanceof UnregisterCandidateLocal) {
113 onUnregisterCandidateLocal((UnregisterCandidateLocal)message);
114 } else if(message instanceof CandidateAdded){
115 onCandidateAdded((CandidateAdded) message);
116 } else if(message instanceof CandidateRemoved){
117 onCandidateRemoved((CandidateRemoved) message);
118 } else if(message instanceof PeerDown) {
119 onPeerDown((PeerDown) message);
120 } else if(message instanceof PeerUp) {
121 onPeerUp((PeerUp) message);
122 } if(message instanceof RegisterListenerLocal) {
123 onRegisterListenerLocal((RegisterListenerLocal)message);
124 } if(message instanceof UnregisterListenerLocal) {
125 onUnregisterListenerLocal((UnregisterListenerLocal)message);
126 } else if(!commitCoordinator.handleMessage(message, this)) {
127 super.onReceiveCommand(message);
131 private void onRegisterCandidateLocal(RegisterCandidateLocal registerCandidate) {
132 LOG.debug("{}: onRegisterCandidateLocal: {}", persistenceId(), registerCandidate);
134 listenerSupport.setHasCandidateForEntity(registerCandidate.getEntity());
136 NormalizedNode<?, ?> entityOwners = entityOwnersWithCandidate(registerCandidate.getEntity().getType(),
137 registerCandidate.getEntity().getId(), localMemberName);
138 commitCoordinator.commitModification(new MergeModification(ENTITY_OWNERS_PATH, entityOwners), this);
140 getSender().tell(SuccessReply.INSTANCE, getSelf());
143 private void onUnregisterCandidateLocal(UnregisterCandidateLocal unregisterCandidate) {
144 LOG.debug("{}: onUnregisterCandidateLocal: {}", persistenceId(), unregisterCandidate);
146 Entity entity = unregisterCandidate.getEntity();
147 listenerSupport.unsetHasCandidateForEntity(entity);
149 YangInstanceIdentifier candidatePath = candidatePath(entity.getType(), entity.getId(), localMemberName);
150 commitCoordinator.commitModification(new DeleteModification(candidatePath), this);
152 getSender().tell(SuccessReply.INSTANCE, getSelf());
155 private void onRegisterListenerLocal(final RegisterListenerLocal registerListener) {
156 LOG.debug("{}: onRegisterListenerLocal: {}", persistenceId(), registerListener);
158 listenerSupport.addEntityOwnershipListener(registerListener.getEntityType(), registerListener.getListener());
160 getSender().tell(SuccessReply.INSTANCE, getSelf());
162 searchForEntitiesOwnedBy(localMemberName, new EntityWalker() {
164 public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
165 Optional<DataContainerChild<? extends PathArgument, ?>> possibleType =
166 entityTypeNode.getChild(ENTITY_TYPE_NODE_ID);
167 String entityType = possibleType.isPresent() ? possibleType.get().getValue().toString() : null;
168 if(registerListener.getEntityType().equals(entityType)) {
169 Entity entity = new Entity(entityType,
170 (YangInstanceIdentifier) entityNode.getChild(ENTITY_ID_NODE_ID).get().getValue());
171 listenerSupport.notifyEntityOwnershipListener(entity, false, true, true, registerListener.getListener());
177 private void onUnregisterListenerLocal(UnregisterListenerLocal unregisterListener) {
178 LOG.debug("{}: onUnregisterListenerLocal: {}", persistenceId(), unregisterListener);
180 listenerSupport.removeEntityOwnershipListener(unregisterListener.getEntityType(), unregisterListener.getListener());
182 getSender().tell(SuccessReply.INSTANCE, getSelf());
185 void tryCommitModifications(final BatchedModifications modifications) {
187 LOG.debug("{}: Committing BatchedModifications {} locally", persistenceId(), modifications.getTransactionID());
189 // Note that it's possible the commit won't get consensus and will timeout and not be applied
190 // to the state. However we don't need to retry it in that case b/c it will be committed to
191 // the journal first and, once a majority of followers come back on line and it is replicated,
192 // it will be applied at that point.
193 handleBatchedModificationsLocal(modifications, self());
195 final ActorSelection leader = getLeader();
196 if (leader != null) {
197 if(LOG.isDebugEnabled()) {
198 LOG.debug("{}: Sending BatchedModifications {} to leader {}", persistenceId(),
199 modifications.getTransactionID(), leader);
202 Future<Object> future = Patterns.ask(leader, modifications, TimeUnit.SECONDS.toMillis(
203 getDatastoreContext().getShardTransactionCommitTimeoutInSeconds()));
205 Patterns.pipe(future, getContext().dispatcher()).pipeTo(getSelf(), ActorRef.noSender());
210 boolean hasLeader() {
211 return getLeader() != null && !isIsolatedLeader();
215 protected void onStateChanged() {
216 super.onStateChanged();
218 commitCoordinator.onStateChanged(this, isLeader());
222 protected void onLeaderChanged(String oldLeader, String newLeader) {
223 super.onLeaderChanged(oldLeader, newLeader);
225 LOG.debug("{}: onLeaderChanged: oldLeader: {}, newLeader: {}, isLeader: {}", persistenceId(), oldLeader,
226 newLeader, isLeader());
229 // We were just elected leader. If the old leader is down, select new owners for the entities
230 // owned by the down leader.
232 String oldLeaderMemberName = peerIdToMemberNames.get(oldLeader);
234 LOG.debug("{}: oldLeaderMemberName: {}", persistenceId(), oldLeaderMemberName);
236 if(downPeerMemberNames.contains(oldLeaderMemberName)) {
237 selectNewOwnerForEntitiesOwnedBy(oldLeaderMemberName);
242 private void onCandidateRemoved(CandidateRemoved message) {
243 LOG.debug("{}: onCandidateRemoved: {}", persistenceId(), message);
246 String currentOwner = getCurrentOwner(message.getEntityPath());
247 if(message.getRemovedCandidate().equals(currentOwner)){
248 writeNewOwner(message.getEntityPath(), newOwner(message.getRemainingCandidates()));
251 // We're not the leader. If the removed candidate is our local member then check if we actually
252 // have a local candidate registered. If we do then we must have been partitioned from the leader
253 // and the leader removed our candidate since the leader can't tell the difference between a
254 // temporary network partition and a node's process actually restarted. So, in that case, re-add
256 if(localMemberName.equals(message.getRemovedCandidate()) &&
257 listenerSupport.hasCandidateForEntity(createEntity(message.getEntityPath()))) {
258 LOG.debug("Local candidate member was removed but a local candidate is registered for {}" +
259 " - adding back local candidate", message.getEntityPath());
261 commitCoordinator.commitModification(new MergeModification(
262 candidatePath(message.getEntityPath(), localMemberName),
263 candidateMapEntry(localMemberName)), this);
268 private void onCandidateAdded(CandidateAdded message) {
273 LOG.debug("{}: onCandidateAdded: {}", persistenceId(), message);
275 // Since a node's candidate member is only added by the node itself, we can assume the node is up so
276 // remove it from the downPeerMemberNames.
277 downPeerMemberNames.remove(message.getNewCandidate());
279 String currentOwner = getCurrentOwner(message.getEntityPath());
280 if(Strings.isNullOrEmpty(currentOwner)){
281 writeNewOwner(message.getEntityPath(), newOwner(message.getAllCandidates()));
285 private void onPeerDown(PeerDown peerDown) {
286 LOG.info("{}: onPeerDown: {}", persistenceId(), peerDown);
288 String downMemberName = peerDown.getMemberName();
289 if(downPeerMemberNames.add(downMemberName) && isLeader()) {
290 // Remove the down peer as a candidate from all entities.
291 removeCandidateFromEntities(downMemberName);
295 private void onPeerUp(PeerUp peerUp) {
296 LOG.debug("{}: onPeerUp: {}", persistenceId(), peerUp);
298 peerIdToMemberNames.put(peerUp.getPeerId(), peerUp.getMemberName());
299 downPeerMemberNames.remove(peerUp.getMemberName());
302 private void selectNewOwnerForEntitiesOwnedBy(String owner) {
303 final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
304 searchForEntitiesOwnedBy(owner, new EntityWalker() {
306 public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
307 Object newOwner = newOwner(getCandidateNames(entityNode));
308 YangInstanceIdentifier entityPath = YangInstanceIdentifier.builder(ENTITY_TYPES_PATH).
309 node(entityTypeNode.getIdentifier()).node(ENTITY_NODE_ID).node(entityNode.getIdentifier()).
310 node(ENTITY_OWNER_NODE_ID).build();
312 LOG.debug("{}: Found entity {}, writing new owner {}", persistenceId(), entityPath, newOwner);
314 modifications.addModification(new WriteModification(entityPath,
315 ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)));
319 commitCoordinator.commitModifications(modifications, this);
322 private void removeCandidateFromEntities(final String owner) {
323 final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
324 searchForEntities(new EntityWalker() {
326 public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
327 if(hasCandidate(entityNode, owner)) {
328 YangInstanceIdentifier entityId =
329 (YangInstanceIdentifier)entityNode.getIdentifier().getKeyValues().get(ENTITY_ID_QNAME);
330 YangInstanceIdentifier candidatePath = candidatePath(
331 entityTypeNode.getIdentifier().getKeyValues().get(ENTITY_TYPE_QNAME).toString(),
334 LOG.info("{}: Found entity {}, removing candidate {}, path {}", persistenceId(), entityId,
335 owner, candidatePath);
337 modifications.addModification(new DeleteModification(candidatePath));
342 commitCoordinator.commitModifications(modifications, this);
345 private static boolean hasCandidate(MapEntryNode entity, String candidateName) {
346 return ((MapNode)entity.getChild(CANDIDATE_NODE_ID).get()).getChild(candidateNodeKey(candidateName)).isPresent();
349 private void searchForEntitiesOwnedBy(final String owner, final EntityWalker walker) {
350 Optional<NormalizedNode<?, ?>> possibleEntityTypes = getDataStore().readNode(ENTITY_TYPES_PATH);
351 if(!possibleEntityTypes.isPresent()) {
355 LOG.debug("{}: Searching for entities owned by {}", persistenceId(), owner);
357 searchForEntities(new EntityWalker() {
359 public void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode) {
360 Optional<DataContainerChild<? extends PathArgument, ?>> possibleOwner =
361 entityNode.getChild(ENTITY_OWNER_NODE_ID);
362 if(possibleOwner.isPresent() && owner.equals(possibleOwner.get().getValue().toString())) {
363 walker.onEntity(entityTypeNode, entityNode);
369 private void searchForEntities(EntityWalker walker) {
370 Optional<NormalizedNode<?, ?>> possibleEntityTypes = getDataStore().readNode(ENTITY_TYPES_PATH);
371 if(!possibleEntityTypes.isPresent()) {
375 for(MapEntryNode entityType: ((MapNode) possibleEntityTypes.get()).getValue()) {
376 Optional<DataContainerChild<? extends PathArgument, ?>> possibleEntities =
377 entityType.getChild(ENTITY_NODE_ID);
378 if(!possibleEntities.isPresent()) {
379 continue; // shouldn't happen but handle anyway
382 for(MapEntryNode entity: ((MapNode) possibleEntities.get()).getValue()) {
383 walker.onEntity(entityType, entity);
388 private static Collection<String> getCandidateNames(MapEntryNode entity) {
389 Collection<MapEntryNode> candidates = ((MapNode)entity.getChild(CANDIDATE_NODE_ID).get()).getValue();
390 Collection<String> candidateNames = new ArrayList<>(candidates.size());
391 for(MapEntryNode candidate: candidates) {
392 candidateNames.add(candidate.getChild(CANDIDATE_NAME_NODE_ID).get().getValue().toString());
395 return candidateNames;
398 private void writeNewOwner(YangInstanceIdentifier entityPath, String newOwner) {
399 LOG.debug("{}: Writing new owner {} for entity {}", persistenceId(), newOwner, entityPath);
401 commitCoordinator.commitModification(new WriteModification(entityPath.node(ENTITY_OWNER_QNAME),
402 ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)), this);
405 private String newOwner(Collection<String> candidates) {
406 for(String candidate: candidates) {
407 if(!downPeerMemberNames.contains(candidate)) {
415 private String getCurrentOwner(YangInstanceIdentifier entityId) {
416 Optional<NormalizedNode<?, ?>> optionalEntityOwner = getDataStore().readNode(entityId.node(ENTITY_OWNER_QNAME));
417 if(optionalEntityOwner.isPresent()){
418 return optionalEntityOwner.get().getValue().toString();
423 public static Props props(final ShardIdentifier name, final Map<String, String> peerAddresses,
424 final DatastoreContext datastoreContext, final SchemaContext schemaContext, final String localMemberName) {
425 return Props.create(new Creator(name, peerAddresses, datastoreContext, schemaContext, localMemberName));
428 private static class Creator extends AbstractShardCreator {
429 private static final long serialVersionUID = 1L;
431 private final String localMemberName;
433 Creator(final ShardIdentifier name, final Map<String, String> peerAddresses,
434 final DatastoreContext datastoreContext, final SchemaContext schemaContext,
435 final String localMemberName) {
436 super(name, peerAddresses, datastoreContext, schemaContext);
437 this.localMemberName = localMemberName;
441 public Shard create() throws Exception {
442 return new EntityOwnershipShard(name, peerAddresses, datastoreContext, schemaContext, localMemberName);
446 private static interface EntityWalker {
447 void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode);