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