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