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