Merge "Bug 1819 - Moved bundle up in features.xml to avoid exception in log Change...
[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 com.google.common.base.Preconditions;
21 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedActorWithMetering;
22
23 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
24 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
25 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfo;
26 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfoMBean;
27 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
28 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
29 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
30 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
31 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
32 import org.opendaylight.controller.cluster.datastore.messages.PrimaryFound;
33 import org.opendaylight.controller.cluster.datastore.messages.PrimaryNotFound;
34 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
35 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
36 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
37 import scala.concurrent.duration.Duration;
38
39 import java.util.ArrayList;
40 import java.util.HashMap;
41 import java.util.List;
42 import java.util.Map;
43
44 /**
45  * The ShardManager has the following jobs,
46  * <ul>
47  * <li> Create all the local shard replicas that belong on this cluster member
48  * <li> Find the address of the local shard
49  * <li> Find the primary replica for any given shard
50  * <li> Monitor the cluster members and store their addresses
51  * <ul>
52  */
53 public class ShardManager extends AbstractUntypedActorWithMetering {
54
55     // Stores a mapping between a member name and the address of the member
56     // Member names look like "member-1", "member-2" etc and are as specified
57     // in configuration
58     private final Map<String, Address> memberNameToAddress = new HashMap<>();
59
60     // Stores a mapping between a shard name and it's corresponding information
61     // Shard names look like inventory, topology etc and are as specified in
62     // configuration
63     private final Map<String, ShardInformation> localShards = new HashMap<>();
64
65     // The type of a ShardManager reflects the type of the datastore itself
66     // A data store could be of type config/operational
67     private final String type;
68
69     private final ClusterWrapper cluster;
70
71     private final Configuration configuration;
72
73     private ShardManagerInfoMBean mBean;
74
75     private final DatastoreContext datastoreContext;
76
77     /**
78      * @param type defines the kind of data that goes into shards created by this shard manager. Examples of type would be
79      *             configuration or operational
80      */
81     private ShardManager(String type, ClusterWrapper cluster, Configuration configuration,
82             DatastoreContext datastoreContext) {
83
84         this.type = Preconditions.checkNotNull(type, "type should not be null");
85         this.cluster = Preconditions.checkNotNull(cluster, "cluster should not be null");
86         this.configuration = Preconditions.checkNotNull(configuration, "configuration should not be null");
87         this.datastoreContext = datastoreContext;
88
89         // Subscribe this actor to cluster member events
90         cluster.subscribeToMemberEvents(getSelf());
91
92         //createLocalShards(null);
93     }
94
95     public static Props props(final String type,
96         final ClusterWrapper cluster,
97         final Configuration configuration,
98         final DatastoreContext datastoreContext) {
99
100         Preconditions.checkNotNull(type, "type should not be null");
101         Preconditions.checkNotNull(cluster, "cluster should not be null");
102         Preconditions.checkNotNull(configuration, "configuration should not be null");
103
104         return Props.create(new ShardManagerCreator(type, cluster, configuration, datastoreContext));
105     }
106
107     @Override
108     public void handleReceive(Object message) throws Exception {
109         if (message.getClass().equals(FindPrimary.SERIALIZABLE_CLASS)) {
110             findPrimary(
111                 FindPrimary.fromSerializable(message));
112         } else if(message instanceof FindLocalShard){
113             findLocalShard((FindLocalShard) message);
114         } else if (message instanceof UpdateSchemaContext) {
115             updateSchemaContext(message);
116         } else if (message instanceof ClusterEvent.MemberUp){
117             memberUp((ClusterEvent.MemberUp) message);
118         } else if(message instanceof ClusterEvent.MemberRemoved) {
119             memberRemoved((ClusterEvent.MemberRemoved) message);
120         } else if(message instanceof ClusterEvent.UnreachableMember) {
121             ignoreMessage(message);
122         } else{
123             unknownMessage(message);
124         }
125
126     }
127
128     private void findLocalShard(FindLocalShard message) {
129         ShardInformation shardInformation =
130             localShards.get(message.getShardName());
131
132         if(shardInformation != null){
133             getSender().tell(new LocalShardFound(shardInformation.getActor()), getSelf());
134             return;
135         }
136
137         getSender().tell(new LocalShardNotFound(message.getShardName()),
138             getSelf());
139     }
140
141     private void memberRemoved(ClusterEvent.MemberRemoved message) {
142         memberNameToAddress.remove(message.member().roles().head());
143     }
144
145     private void memberUp(ClusterEvent.MemberUp message) {
146         String memberName = message.member().roles().head();
147
148         memberNameToAddress.put(memberName , message.member().address());
149
150         for(ShardInformation info : localShards.values()){
151             String shardName = info.getShardName();
152             info.updatePeerAddress(getShardIdentifier(memberName, shardName),
153                 getShardActorPath(shardName, memberName));
154         }
155     }
156
157     /**
158      * Notifies all the local shards of a change in the schema context
159      *
160      * @param message
161      */
162     private void updateSchemaContext(Object message) {
163         SchemaContext schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
164
165         if(localShards.size() == 0){
166             createLocalShards(schemaContext);
167         } else {
168             for (ShardInformation info : localShards.values()) {
169                 info.getActor().tell(message, getSelf());
170             }
171         }
172     }
173
174     private void findPrimary(FindPrimary message) {
175         String shardName = message.getShardName();
176
177         // First see if the there is a local replica for the shard
178         ShardInformation info = localShards.get(shardName);
179         if(info != null) {
180             ActorPath shardPath = info.getActorPath();
181             if (shardPath != null) {
182                 getSender()
183                     .tell(
184                         new PrimaryFound(shardPath.toString()).toSerializable(),
185                         getSelf());
186                 return;
187             }
188         }
189
190         List<String> members =
191             configuration.getMembersFromShardName(shardName);
192
193         if(cluster.getCurrentMemberName() != null) {
194             members.remove(cluster.getCurrentMemberName());
195         }
196
197         // There is no way for us to figure out the primary (for now) so assume
198         // that one of the remote nodes is a primary
199         for(String memberName : members) {
200             Address address = memberNameToAddress.get(memberName);
201             if(address != null){
202                 String path =
203                     getShardActorPath(shardName, memberName);
204                 getSender().tell(new PrimaryFound(path).toSerializable(), getSelf());
205                 return;
206             }
207         }
208         getSender().tell(new PrimaryNotFound(shardName).toSerializable(), getSelf());
209     }
210
211     private String getShardActorPath(String shardName, String memberName) {
212         Address address = memberNameToAddress.get(memberName);
213         if(address != null) {
214             StringBuilder builder = new StringBuilder();
215             builder.append(address.toString())
216                 .append("/user/")
217                 .append(ShardManagerIdentifier.builder().type(type).build().toString())
218                 .append("/")
219                 .append(getShardIdentifier(memberName, shardName));
220             return builder.toString();
221         }
222         return null;
223     }
224
225     /**
226      * Construct the name of the shard actor given the name of the member on
227      * which the shard resides and the name of the shard
228      *
229      * @param memberName
230      * @param shardName
231      * @return
232      */
233     private ShardIdentifier getShardIdentifier(String memberName, String shardName){
234         return ShardIdentifier.builder().memberName(memberName).shardName(shardName).type(type).build();
235     }
236
237     /**
238      * Create shards that are local to the member on which the ShardManager
239      * runs
240      *
241      */
242     private void createLocalShards(SchemaContext schemaContext) {
243         String memberName = this.cluster.getCurrentMemberName();
244         List<String> memberShardNames =
245             this.configuration.getMemberShardNames(memberName);
246
247         List<String> localShardActorNames = new ArrayList<>();
248         for(String shardName : memberShardNames){
249             ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
250             Map<ShardIdentifier, String> peerAddresses = getPeerAddresses(shardName);
251             ActorRef actor = getContext()
252                 .actorOf(Shard.props(shardId, peerAddresses, datastoreContext, schemaContext).
253                     withMailbox(ActorContext.MAILBOX), shardId.toString());
254             localShardActorNames.add(shardId.toString());
255             localShards.put(shardName, new ShardInformation(shardName, actor, peerAddresses));
256         }
257
258         mBean = ShardManagerInfo.createShardManagerMBean("shard-manager-" + this.type,
259                     datastoreContext.getDataStoreMXBeanType(), localShardActorNames);
260     }
261
262     /**
263      * Given the name of the shard find the addresses of all it's peers
264      *
265      * @param shardName
266      * @return
267      */
268     private Map<ShardIdentifier, String> getPeerAddresses(String shardName){
269
270         Map<ShardIdentifier, String> peerAddresses = new HashMap<>();
271
272         List<String> members =
273             this.configuration.getMembersFromShardName(shardName);
274
275         String currentMemberName = this.cluster.getCurrentMemberName();
276
277         for(String memberName : members){
278             if(!currentMemberName.equals(memberName)){
279                 ShardIdentifier shardId = getShardIdentifier(memberName,
280                     shardName);
281                 String path =
282                     getShardActorPath(shardName, currentMemberName);
283                 peerAddresses.put(shardId, path);
284             }
285         }
286         return peerAddresses;
287     }
288
289     @Override
290     public SupervisorStrategy supervisorStrategy() {
291
292         return new OneForOneStrategy(10, Duration.create("1 minute"),
293             new Function<Throwable, SupervisorStrategy.Directive>() {
294                 @Override
295                 public SupervisorStrategy.Directive apply(Throwable t) {
296                     StringBuilder sb = new StringBuilder();
297                     for(StackTraceElement element : t.getStackTrace()) {
298                        sb.append("\n\tat ")
299                          .append(element.toString());
300                     }
301                     LOG.warning("Supervisor Strategy of resume applied {}",sb.toString());
302                     return SupervisorStrategy.resume();
303                 }
304             }
305         );
306
307     }
308
309     private class ShardInformation {
310         private final String shardName;
311         private final ActorRef actor;
312         private final ActorPath actorPath;
313         private final Map<ShardIdentifier, String> peerAddresses;
314
315         private ShardInformation(String shardName, ActorRef actor,
316             Map<ShardIdentifier, String> peerAddresses) {
317             this.shardName = shardName;
318             this.actor = actor;
319             this.actorPath = actor.path();
320             this.peerAddresses = peerAddresses;
321         }
322
323         public String getShardName() {
324             return shardName;
325         }
326
327         public ActorRef getActor(){
328             return actor;
329         }
330
331         public ActorPath getActorPath() {
332             return actorPath;
333         }
334
335         public void updatePeerAddress(ShardIdentifier peerId, String peerAddress){
336             LOG.info("updatePeerAddress for peer {} with address {}", peerId,
337                 peerAddress);
338             if(peerAddresses.containsKey(peerId)){
339                 peerAddresses.put(peerId, peerAddress);
340                 if(LOG.isDebugEnabled()) {
341                     LOG.debug(
342                         "Sending PeerAddressResolved for peer {} with address {} to {}",
343                         peerId, peerAddress, actor.path());
344                 }
345                 actor
346                     .tell(new PeerAddressResolved(peerId, peerAddress),
347                         getSelf());
348
349             }
350         }
351     }
352
353     private static class ShardManagerCreator implements Creator<ShardManager> {
354         private static final long serialVersionUID = 1L;
355
356         final String type;
357         final ClusterWrapper cluster;
358         final Configuration configuration;
359         final DatastoreContext datastoreContext;
360
361         ShardManagerCreator(String type, ClusterWrapper cluster,
362                 Configuration configuration, DatastoreContext datastoreContext) {
363             this.type = type;
364             this.cluster = cluster;
365             this.configuration = configuration;
366             this.datastoreContext = datastoreContext;
367         }
368
369         @Override
370         public ShardManager create() throws Exception {
371             return new ShardManager(type, cluster, configuration, datastoreContext);
372         }
373     }
374 }
375
376
377