3d48271c54f9178685260c30841d1437caa4a62e
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / entityownership / EntityOwnershipShard.java
1 /*
2  * Copyright (c) 2015 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.cluster.datastore.entityownership;
9
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;
36 import java.util.Map;
37 import java.util.Set;
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;
65
66 /**
67  * Special Shard for EntityOwnership.
68  *
69  * @author Thomas Pantelis
70  */
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<>();
77
78     private static DatastoreContext noPersistenceDatastoreContext(DatastoreContext datastoreContext) {
79         return DatastoreContext.newBuilderFrom(datastoreContext).persistent(false).build();
80     }
81
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());
88
89         for(String peerId: peerAddresses.keySet()) {
90             ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(peerId).build();
91             peerIdToMemberNames.put(peerId, shardId.getMemberName());
92         }
93     }
94
95     @Override
96     protected void onDatastoreContext(DatastoreContext context) {
97         super.onDatastoreContext(noPersistenceDatastoreContext(context));
98     }
99
100     @Override
101     protected void onRecoveryComplete() {
102         super.onRecoveryComplete();
103
104         new CandidateListChangeListener(getSelf(), persistenceId()).init(getDataStore());
105         new EntityOwnerChangeListener(localMemberName, listenerSupport).init(getDataStore());
106     }
107
108     @Override
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);
128         }
129     }
130
131     private void onRegisterCandidateLocal(RegisterCandidateLocal registerCandidate) {
132         LOG.debug("{}: onRegisterCandidateLocal: {}", persistenceId(), registerCandidate);
133
134         listenerSupport.setHasCandidateForEntity(registerCandidate.getEntity());
135
136         NormalizedNode<?, ?> entityOwners = entityOwnersWithCandidate(registerCandidate.getEntity().getType(),
137                 registerCandidate.getEntity().getId(), localMemberName);
138         commitCoordinator.commitModification(new MergeModification(ENTITY_OWNERS_PATH, entityOwners), this);
139
140         getSender().tell(SuccessReply.INSTANCE, getSelf());
141     }
142
143     private void onUnregisterCandidateLocal(UnregisterCandidateLocal unregisterCandidate) {
144         LOG.debug("{}: onUnregisterCandidateLocal: {}", persistenceId(), unregisterCandidate);
145
146         Entity entity = unregisterCandidate.getEntity();
147         listenerSupport.unsetHasCandidateForEntity(entity);
148
149         YangInstanceIdentifier candidatePath = candidatePath(entity.getType(), entity.getId(), localMemberName);
150         commitCoordinator.commitModification(new DeleteModification(candidatePath), this);
151
152         getSender().tell(SuccessReply.INSTANCE, getSelf());
153     }
154
155     private void onRegisterListenerLocal(final RegisterListenerLocal registerListener) {
156         LOG.debug("{}: onRegisterListenerLocal: {}", persistenceId(), registerListener);
157
158         listenerSupport.addEntityOwnershipListener(registerListener.getEntityType(), registerListener.getListener());
159
160         getSender().tell(SuccessReply.INSTANCE, getSelf());
161
162         searchForEntitiesOwnedBy(localMemberName, new EntityWalker() {
163             @Override
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());
172                 }
173             }
174         });
175     }
176
177     private void onUnregisterListenerLocal(UnregisterListenerLocal unregisterListener) {
178         LOG.debug("{}: onUnregisterListenerLocal: {}", persistenceId(), unregisterListener);
179
180         listenerSupport.removeEntityOwnershipListener(unregisterListener.getEntityType(), unregisterListener.getListener());
181
182         getSender().tell(SuccessReply.INSTANCE, getSelf());
183     }
184
185     void tryCommitModifications(final BatchedModifications modifications) {
186         if(isLeader()) {
187             LOG.debug("{}: Committing BatchedModifications {} locally", persistenceId(), modifications.getTransactionID());
188
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());
194         } else {
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);
200                 }
201
202                 Future<Object> future = Patterns.ask(leader, modifications, TimeUnit.SECONDS.toMillis(
203                         getDatastoreContext().getShardTransactionCommitTimeoutInSeconds()));
204
205                 Patterns.pipe(future, getContext().dispatcher()).pipeTo(getSelf(), ActorRef.noSender());
206             }
207         }
208     }
209
210     boolean hasLeader() {
211         return getLeader() != null && !isIsolatedLeader();
212     }
213
214     @Override
215     protected void onStateChanged() {
216         super.onStateChanged();
217
218         commitCoordinator.onStateChanged(this, isLeader());
219     }
220
221     @Override
222     protected void onLeaderChanged(String oldLeader, String newLeader) {
223         super.onLeaderChanged(oldLeader, newLeader);
224
225         LOG.debug("{}: onLeaderChanged: oldLeader: {}, newLeader: {}, isLeader: {}", persistenceId(), oldLeader,
226                 newLeader, isLeader());
227
228         if(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.
231
232             String oldLeaderMemberName = peerIdToMemberNames.get(oldLeader);
233
234             LOG.debug("{}: oldLeaderMemberName: {}", persistenceId(), oldLeaderMemberName);
235
236             if(downPeerMemberNames.contains(oldLeaderMemberName)) {
237                 selectNewOwnerForEntitiesOwnedBy(oldLeaderMemberName);
238             }
239         }
240     }
241
242     private void onCandidateRemoved(CandidateRemoved message) {
243         LOG.debug("{}: onCandidateRemoved: {}", persistenceId(), message);
244
245         if(isLeader()) {
246             String currentOwner = getCurrentOwner(message.getEntityPath());
247             if(message.getRemovedCandidate().equals(currentOwner)){
248                 writeNewOwner(message.getEntityPath(), newOwner(message.getRemainingCandidates()));
249             }
250         } else {
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
255             // our candidate.
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());
260
261                 commitCoordinator.commitModification(new MergeModification(
262                         candidatePath(message.getEntityPath(), localMemberName),
263                         candidateMapEntry(localMemberName)), this);
264             }
265         }
266     }
267
268     private void onCandidateAdded(CandidateAdded message) {
269         if(!isLeader()){
270             return;
271         }
272
273         LOG.debug("{}: onCandidateAdded: {}", persistenceId(), message);
274
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());
278
279         String currentOwner = getCurrentOwner(message.getEntityPath());
280         if(Strings.isNullOrEmpty(currentOwner)){
281             writeNewOwner(message.getEntityPath(), newOwner(message.getAllCandidates()));
282         }
283     }
284
285     private void onPeerDown(PeerDown peerDown) {
286         LOG.info("{}: onPeerDown: {}", persistenceId(), peerDown);
287
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);
292         }
293     }
294
295     private void onPeerUp(PeerUp peerUp) {
296         LOG.debug("{}: onPeerUp: {}", persistenceId(), peerUp);
297
298         peerIdToMemberNames.put(peerUp.getPeerId(), peerUp.getMemberName());
299         downPeerMemberNames.remove(peerUp.getMemberName());
300     }
301
302     private void selectNewOwnerForEntitiesOwnedBy(String owner) {
303         final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
304         searchForEntitiesOwnedBy(owner, new EntityWalker() {
305             @Override
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();
311
312                 LOG.debug("{}: Found entity {}, writing new owner {}", persistenceId(), entityPath, newOwner);
313
314                 modifications.addModification(new WriteModification(entityPath,
315                         ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)));
316             }
317         });
318
319         commitCoordinator.commitModifications(modifications, this);
320     }
321
322     private void removeCandidateFromEntities(final String owner) {
323         final BatchedModifications modifications = commitCoordinator.newBatchedModifications();
324         searchForEntities(new EntityWalker() {
325             @Override
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(),
332                             entityId, owner);
333
334                     LOG.info("{}: Found entity {}, removing candidate {}, path {}", persistenceId(), entityId,
335                             owner, candidatePath);
336
337                     modifications.addModification(new DeleteModification(candidatePath));
338                 }
339             }
340         });
341
342         commitCoordinator.commitModifications(modifications, this);
343     }
344
345     private static boolean hasCandidate(MapEntryNode entity, String candidateName) {
346         return ((MapNode)entity.getChild(CANDIDATE_NODE_ID).get()).getChild(candidateNodeKey(candidateName)).isPresent();
347     }
348
349     private void searchForEntitiesOwnedBy(final String owner, final EntityWalker walker) {
350         Optional<NormalizedNode<?, ?>> possibleEntityTypes = getDataStore().readNode(ENTITY_TYPES_PATH);
351         if(!possibleEntityTypes.isPresent()) {
352             return;
353         }
354
355         LOG.debug("{}: Searching for entities owned by {}", persistenceId(), owner);
356
357         searchForEntities(new EntityWalker() {
358             @Override
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);
364                 }
365             }
366         });
367     }
368
369     private void searchForEntities(EntityWalker walker) {
370         Optional<NormalizedNode<?, ?>> possibleEntityTypes = getDataStore().readNode(ENTITY_TYPES_PATH);
371         if(!possibleEntityTypes.isPresent()) {
372             return;
373         }
374
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
380             }
381
382             for(MapEntryNode entity:  ((MapNode) possibleEntities.get()).getValue()) {
383                 walker.onEntity(entityType, entity);
384             }
385         }
386     }
387
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());
393         }
394
395         return candidateNames;
396     }
397
398     private void writeNewOwner(YangInstanceIdentifier entityPath, String newOwner) {
399         LOG.debug("{}: Writing new owner {} for entity {}", persistenceId(), newOwner, entityPath);
400
401         commitCoordinator.commitModification(new WriteModification(entityPath.node(ENTITY_OWNER_QNAME),
402                 ImmutableNodes.leafNode(ENTITY_OWNER_NODE_ID, newOwner)), this);
403     }
404
405     private String newOwner(Collection<String> candidates) {
406         for(String candidate: candidates) {
407             if(!downPeerMemberNames.contains(candidate)) {
408                 return candidate;
409             }
410         }
411
412         return "";
413     }
414
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();
419         }
420         return null;
421     }
422
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));
426     }
427
428     private static class Creator extends AbstractShardCreator {
429         private static final long serialVersionUID = 1L;
430
431         private final String localMemberName;
432
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;
438         }
439
440         @Override
441         public Shard create() throws Exception {
442             return new EntityOwnershipShard(name, peerAddresses, datastoreContext, schemaContext, localMemberName);
443         }
444     }
445
446     private static interface EntityWalker {
447         void onEntity(MapEntryNode entityTypeNode, MapEntryNode entityNode);
448     }
449 }