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