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