2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.cluster.datastore;
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;
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;
55 * The ShardManager has the following jobs,
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
63 public class ShardManager extends AbstractUntypedPersistentActor {
65 protected final LoggingAdapter LOG =
66 Logging.getLogger(getContext().system(), this);
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
71 private final Map<String, Address> memberNameToAddress = new HashMap<>();
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
76 private final Map<String, ShardInformation> localShards = new HashMap<>();
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;
82 private final ClusterWrapper cluster;
84 private final Configuration configuration;
86 private ShardManagerInfoMBean mBean;
88 private final DatastoreContext datastoreContext;
90 private final Collection<String> knownModules = new HashSet<>(128);
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
96 private ShardManager(String type, ClusterWrapper cluster, Configuration configuration,
97 DatastoreContext datastoreContext) {
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;
104 // Subscribe this actor to cluster member events
105 cluster.subscribeToMemberEvents(getSelf());
107 //createLocalShards(null);
110 public static Props props(final String type,
111 final ClusterWrapper cluster,
112 final Configuration configuration,
113 final DatastoreContext datastoreContext) {
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");
119 return Props.create(new ShardManagerCreator(type, cluster, configuration, datastoreContext));
123 public void handleCommand(Object message) throws Exception {
124 if (message.getClass().equals(FindPrimary.SERIALIZABLE_CLASS)) {
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);
138 unknownMessage(message);
143 @Override protected void handleRecover(Object message) throws Exception {
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());
155 // Delete all the messages from the akka journal except the last one
156 deleteMessages(lastSequenceNr() - 1);
160 private void findLocalShard(FindLocalShard message) {
161 ShardInformation shardInformation =
162 localShards.get(message.getShardName());
164 if(shardInformation != null){
165 getSender().tell(new LocalShardFound(shardInformation.getActor()), getSelf());
169 getSender().tell(new LocalShardNotFound(message.getShardName()),
173 private void memberRemoved(ClusterEvent.MemberRemoved message) {
174 memberNameToAddress.remove(message.member().roles().head());
177 private void memberUp(ClusterEvent.MemberUp message) {
178 String memberName = message.member().roles().head();
180 memberNameToAddress.put(memberName , message.member().address());
182 for(ShardInformation info : localShards.values()){
183 String shardName = info.getShardName();
184 info.updatePeerAddress(getShardIdentifier(memberName, shardName),
185 getShardActorPath(shardName, memberName));
190 * Notifies all the local shards of a change in the schema context
194 private void updateSchemaContext(final Object message) {
195 final SchemaContext schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
197 Set<ModuleIdentifier> allModuleIdentifiers = schemaContext.getAllModuleIdentifiers();
198 Set<String> newModules = new HashSet<>(128);
200 for(ModuleIdentifier moduleIdentifier : allModuleIdentifiers){
201 String s = moduleIdentifier.getNamespace().toString();
205 if(newModules.containsAll(knownModules)) {
207 LOG.info("New SchemaContext has a super set of current knownModules - persisting info");
209 knownModules.clear();
210 knownModules.addAll(newModules);
212 persist(new SchemaContextModules(newModules), new Procedure<SchemaContextModules>() {
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);
219 for (ShardInformation info : localShards.values()) {
220 info.getActor().tell(message, getSelf());
227 LOG.info("Rejecting schema context update because it is not a super set of previously known modules");
232 private void findPrimary(FindPrimary message) {
233 String shardName = message.getShardName();
235 // First see if the there is a local replica for the shard
236 ShardInformation info = localShards.get(shardName);
238 ActorPath shardPath = info.getActorPath();
239 if (shardPath != null) {
242 new PrimaryFound(shardPath.toString()).toSerializable(),
248 List<String> members =
249 configuration.getMembersFromShardName(shardName);
251 if(cluster.getCurrentMemberName() != null) {
252 members.remove(cluster.getCurrentMemberName());
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);
261 getShardActorPath(shardName, memberName);
262 getSender().tell(new PrimaryFound(path).toSerializable(), getSelf());
266 getSender().tell(new PrimaryNotFound(shardName).toSerializable(), getSelf());
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())
275 .append(ShardManagerIdentifier.builder().type(type).build().toString())
277 .append(getShardIdentifier(memberName, shardName));
278 return builder.toString();
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
291 private ShardIdentifier getShardIdentifier(String memberName, String shardName){
292 return ShardIdentifier.builder().memberName(memberName).shardName(shardName).type(type).build();
296 * Create shards that are local to the member on which the ShardManager
300 private void createLocalShards(SchemaContext schemaContext) {
301 String memberName = this.cluster.getCurrentMemberName();
302 List<String> memberShardNames =
303 this.configuration.getMemberShardNames(memberName);
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));
316 mBean = ShardManagerInfo.createShardManagerMBean("shard-manager-" + this.type,
317 datastoreContext.getDataStoreMXBeanType(), localShardActorNames);
321 * Given the name of the shard find the addresses of all it's peers
326 private Map<ShardIdentifier, String> getPeerAddresses(String shardName){
328 Map<ShardIdentifier, String> peerAddresses = new HashMap<>();
330 List<String> members =
331 this.configuration.getMembersFromShardName(shardName);
333 String currentMemberName = this.cluster.getCurrentMemberName();
335 for(String memberName : members){
336 if(!currentMemberName.equals(memberName)){
337 ShardIdentifier shardId = getShardIdentifier(memberName,
340 getShardActorPath(shardName, currentMemberName);
341 peerAddresses.put(shardId, path);
344 return peerAddresses;
348 public SupervisorStrategy supervisorStrategy() {
350 return new OneForOneStrategy(10, Duration.create("1 minute"),
351 new Function<Throwable, SupervisorStrategy.Directive>() {
353 public SupervisorStrategy.Directive apply(Throwable t) {
354 StringBuilder sb = new StringBuilder();
355 for(StackTraceElement element : t.getStackTrace()) {
357 .append(element.toString());
359 LOG.warning("Supervisor Strategy of resume applied {}",sb.toString());
360 return SupervisorStrategy.resume();
367 @Override public String persistenceId() {
368 return "shard-manager-" + type;
371 @VisibleForTesting public Collection<String> getKnownModules() {
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;
381 private ShardInformation(String shardName, ActorRef actor,
382 Map<ShardIdentifier, String> peerAddresses) {
383 this.shardName = shardName;
385 this.actorPath = actor.path();
386 this.peerAddresses = peerAddresses;
389 public String getShardName() {
393 public ActorRef getActor(){
397 public ActorPath getActorPath() {
401 public void updatePeerAddress(ShardIdentifier peerId, String peerAddress){
402 LOG.info("updatePeerAddress for peer {} with address {}", peerId,
404 if(peerAddresses.containsKey(peerId)){
405 peerAddresses.put(peerId, peerAddress);
406 if(LOG.isDebugEnabled()) {
408 "Sending PeerAddressResolved for peer {} with address {} to {}",
409 peerId, peerAddress, actor.path());
412 .tell(new PeerAddressResolved(peerId, peerAddress),
419 private static class ShardManagerCreator implements Creator<ShardManager> {
420 private static final long serialVersionUID = 1L;
423 final ClusterWrapper cluster;
424 final Configuration configuration;
425 final DatastoreContext datastoreContext;
427 ShardManagerCreator(String type, ClusterWrapper cluster,
428 Configuration configuration, DatastoreContext datastoreContext) {
430 this.cluster = cluster;
431 this.configuration = configuration;
432 this.datastoreContext = datastoreContext;
436 public ShardManager create() throws Exception {
437 return new ShardManager(type, cluster, configuration, datastoreContext);
441 static class SchemaContextModules implements Serializable {
442 private final Set<String> modules;
444 SchemaContextModules(Set<String> modules){
445 this.modules = modules;
448 public Set<String> getModules() {