Merge "Bug-2098- sal-compatibility not get up-to-date flow information"
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / ShardManager.java
1 /*
2  * Copyright (c) 2014 Cisco 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
9 package org.opendaylight.controller.cluster.datastore;
10
11 import akka.actor.ActorPath;
12 import akka.actor.ActorRef;
13 import akka.actor.Address;
14 import akka.actor.OneForOneStrategy;
15 import akka.actor.Props;
16 import akka.actor.SupervisorStrategy;
17 import akka.cluster.ClusterEvent;
18 import akka.event.Logging;
19 import akka.event.LoggingAdapter;
20 import akka.japi.Creator;
21 import akka.japi.Function;
22 import akka.japi.Procedure;
23 import akka.persistence.RecoveryCompleted;
24 import akka.persistence.RecoveryFailure;
25 import com.google.common.annotations.VisibleForTesting;
26 import com.google.common.base.Preconditions;
27 import com.google.common.base.Supplier;
28 import com.google.common.collect.Lists;
29 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActorWithMetering;
30 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
31 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
32 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfo;
33 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfoMBean;
34 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
35 import org.opendaylight.controller.cluster.datastore.messages.ActorNotInitialized;
36 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
37 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
38 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
39 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
40 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
41 import org.opendaylight.controller.cluster.datastore.messages.PrimaryFound;
42 import org.opendaylight.controller.cluster.datastore.messages.PrimaryNotFound;
43 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
44 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
45 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
46 import scala.concurrent.duration.Duration;
47 import java.io.Serializable;
48 import java.util.ArrayList;
49 import java.util.Collection;
50 import java.util.HashMap;
51 import java.util.HashSet;
52 import java.util.List;
53 import java.util.Map;
54 import java.util.Set;
55
56 /**
57  * The ShardManager has the following jobs,
58  * <ul>
59  * <li> Create all the local shard replicas that belong on this cluster member
60  * <li> Find the address of the local shard
61  * <li> Find the primary replica for any given shard
62  * <li> Monitor the cluster members and store their addresses
63  * <ul>
64  */
65 public class ShardManager extends AbstractUntypedPersistentActorWithMetering {
66
67     protected final LoggingAdapter LOG =
68         Logging.getLogger(getContext().system(), this);
69
70     // Stores a mapping between a member name and the address of the member
71     // Member names look like "member-1", "member-2" etc and are as specified
72     // in configuration
73     private final Map<String, Address> memberNameToAddress = new HashMap<>();
74
75     // Stores a mapping between a shard name and it's corresponding information
76     // Shard names look like inventory, topology etc and are as specified in
77     // configuration
78     private final Map<String, ShardInformation> localShards = new HashMap<>();
79
80     // The type of a ShardManager reflects the type of the datastore itself
81     // A data store could be of type config/operational
82     private final String type;
83
84     private final ClusterWrapper cluster;
85
86     private final Configuration configuration;
87
88     private ShardManagerInfoMBean mBean;
89
90     private final DatastoreContext datastoreContext;
91
92     private final Collection<String> knownModules = new HashSet<>(128);
93
94     /**
95      * @param type defines the kind of data that goes into shards created by this shard manager. Examples of type would be
96      *             configuration or operational
97      */
98     protected ShardManager(String type, ClusterWrapper cluster, Configuration configuration,
99             DatastoreContext datastoreContext) {
100
101         this.type = Preconditions.checkNotNull(type, "type should not be null");
102         this.cluster = Preconditions.checkNotNull(cluster, "cluster should not be null");
103         this.configuration = Preconditions.checkNotNull(configuration, "configuration should not be null");
104         this.datastoreContext = datastoreContext;
105
106         // Subscribe this actor to cluster member events
107         cluster.subscribeToMemberEvents(getSelf());
108
109         createLocalShards();
110     }
111
112     public static Props props(final String type,
113         final ClusterWrapper cluster,
114         final Configuration configuration,
115         final DatastoreContext datastoreContext) {
116
117         Preconditions.checkNotNull(type, "type should not be null");
118         Preconditions.checkNotNull(cluster, "cluster should not be null");
119         Preconditions.checkNotNull(configuration, "configuration should not be null");
120
121         return Props.create(new ShardManagerCreator(type, cluster, configuration, datastoreContext));
122     }
123
124     @Override
125     public void handleCommand(Object message) throws Exception {
126         if (message.getClass().equals(FindPrimary.SERIALIZABLE_CLASS)) {
127             findPrimary(FindPrimary.fromSerializable(message));
128         } else if(message instanceof FindLocalShard){
129             findLocalShard((FindLocalShard) message);
130         } else if (message instanceof UpdateSchemaContext) {
131             updateSchemaContext(message);
132         } else if(message instanceof ActorInitialized) {
133             onActorInitialized(message);
134         } else if (message instanceof ClusterEvent.MemberUp){
135             memberUp((ClusterEvent.MemberUp) message);
136         } else if(message instanceof ClusterEvent.MemberRemoved) {
137             memberRemoved((ClusterEvent.MemberRemoved) message);
138         } else if(message instanceof ClusterEvent.UnreachableMember) {
139             ignoreMessage(message);
140         } else{
141             unknownMessage(message);
142         }
143
144     }
145
146     private void onActorInitialized(Object message) {
147         final ActorRef sender = getSender();
148
149         if (sender == null) {
150             return; //why is a non-actor sending this message? Just ignore.
151         }
152
153         String actorName = sender.path().name();
154         //find shard name from actor name; actor name is stringified shardId
155         ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(actorName).build();
156
157         if (shardId.getShardName() == null) {
158             return;
159         }
160         markShardAsInitialized(shardId.getShardName());
161     }
162
163     private void markShardAsInitialized(String shardName) {
164         LOG.debug("Initializing shard [{}]", shardName);
165         ShardInformation shardInformation = localShards.get(shardName);
166         if (shardInformation != null) {
167             shardInformation.setActorInitialized();
168         }
169     }
170
171     @Override
172     protected void handleRecover(Object message) throws Exception {
173         if(message instanceof SchemaContextModules){
174             SchemaContextModules msg = (SchemaContextModules) message;
175             knownModules.clear();
176             knownModules.addAll(msg.getModules());
177         } else if(message instanceof RecoveryFailure){
178             RecoveryFailure failure = (RecoveryFailure) message;
179             LOG.error(failure.cause(), "Recovery failed");
180         } else if(message instanceof RecoveryCompleted){
181             LOG.info("Recovery complete : {}", persistenceId());
182
183             // Delete all the messages from the akka journal except the last one
184             deleteMessages(lastSequenceNr() - 1);
185         }
186     }
187
188     private void findLocalShard(FindLocalShard message) {
189         final ShardInformation shardInformation = localShards.get(message.getShardName());
190
191         if(shardInformation == null){
192             getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
193             return;
194         }
195
196         sendResponse(shardInformation, message.isWaitUntilInitialized(), new Supplier<Object>() {
197             @Override
198             public Object get() {
199                 return new LocalShardFound(shardInformation.getActor());
200             }
201         });
202     }
203
204     private void sendResponse(ShardInformation shardInformation, boolean waitUntilInitialized,
205             final Supplier<Object> messageSupplier) {
206         if (!shardInformation.isShardInitialized()) {
207             if(waitUntilInitialized) {
208                 final ActorRef sender = getSender();
209                 final ActorRef self = self();
210                 shardInformation.addRunnableOnInitialized(new Runnable() {
211                     @Override
212                     public void run() {
213                         sender.tell(messageSupplier.get(), self);
214                     }
215                 });
216             } else {
217                 getSender().tell(new ActorNotInitialized(), getSelf());
218             }
219
220             return;
221         }
222
223         getSender().tell(messageSupplier.get(), getSelf());
224     }
225
226     private void memberRemoved(ClusterEvent.MemberRemoved message) {
227         memberNameToAddress.remove(message.member().roles().head());
228     }
229
230     private void memberUp(ClusterEvent.MemberUp message) {
231         String memberName = message.member().roles().head();
232
233         memberNameToAddress.put(memberName, message.member().address());
234
235         for(ShardInformation info : localShards.values()){
236             String shardName = info.getShardName();
237             info.updatePeerAddress(getShardIdentifier(memberName, shardName),
238                 getShardActorPath(shardName, memberName));
239         }
240     }
241
242     /**
243      * Notifies all the local shards of a change in the schema context
244      *
245      * @param message
246      */
247     private void updateSchemaContext(final Object message) {
248         final SchemaContext schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
249
250         Set<ModuleIdentifier> allModuleIdentifiers = schemaContext.getAllModuleIdentifiers();
251         Set<String> newModules = new HashSet<>(128);
252
253         for(ModuleIdentifier moduleIdentifier : allModuleIdentifiers){
254             String s = moduleIdentifier.getNamespace().toString();
255             newModules.add(s);
256         }
257
258         if(newModules.containsAll(knownModules)) {
259
260             LOG.info("New SchemaContext has a super set of current knownModules - persisting info");
261
262             knownModules.clear();
263             knownModules.addAll(newModules);
264
265             persist(new SchemaContextModules(newModules), new Procedure<SchemaContextModules>() {
266
267                 @Override
268                 public void apply(SchemaContextModules param) throws Exception {
269                     LOG.info("Sending new SchemaContext to Shards");
270                     for (ShardInformation info : localShards.values()) {
271                         if(info.getActor() == null) {
272                             info.setActor(getContext().actorOf(Shard.props(info.getShardId(),
273                                     info.getPeerAddresses(), datastoreContext, schemaContext),
274                                     info.getShardId().toString()));
275                         } else {
276                             info.getActor().tell(message, getSelf());
277                         }
278                     }
279                 }
280
281             });
282         } else {
283             LOG.info("Rejecting schema context update because it is not a super set of previously known modules");
284         }
285
286     }
287
288     private void findPrimary(FindPrimary message) {
289         String shardName = message.getShardName();
290
291         // First see if the there is a local replica for the shard
292         final ShardInformation info = localShards.get(shardName);
293         if (info != null) {
294             sendResponse(info, message.isWaitUntilInitialized(), new Supplier<Object>() {
295                 @Override
296                 public Object get() {
297                     return new PrimaryFound(info.getActorPath().toString()).toSerializable();
298                 }
299             });
300
301             return;
302         }
303
304         List<String> members = configuration.getMembersFromShardName(shardName);
305
306         if(cluster.getCurrentMemberName() != null) {
307             members.remove(cluster.getCurrentMemberName());
308         }
309
310         /**
311          * FIXME: Instead of sending remote shard actor path back to sender,
312          * forward FindPrimary message to remote shard manager
313          */
314         // There is no way for us to figure out the primary (for now) so assume
315         // that one of the remote nodes is a primary
316         for(String memberName : members) {
317             Address address = memberNameToAddress.get(memberName);
318             if(address != null){
319                 String path =
320                     getShardActorPath(shardName, memberName);
321                 getSender().tell(new PrimaryFound(path).toSerializable(), getSelf());
322                 return;
323             }
324         }
325         getSender().tell(new PrimaryNotFound(shardName).toSerializable(), getSelf());
326     }
327
328     private String getShardActorPath(String shardName, String memberName) {
329         Address address = memberNameToAddress.get(memberName);
330         if(address != null) {
331             StringBuilder builder = new StringBuilder();
332             builder.append(address.toString())
333                 .append("/user/")
334                 .append(ShardManagerIdentifier.builder().type(type).build().toString())
335                 .append("/")
336                 .append(getShardIdentifier(memberName, shardName));
337             return builder.toString();
338         }
339         return null;
340     }
341
342     /**
343      * Construct the name of the shard actor given the name of the member on
344      * which the shard resides and the name of the shard
345      *
346      * @param memberName
347      * @param shardName
348      * @return
349      */
350     private ShardIdentifier getShardIdentifier(String memberName, String shardName){
351         return ShardIdentifier.builder().memberName(memberName).shardName(shardName).type(type).build();
352     }
353
354     /**
355      * Create shards that are local to the member on which the ShardManager
356      * runs
357      *
358      */
359     private void createLocalShards() {
360         String memberName = this.cluster.getCurrentMemberName();
361         List<String> memberShardNames =
362             this.configuration.getMemberShardNames(memberName);
363
364         List<String> localShardActorNames = new ArrayList<>();
365         for(String shardName : memberShardNames){
366             ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
367             Map<ShardIdentifier, String> peerAddresses = getPeerAddresses(shardName);
368             localShardActorNames.add(shardId.toString());
369             localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses));
370         }
371
372         mBean = ShardManagerInfo.createShardManagerMBean("shard-manager-" + this.type,
373                     datastoreContext.getDataStoreMXBeanType(), localShardActorNames);
374     }
375
376     /**
377      * Given the name of the shard find the addresses of all it's peers
378      *
379      * @param shardName
380      * @return
381      */
382     private Map<ShardIdentifier, String> getPeerAddresses(String shardName){
383
384         Map<ShardIdentifier, String> peerAddresses = new HashMap<>();
385
386         List<String> members =
387             this.configuration.getMembersFromShardName(shardName);
388
389         String currentMemberName = this.cluster.getCurrentMemberName();
390
391         for(String memberName : members){
392             if(!currentMemberName.equals(memberName)){
393                 ShardIdentifier shardId = getShardIdentifier(memberName,
394                     shardName);
395                 String path =
396                     getShardActorPath(shardName, currentMemberName);
397                 peerAddresses.put(shardId, path);
398             }
399         }
400         return peerAddresses;
401     }
402
403     @Override
404     public SupervisorStrategy supervisorStrategy() {
405
406         return new OneForOneStrategy(10, Duration.create("1 minute"),
407             new Function<Throwable, SupervisorStrategy.Directive>() {
408                 @Override
409                 public SupervisorStrategy.Directive apply(Throwable t) {
410                     StringBuilder sb = new StringBuilder();
411                     for(StackTraceElement element : t.getStackTrace()) {
412                        sb.append("\n\tat ")
413                          .append(element.toString());
414                     }
415                     LOG.warning("Supervisor Strategy of resume applied {}",sb.toString());
416                     return SupervisorStrategy.resume();
417                 }
418             }
419         );
420
421     }
422
423     @Override
424     public String persistenceId() {
425         return "shard-manager-" + type;
426     }
427
428     @VisibleForTesting
429     Collection<String> getKnownModules() {
430         return knownModules;
431     }
432
433     private class ShardInformation {
434         private final ShardIdentifier shardId;
435         private final String shardName;
436         private ActorRef actor;
437         private ActorPath actorPath;
438         private final Map<ShardIdentifier, String> peerAddresses;
439
440         // flag that determines if the actor is ready for business
441         private boolean actorInitialized = false;
442
443         private final List<Runnable> runnablesOnInitialized = Lists.newArrayList();
444
445         private ShardInformation(String shardName, ShardIdentifier shardId,
446                 Map<ShardIdentifier, String> peerAddresses) {
447             this.shardName = shardName;
448             this.shardId = shardId;
449             this.peerAddresses = peerAddresses;
450         }
451
452         String getShardName() {
453             return shardName;
454         }
455
456         ActorRef getActor(){
457             return actor;
458         }
459
460         ActorPath getActorPath() {
461             return actorPath;
462         }
463
464         void setActor(ActorRef actor) {
465             this.actor = actor;
466             this.actorPath = actor.path();
467         }
468
469         ShardIdentifier getShardId() {
470             return shardId;
471         }
472
473         Map<ShardIdentifier, String> getPeerAddresses() {
474             return peerAddresses;
475         }
476
477         void updatePeerAddress(ShardIdentifier peerId, String peerAddress){
478             LOG.info("updatePeerAddress for peer {} with address {}", peerId,
479                 peerAddress);
480             if(peerAddresses.containsKey(peerId)){
481                 peerAddresses.put(peerId, peerAddress);
482
483                 if(actor != null) {
484                     if(LOG.isDebugEnabled()) {
485                         LOG.debug("Sending PeerAddressResolved for peer {} with address {} to {}",
486                                 peerId, peerAddress, actor.path());
487                     }
488
489                     actor.tell(new PeerAddressResolved(peerId, peerAddress), getSelf());
490                 }
491             }
492         }
493
494         boolean isShardInitialized() {
495             return getActor() != null && actorInitialized;
496         }
497
498         void setActorInitialized() {
499             this.actorInitialized = true;
500
501             for(Runnable runnable: runnablesOnInitialized) {
502                 runnable.run();
503             }
504
505             runnablesOnInitialized.clear();
506         }
507
508         void addRunnableOnInitialized(Runnable runnable) {
509             runnablesOnInitialized.add(runnable);
510         }
511     }
512
513     private static class ShardManagerCreator implements Creator<ShardManager> {
514         private static final long serialVersionUID = 1L;
515
516         final String type;
517         final ClusterWrapper cluster;
518         final Configuration configuration;
519         final DatastoreContext datastoreContext;
520
521         ShardManagerCreator(String type, ClusterWrapper cluster,
522                 Configuration configuration, DatastoreContext datastoreContext) {
523             this.type = type;
524             this.cluster = cluster;
525             this.configuration = configuration;
526             this.datastoreContext = datastoreContext;
527         }
528
529         @Override
530         public ShardManager create() throws Exception {
531             return new ShardManager(type, cluster, configuration, datastoreContext);
532         }
533     }
534
535     static class SchemaContextModules implements Serializable {
536         private final Set<String> modules;
537
538         SchemaContextModules(Set<String> modules){
539             this.modules = modules;
540         }
541
542         public Set<String> getModules() {
543             return modules;
544         }
545     }
546 }
547
548
549