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_NODE_ID;
13 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_OWNERS_PATH;
14 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_OWNER_NODE_ID;
15 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_OWNER_QNAME;
16 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.ENTITY_TYPES_PATH;
17 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.candidatePath;
18 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityOwnersWithCandidate;
19 import akka.actor.ActorRef;
20 import akka.actor.ActorSelection;
21 import akka.actor.Props;
22 import akka.pattern.Patterns;
23 import com.google.common.base.Optional;
24 import com.google.common.base.Strings;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.HashMap;
28 import java.util.HashSet;
31 import java.util.concurrent.TimeUnit;
32 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
33 import org.opendaylight.controller.cluster.datastore.Shard;
34 import org.opendaylight.controller.cluster.datastore.entityownership.messages.CandidateAdded;
35 import org.opendaylight.controller.cluster.datastore.entityownership.messages.CandidateRemoved;
36 import org.opendaylight.controller.cluster.datastore.entityownership.messages.RegisterCandidateLocal;
37 import org.opendaylight.controller.cluster.datastore.entityownership.messages.UnregisterCandidateLocal;
38 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
39 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
40 import org.opendaylight.controller.cluster.datastore.messages.PeerDown;
41 import org.opendaylight.controller.cluster.datastore.messages.PeerUp;
42 import org.opendaylight.controller.cluster.datastore.messages.SuccessReply;
43 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
44 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
45 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
46 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
49 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
50 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
54 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
55 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
56 import scala.concurrent.Future;
59 * Special Shard for EntityOwnership.
61 * @author Thomas Pantelis
63 class EntityOwnershipShard extends Shard {
64 private final String localMemberName;
65 private final EntityOwnershipShardCommitCoordinator commitCoordinator;
66 private final EntityOwnershipListenerSupport listenerSupport;
67 private final Set<String> downPeerMemberNames = new HashSet<>();
68 private final Map<String, String> peerIdToMemberNames = new HashMap<>();
70 private static DatastoreContext noPersistenceDatastoreContext(DatastoreContext datastoreContext) {
71 return DatastoreContext.newBuilderFrom(datastoreContext).persistent(false).build();
74 protected EntityOwnershipShard(ShardIdentifier name, Map<String, String> peerAddresses,
75 DatastoreContext datastoreContext, SchemaContext schemaContext, String localMemberName) {
76 super(name, peerAddresses, noPersistenceDatastoreContext(datastoreContext), schemaContext);
77 this.localMemberName = localMemberName;
78 this.commitCoordinator = new EntityOwnershipShardCommitCoordinator(localMemberName, LOG);
79 this.listenerSupport = new EntityOwnershipListenerSupport(getContext());
81 for(String peerId: peerAddresses.keySet()) {
82 ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(peerId).build();
83 peerIdToMemberNames.put(peerId, shardId.getMemberName());
88 protected void onDatastoreContext(DatastoreContext context) {
89 super.onDatastoreContext(noPersistenceDatastoreContext(context));
93 protected void onRecoveryComplete() {
94 super.onRecoveryComplete();
96 new CandidateListChangeListener(getSelf()).init(getDataStore());
97 new EntityOwnerChangeListener(localMemberName, listenerSupport).init(getDataStore());
101 public void onReceiveCommand(final Object message) throws Exception {
102 if(message instanceof RegisterCandidateLocal) {
103 onRegisterCandidateLocal((RegisterCandidateLocal)message);
104 } else if(message instanceof UnregisterCandidateLocal) {
105 onUnregisterCandidateLocal((UnregisterCandidateLocal)message);
106 } else if(message instanceof CandidateAdded){
107 onCandidateAdded((CandidateAdded) message);
108 } else if(message instanceof CandidateRemoved){
109 onCandidateRemoved((CandidateRemoved) message);
110 } else if(message instanceof PeerDown) {
111 onPeerDown((PeerDown) message);
112 } else if(message instanceof PeerUp) {
113 onPeerUp((PeerUp) message);
114 } else if(!commitCoordinator.handleMessage(message, this)) {
115 super.onReceiveCommand(message);
119 private void onRegisterCandidateLocal(RegisterCandidateLocal registerCandidate) {
120 LOG.debug("{}: onRegisterCandidateLocal: {}", persistenceId(), registerCandidate);
122 listenerSupport.addEntityOwnershipListener(registerCandidate.getEntity(), registerCandidate.getCandidate());
124 NormalizedNode<?, ?> entityOwners = entityOwnersWithCandidate(registerCandidate.getEntity().getType(),
125 registerCandidate.getEntity().getId(), localMemberName);
126 commitCoordinator.commitModification(new MergeModification(ENTITY_OWNERS_PATH, entityOwners), this);
128 getSender().tell(SuccessReply.INSTANCE, getSelf());
131 private void onUnregisterCandidateLocal(UnregisterCandidateLocal unregisterCandidate) {
132 LOG.debug("{}: onUnregisterCandidateLocal: {}", persistenceId(), unregisterCandidate);
134 Entity entity = unregisterCandidate.getEntity();
135 listenerSupport.removeEntityOwnershipListener(entity, unregisterCandidate.getCandidate());
137 YangInstanceIdentifier candidatePath = candidatePath(entity.getType(), entity.getId(), localMemberName);
138 commitCoordinator.commitModification(new DeleteModification(candidatePath), this);
140 getSender().tell(SuccessReply.INSTANCE, getSelf());
143 void tryCommitModifications(final BatchedModifications modifications) {
145 LOG.debug("{}: Committing BatchedModifications {} locally", persistenceId(), modifications.getTransactionID());
147 // Note that it's possible the commit won't get consensus and will timeout and not be applied
148 // to the state. However we don't need to retry it in that case b/c it will be committed to
149 // the journal first and, once a majority of followers come back on line and it is replicated,
150 // it will be applied at that point.
151 handleBatchedModificationsLocal(modifications, self());
153 final ActorSelection leader = getLeader();
154 if (leader != null) {
155 if(LOG.isDebugEnabled()) {
156 LOG.debug("{}: Sending BatchedModifications {} to leader {}", persistenceId(),
157 modifications.getTransactionID(), leader);
160 Future<Object> future = Patterns.ask(leader, modifications, TimeUnit.SECONDS.toMillis(
161 getDatastoreContext().getShardTransactionCommitTimeoutInSeconds()));
163 Patterns.pipe(future, getContext().dispatcher()).pipeTo(getSelf(), ActorRef.noSender());
168 boolean hasLeader() {
169 return getLeader() != null && !isIsolatedLeader();
173 protected void onStateChanged() {
174 super.onStateChanged();
176 commitCoordinator.onStateChanged(this, isLeader());
180 protected void onLeaderChanged(String oldLeader, String newLeader) {
181 super.onLeaderChanged(oldLeader, newLeader);
183 LOG.debug("{}: onLeaderChanged: oldLeader: {}, newLeader: {}, isLeader: {}", persistenceId(), oldLeader,
184 newLeader, isLeader());
187 // We were just elected leader. If the old leader is down, select new owners for the entities
188 // owned by the down leader.
190 String oldLeaderMemberName = peerIdToMemberNames.get(oldLeader);
192 LOG.debug("{}: oldLeaderMemberName: {}", persistenceId(), oldLeaderMemberName);
194 if(downPeerMemberNames.contains(oldLeaderMemberName)) {
195 selectNewOwnerForEntitiesOwnedBy(oldLeaderMemberName);
200 private void onCandidateRemoved(CandidateRemoved message) {
205 LOG.debug("{}: onCandidateRemoved: {}", persistenceId(), message);
207 String currentOwner = getCurrentOwner(message.getEntityPath());
208 if(message.getRemovedCandidate().equals(currentOwner)){
209 writeNewOwner(message.getEntityPath(), newOwner(message.getRemainingCandidates()));
213 private void onCandidateAdded(CandidateAdded message) {
218 LOG.debug("{}: onCandidateAdded: {}", persistenceId(), message);
220 String currentOwner = getCurrentOwner(message.getEntityPath());
221 if(Strings.isNullOrEmpty(currentOwner)){
222 writeNewOwner(message.getEntityPath(), newOwner(message.getAllCandidates()));
226 private void onPeerDown(PeerDown peerDown) {
227 LOG.debug("{}: onPeerDown: {}", persistenceId(), peerDown);
229 String downMemberName = peerDown.getMemberName();
230 if(downPeerMemberNames.add(downMemberName) && isLeader()) {
231 // Select new owners for entities owned by the down peer.
232 selectNewOwnerForEntitiesOwnedBy(downMemberName);
236 private void onPeerUp(PeerUp peerUp) {
237 LOG.debug("{}: onPeerUp: {}", persistenceId(), peerUp);
239 peerIdToMemberNames.put(peerUp.getPeerId(), peerUp.getMemberName());
241 if(downPeerMemberNames.remove(peerUp.getMemberName()) && isLeader()) {
242 // This peer was previously down - for its previously owned entities, if there were no other
243 // candidates, the owner would have been cleared so handle that here by trying to re-assign
244 // ownership for entities whose owner is cleared.
245 selectNewOwnerForEntitiesOwnedBy("");
249 private void selectNewOwnerForEntitiesOwnedBy(String owner) {
250 DataTreeSnapshot snapshot = getDataStore().getDataTree().takeSnapshot();
251 Optional<NormalizedNode<?, ?>> possibleEntityTypes = snapshot.readNode(ENTITY_TYPES_PATH);
252 if(!possibleEntityTypes.isPresent()) {
256 LOG.debug("{}: Searching for entities owned by {}", persistenceId(), owner);
258 BatchedModifications modifications = commitCoordinator.newBatchedModifications();
259 for(MapEntryNode entityType: ((MapNode) possibleEntityTypes.get()).getValue()) {
260 Optional<DataContainerChild<? extends PathArgument, ?>> possibleEntities =
261 entityType.getChild(ENTITY_NODE_ID);
262 if(!possibleEntities.isPresent()) {
263 continue; // shouldn't happen but handle anyway
266 for(MapEntryNode entity: ((MapNode) possibleEntities.get()).getValue()) {
267 Optional<DataContainerChild<? extends PathArgument, ?>> possibleOwner =
268 entity.getChild(ENTITY_OWNER_NODE_ID);
269 if(possibleOwner.isPresent() && owner.equals(possibleOwner.get().getValue().toString())) {
270 Object newOwner = newOwner(getCandidateNames(entity));
271 YangInstanceIdentifier entityPath = YangInstanceIdentifier.builder(ENTITY_TYPES_PATH).
272 node(entityType.getIdentifier()).node(ENTITY_NODE_ID).node(entity.getIdentifier()).
273 node(ENTITY_OWNER_NODE_ID).build();
275 LOG.debug("{}: Found entity {}, writing new owner {}", persistenceId(), entityPath, newOwner);
277 modifications.addModification(new WriteModification(entityPath,
278 ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)));
283 commitCoordinator.commitModifications(modifications, this);
286 private Collection<String> getCandidateNames(MapEntryNode entity) {
287 Collection<MapEntryNode> candidates = ((MapNode)entity.getChild(CANDIDATE_NODE_ID).get()).getValue();
288 Collection<String> candidateNames = new ArrayList<>(candidates.size());
289 for(MapEntryNode candidate: candidates) {
290 candidateNames.add(candidate.getChild(CANDIDATE_NAME_NODE_ID).get().getValue().toString());
293 return candidateNames;
296 private void writeNewOwner(YangInstanceIdentifier entityPath, String newOwner) {
297 LOG.debug("{}: Writing new owner {} for entity {}", persistenceId(), newOwner, entityPath);
299 commitCoordinator.commitModification(new WriteModification(entityPath.node(ENTITY_OWNER_QNAME),
300 ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)), this);
303 private String newOwner(Collection<String> candidates) {
304 for(String candidate: candidates) {
305 if(!downPeerMemberNames.contains(candidate)) {
313 private String getCurrentOwner(YangInstanceIdentifier entityId) {
314 DataTreeSnapshot snapshot = getDataStore().getDataTree().takeSnapshot();
315 Optional<NormalizedNode<?, ?>> optionalEntityOwner = snapshot.readNode(entityId.node(ENTITY_OWNER_QNAME));
316 if(optionalEntityOwner.isPresent()){
317 return optionalEntityOwner.get().getValue().toString();
322 public static Props props(final ShardIdentifier name, final Map<String, String> peerAddresses,
323 final DatastoreContext datastoreContext, final SchemaContext schemaContext, final String localMemberName) {
324 return Props.create(new Creator(name, peerAddresses, datastoreContext, schemaContext, localMemberName));
327 private static class Creator extends AbstractShardCreator {
328 private static final long serialVersionUID = 1L;
330 private final String localMemberName;
332 Creator(final ShardIdentifier name, final Map<String, String> peerAddresses,
333 final DatastoreContext datastoreContext, final SchemaContext schemaContext,
334 final String localMemberName) {
335 super(name, peerAddresses, datastoreContext, schemaContext);
336 this.localMemberName = localMemberName;
340 public Shard create() throws Exception {
341 return new EntityOwnershipShard(name, peerAddresses, datastoreContext, schemaContext, localMemberName);