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 com.google.common.base.Supplier;
28 import com.google.common.collect.Lists;
29 import org.opendaylight.controller.cluster.DataPersistenceProvider;
30 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActorWithMetering;
31 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
32 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
33 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfo;
34 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfoMBean;
35 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
36 import org.opendaylight.controller.cluster.datastore.messages.ActorNotInitialized;
37 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
38 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
39 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
40 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
41 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
42 import org.opendaylight.controller.cluster.datastore.messages.PrimaryFound;
43 import org.opendaylight.controller.cluster.datastore.messages.PrimaryNotFound;
44 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
45 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
46 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
47 import scala.concurrent.duration.Duration;
49 import java.io.Serializable;
50 import java.util.ArrayList;
51 import java.util.Collection;
52 import java.util.HashMap;
53 import java.util.HashSet;
54 import java.util.List;
59 * The ShardManager has the following jobs,
61 * <li> Create all the local shard replicas that belong on this cluster member
62 * <li> Find the address of the local shard
63 * <li> Find the primary replica for any given shard
64 * <li> Monitor the cluster members and store their addresses
67 public class ShardManager extends AbstractUntypedPersistentActorWithMetering {
69 protected final LoggingAdapter LOG =
70 Logging.getLogger(getContext().system(), this);
72 // Stores a mapping between a member name and the address of the member
73 // Member names look like "member-1", "member-2" etc and are as specified
75 private final Map<String, Address> memberNameToAddress = new HashMap<>();
77 // Stores a mapping between a shard name and it's corresponding information
78 // Shard names look like inventory, topology etc and are as specified in
80 private final Map<String, ShardInformation> localShards = new HashMap<>();
82 // The type of a ShardManager reflects the type of the datastore itself
83 // A data store could be of type config/operational
84 private final String type;
86 private final ClusterWrapper cluster;
88 private final Configuration configuration;
90 private ShardManagerInfoMBean mBean;
92 private final DatastoreContext datastoreContext;
94 private final Collection<String> knownModules = new HashSet<>(128);
96 private final DataPersistenceProvider dataPersistenceProvider;
99 * @param type defines the kind of data that goes into shards created by this shard manager. Examples of type would be
100 * configuration or operational
102 protected ShardManager(String type, ClusterWrapper cluster, Configuration configuration,
103 DatastoreContext datastoreContext) {
105 this.type = Preconditions.checkNotNull(type, "type should not be null");
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());
111 // Subscribe this actor to cluster member events
112 cluster.subscribeToMemberEvents(getSelf());
117 protected DataPersistenceProvider createDataPersistenceProvider(boolean persistent) {
118 return (persistent) ? new PersistentDataProvider() : new NonPersistentDataProvider();
121 public static Props props(final String type,
122 final ClusterWrapper cluster,
123 final Configuration configuration,
124 final DatastoreContext datastoreContext) {
126 Preconditions.checkNotNull(type, "type should not be null");
127 Preconditions.checkNotNull(cluster, "cluster should not be null");
128 Preconditions.checkNotNull(configuration, "configuration should not be null");
130 return Props.create(new ShardManagerCreator(type, cluster, configuration, datastoreContext));
134 public void handleCommand(Object message) throws Exception {
135 if (message.getClass().equals(FindPrimary.SERIALIZABLE_CLASS)) {
136 findPrimary(FindPrimary.fromSerializable(message));
137 } else if(message instanceof FindLocalShard){
138 findLocalShard((FindLocalShard) message);
139 } else if (message instanceof UpdateSchemaContext) {
140 updateSchemaContext(message);
141 } else if(message instanceof ActorInitialized) {
142 onActorInitialized(message);
143 } else if (message instanceof ClusterEvent.MemberUp){
144 memberUp((ClusterEvent.MemberUp) message);
145 } else if(message instanceof ClusterEvent.MemberRemoved) {
146 memberRemoved((ClusterEvent.MemberRemoved) message);
147 } else if(message instanceof ClusterEvent.UnreachableMember) {
148 ignoreMessage(message);
150 unknownMessage(message);
155 private void onActorInitialized(Object message) {
156 final ActorRef sender = getSender();
158 if (sender == null) {
159 return; //why is a non-actor sending this message? Just ignore.
162 String actorName = sender.path().name();
163 //find shard name from actor name; actor name is stringified shardId
164 ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(actorName).build();
166 if (shardId.getShardName() == null) {
169 markShardAsInitialized(shardId.getShardName());
172 private void markShardAsInitialized(String shardName) {
173 LOG.debug("Initializing shard [{}]", shardName);
174 ShardInformation shardInformation = localShards.get(shardName);
175 if (shardInformation != null) {
176 shardInformation.setActorInitialized();
181 protected void handleRecover(Object message) throws Exception {
182 if(dataPersistenceProvider.isRecoveryApplicable()) {
183 if (message instanceof SchemaContextModules) {
184 SchemaContextModules msg = (SchemaContextModules) message;
185 knownModules.clear();
186 knownModules.addAll(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());
193 // Delete all the messages from the akka journal except the last one
194 deleteMessages(lastSequenceNr() - 1);
197 if (message instanceof RecoveryCompleted) {
198 LOG.info("Recovery complete : {}", persistenceId());
200 // Delete all the messages from the akka journal
201 deleteMessages(lastSequenceNr());
206 private void findLocalShard(FindLocalShard message) {
207 final ShardInformation shardInformation = localShards.get(message.getShardName());
209 if(shardInformation == null){
210 getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
214 sendResponse(shardInformation, message.isWaitUntilInitialized(), new Supplier<Object>() {
216 public Object get() {
217 return new LocalShardFound(shardInformation.getActor());
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() {
231 sender.tell(messageSupplier.get(), self);
235 getSender().tell(new ActorNotInitialized(), getSelf());
241 getSender().tell(messageSupplier.get(), getSelf());
244 private void memberRemoved(ClusterEvent.MemberRemoved message) {
245 memberNameToAddress.remove(message.member().roles().head());
248 private void memberUp(ClusterEvent.MemberUp message) {
249 String memberName = message.member().roles().head();
251 memberNameToAddress.put(memberName, message.member().address());
253 for(ShardInformation info : localShards.values()){
254 String shardName = info.getShardName();
255 info.updatePeerAddress(getShardIdentifier(memberName, shardName),
256 getShardActorPath(shardName, memberName));
261 * Notifies all the local shards of a change in the schema context
265 private void updateSchemaContext(final Object message) {
266 final SchemaContext schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
268 Set<ModuleIdentifier> allModuleIdentifiers = schemaContext.getAllModuleIdentifiers();
269 Set<String> newModules = new HashSet<>(128);
271 for(ModuleIdentifier moduleIdentifier : allModuleIdentifiers){
272 String s = moduleIdentifier.getNamespace().toString();
276 if(newModules.containsAll(knownModules)) {
278 LOG.info("New SchemaContext has a super set of current knownModules - persisting info");
280 knownModules.clear();
281 knownModules.addAll(newModules);
283 dataPersistenceProvider.persist(new SchemaContextModules(newModules), new Procedure<SchemaContextModules>() {
286 public void apply(SchemaContextModules param) throws Exception {
287 LOG.info("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 info.getShardId().toString()));
294 info.getActor().tell(message, getSelf());
301 LOG.info("Rejecting schema context update because it is not a super set of previously known modules");
306 private void findPrimary(FindPrimary message) {
307 String shardName = message.getShardName();
309 // First see if the there is a local replica for the shard
310 final ShardInformation info = localShards.get(shardName);
312 sendResponse(info, message.isWaitUntilInitialized(), new Supplier<Object>() {
314 public Object get() {
315 return new PrimaryFound(info.getActorPath().toString()).toSerializable();
322 List<String> members = configuration.getMembersFromShardName(shardName);
324 if(cluster.getCurrentMemberName() != null) {
325 members.remove(cluster.getCurrentMemberName());
329 * FIXME: Instead of sending remote shard actor path back to sender,
330 * forward FindPrimary message to remote shard manager
332 // There is no way for us to figure out the primary (for now) so assume
333 // that one of the remote nodes is a primary
334 for(String memberName : members) {
335 Address address = memberNameToAddress.get(memberName);
338 getShardActorPath(shardName, memberName);
339 getSender().tell(new PrimaryFound(path).toSerializable(), getSelf());
343 getSender().tell(new PrimaryNotFound(shardName).toSerializable(), getSelf());
346 private String getShardActorPath(String shardName, String memberName) {
347 Address address = memberNameToAddress.get(memberName);
348 if(address != null) {
349 StringBuilder builder = new StringBuilder();
350 builder.append(address.toString())
352 .append(ShardManagerIdentifier.builder().type(type).build().toString())
354 .append(getShardIdentifier(memberName, shardName));
355 return builder.toString();
361 * Construct the name of the shard actor given the name of the member on
362 * which the shard resides and the name of the shard
368 private ShardIdentifier getShardIdentifier(String memberName, String shardName){
369 return ShardIdentifier.builder().memberName(memberName).shardName(shardName).type(type).build();
373 * Create shards that are local to the member on which the ShardManager
377 private void createLocalShards() {
378 String memberName = this.cluster.getCurrentMemberName();
379 List<String> memberShardNames =
380 this.configuration.getMemberShardNames(memberName);
382 List<String> localShardActorNames = new ArrayList<>();
383 for(String shardName : memberShardNames){
384 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
385 Map<ShardIdentifier, String> peerAddresses = getPeerAddresses(shardName);
386 localShardActorNames.add(shardId.toString());
387 localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses));
390 mBean = ShardManagerInfo.createShardManagerMBean("shard-manager-" + this.type,
391 datastoreContext.getDataStoreMXBeanType(), localShardActorNames);
395 * Given the name of the shard find the addresses of all it's peers
400 private Map<ShardIdentifier, String> getPeerAddresses(String shardName){
402 Map<ShardIdentifier, String> peerAddresses = new HashMap<>();
404 List<String> members =
405 this.configuration.getMembersFromShardName(shardName);
407 String currentMemberName = this.cluster.getCurrentMemberName();
409 for(String memberName : members){
410 if(!currentMemberName.equals(memberName)){
411 ShardIdentifier shardId = getShardIdentifier(memberName,
414 getShardActorPath(shardName, currentMemberName);
415 peerAddresses.put(shardId, path);
418 return peerAddresses;
422 public SupervisorStrategy supervisorStrategy() {
424 return new OneForOneStrategy(10, Duration.create("1 minute"),
425 new Function<Throwable, SupervisorStrategy.Directive>() {
427 public SupervisorStrategy.Directive apply(Throwable t) {
428 StringBuilder sb = new StringBuilder();
429 for(StackTraceElement element : t.getStackTrace()) {
431 .append(element.toString());
433 LOG.warning("Supervisor Strategy of resume applied {}",sb.toString());
434 return SupervisorStrategy.resume();
442 public String persistenceId() {
443 return "shard-manager-" + type;
447 Collection<String> getKnownModules() {
452 DataPersistenceProvider getDataPersistenceProvider() {
453 return dataPersistenceProvider;
456 private class ShardInformation {
457 private final ShardIdentifier shardId;
458 private final String shardName;
459 private ActorRef actor;
460 private ActorPath actorPath;
461 private final Map<ShardIdentifier, String> peerAddresses;
463 // flag that determines if the actor is ready for business
464 private boolean actorInitialized = false;
466 private final List<Runnable> runnablesOnInitialized = Lists.newArrayList();
468 private ShardInformation(String shardName, ShardIdentifier shardId,
469 Map<ShardIdentifier, String> peerAddresses) {
470 this.shardName = shardName;
471 this.shardId = shardId;
472 this.peerAddresses = peerAddresses;
475 String getShardName() {
483 ActorPath getActorPath() {
487 void setActor(ActorRef actor) {
489 this.actorPath = actor.path();
492 ShardIdentifier getShardId() {
496 Map<ShardIdentifier, String> getPeerAddresses() {
497 return peerAddresses;
500 void updatePeerAddress(ShardIdentifier peerId, String peerAddress){
501 LOG.info("updatePeerAddress for peer {} with address {}", peerId,
503 if(peerAddresses.containsKey(peerId)){
504 peerAddresses.put(peerId, peerAddress);
507 if(LOG.isDebugEnabled()) {
508 LOG.debug("Sending PeerAddressResolved for peer {} with address {} to {}",
509 peerId, peerAddress, actor.path());
512 actor.tell(new PeerAddressResolved(peerId, peerAddress), getSelf());
517 boolean isShardInitialized() {
518 return getActor() != null && actorInitialized;
521 void setActorInitialized() {
522 this.actorInitialized = true;
524 for(Runnable runnable: runnablesOnInitialized) {
528 runnablesOnInitialized.clear();
531 void addRunnableOnInitialized(Runnable runnable) {
532 runnablesOnInitialized.add(runnable);
536 private static class ShardManagerCreator implements Creator<ShardManager> {
537 private static final long serialVersionUID = 1L;
540 final ClusterWrapper cluster;
541 final Configuration configuration;
542 final DatastoreContext datastoreContext;
544 ShardManagerCreator(String type, ClusterWrapper cluster,
545 Configuration configuration, DatastoreContext datastoreContext) {
547 this.cluster = cluster;
548 this.configuration = configuration;
549 this.datastoreContext = datastoreContext;
553 public ShardManager create() throws Exception {
554 return new ShardManager(type, cluster, configuration, datastoreContext);
558 static class SchemaContextModules implements Serializable {
559 private static final long serialVersionUID = 1L;
560 private final Set<String> modules;
562 SchemaContextModules(Set<String> modules){
563 this.modules = modules;
566 public Set<String> getModules() {