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.ImmutableSet;
29 import com.google.common.collect.Lists;
30 import java.io.Serializable;
31 import java.util.ArrayList;
32 import java.util.Collection;
33 import java.util.Collections;
34 import java.util.HashMap;
35 import java.util.HashSet;
36 import java.util.List;
39 import org.opendaylight.controller.cluster.DataPersistenceProvider;
40 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActorWithMetering;
41 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
42 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
43 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfo;
44 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfoMBean;
45 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
46 import org.opendaylight.controller.cluster.datastore.messages.ActorNotInitialized;
47 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
48 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
49 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
50 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
51 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
52 import org.opendaylight.controller.cluster.datastore.messages.PrimaryFound;
53 import org.opendaylight.controller.cluster.datastore.messages.PrimaryNotFound;
54 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
55 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
56 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
57 import scala.concurrent.duration.Duration;
60 * The ShardManager has the following jobs,
62 * <li> Create all the local shard replicas that belong on this cluster member
63 * <li> Find the address of the local shard
64 * <li> Find the primary replica for any given shard
65 * <li> Monitor the cluster members and store their addresses
68 public class ShardManager extends AbstractUntypedPersistentActorWithMetering {
70 protected final LoggingAdapter LOG =
71 Logging.getLogger(getContext().system(), this);
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
76 private final Map<String, Address> memberNameToAddress = new HashMap<>();
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
81 private final Map<String, ShardInformation> localShards = new HashMap<>();
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;
87 private final ClusterWrapper cluster;
89 private final Configuration configuration;
91 private ShardManagerInfoMBean mBean;
93 private final DatastoreContext datastoreContext;
95 private Collection<String> knownModules = Collections.emptySet();
97 private final DataPersistenceProvider dataPersistenceProvider;
100 * @param type defines the kind of data that goes into shards created by this shard manager. Examples of type would be
101 * configuration or operational
103 protected ShardManager(String type, ClusterWrapper cluster, Configuration configuration,
104 DatastoreContext datastoreContext) {
106 this.type = Preconditions.checkNotNull(type, "type should not be null");
107 this.cluster = Preconditions.checkNotNull(cluster, "cluster should not be null");
108 this.configuration = Preconditions.checkNotNull(configuration, "configuration should not be null");
109 this.datastoreContext = datastoreContext;
110 this.dataPersistenceProvider = createDataPersistenceProvider(datastoreContext.isPersistent());
112 // Subscribe this actor to cluster member events
113 cluster.subscribeToMemberEvents(getSelf());
118 protected DataPersistenceProvider createDataPersistenceProvider(boolean persistent) {
119 return (persistent) ? new PersistentDataProvider() : new NonPersistentDataProvider();
122 public static Props props(final String type,
123 final ClusterWrapper cluster,
124 final Configuration configuration,
125 final DatastoreContext datastoreContext) {
127 Preconditions.checkNotNull(type, "type should not be null");
128 Preconditions.checkNotNull(cluster, "cluster should not be null");
129 Preconditions.checkNotNull(configuration, "configuration should not be null");
131 return Props.create(new ShardManagerCreator(type, cluster, configuration, datastoreContext));
135 public void handleCommand(Object message) throws Exception {
136 if (message.getClass().equals(FindPrimary.SERIALIZABLE_CLASS)) {
137 findPrimary(FindPrimary.fromSerializable(message));
138 } else if(message instanceof FindLocalShard){
139 findLocalShard((FindLocalShard) message);
140 } else if (message instanceof UpdateSchemaContext) {
141 updateSchemaContext(message);
142 } else if(message instanceof ActorInitialized) {
143 onActorInitialized(message);
144 } else if (message instanceof ClusterEvent.MemberUp){
145 memberUp((ClusterEvent.MemberUp) message);
146 } else if(message instanceof ClusterEvent.MemberRemoved) {
147 memberRemoved((ClusterEvent.MemberRemoved) message);
148 } else if(message instanceof ClusterEvent.UnreachableMember) {
149 ignoreMessage(message);
151 unknownMessage(message);
156 private void onActorInitialized(Object message) {
157 final ActorRef sender = getSender();
159 if (sender == null) {
160 return; //why is a non-actor sending this message? Just ignore.
163 String actorName = sender.path().name();
164 //find shard name from actor name; actor name is stringified shardId
165 ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(actorName).build();
167 if (shardId.getShardName() == null) {
170 markShardAsInitialized(shardId.getShardName());
173 private void markShardAsInitialized(String shardName) {
174 LOG.debug("Initializing shard [{}]", shardName);
175 ShardInformation shardInformation = localShards.get(shardName);
176 if (shardInformation != null) {
177 shardInformation.setActorInitialized();
182 protected void handleRecover(Object message) throws Exception {
183 if(dataPersistenceProvider.isRecoveryApplicable()) {
184 if (message instanceof SchemaContextModules) {
185 SchemaContextModules msg = (SchemaContextModules) message;
186 knownModules = ImmutableSet.copyOf(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 = ImmutableSet.copyOf(newModules);
282 dataPersistenceProvider.persist(new SchemaContextModules(newModules), new Procedure<SchemaContextModules>() {
285 public void apply(SchemaContextModules param) throws Exception {
286 LOG.info("Sending new SchemaContext to Shards");
287 for (ShardInformation info : localShards.values()) {
288 if (info.getActor() == null) {
289 info.setActor(getContext().actorOf(Shard.props(info.getShardId(),
290 info.getPeerAddresses(), datastoreContext, schemaContext),
291 info.getShardId().toString()));
293 info.getActor().tell(message, getSelf());
300 LOG.info("Rejecting schema context update because it is not a super set of previously known modules");
305 private void findPrimary(FindPrimary message) {
306 String shardName = message.getShardName();
308 // First see if the there is a local replica for the shard
309 final ShardInformation info = localShards.get(shardName);
311 sendResponse(info, message.isWaitUntilInitialized(), new Supplier<Object>() {
313 public Object get() {
314 return new PrimaryFound(info.getActorPath().toString()).toSerializable();
321 List<String> members = configuration.getMembersFromShardName(shardName);
323 if(cluster.getCurrentMemberName() != null) {
324 members.remove(cluster.getCurrentMemberName());
328 * FIXME: Instead of sending remote shard actor path back to sender,
329 * forward FindPrimary message to remote shard manager
331 // There is no way for us to figure out the primary (for now) so assume
332 // that one of the remote nodes is a primary
333 for(String memberName : members) {
334 Address address = memberNameToAddress.get(memberName);
337 getShardActorPath(shardName, memberName);
338 getSender().tell(new PrimaryFound(path).toSerializable(), getSelf());
342 getSender().tell(new PrimaryNotFound(shardName).toSerializable(), getSelf());
345 private String getShardActorPath(String shardName, String memberName) {
346 Address address = memberNameToAddress.get(memberName);
347 if(address != null) {
348 StringBuilder builder = new StringBuilder();
349 builder.append(address.toString())
351 .append(ShardManagerIdentifier.builder().type(type).build().toString())
353 .append(getShardIdentifier(memberName, shardName));
354 return builder.toString();
360 * Construct the name of the shard actor given the name of the member on
361 * which the shard resides and the name of the shard
367 private ShardIdentifier getShardIdentifier(String memberName, String shardName){
368 return ShardIdentifier.builder().memberName(memberName).shardName(shardName).type(type).build();
372 * Create shards that are local to the member on which the ShardManager
376 private void createLocalShards() {
377 String memberName = this.cluster.getCurrentMemberName();
378 List<String> memberShardNames =
379 this.configuration.getMemberShardNames(memberName);
381 List<String> localShardActorNames = new ArrayList<>();
382 for(String shardName : memberShardNames){
383 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
384 Map<ShardIdentifier, String> peerAddresses = getPeerAddresses(shardName);
385 localShardActorNames.add(shardId.toString());
386 localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses));
389 mBean = ShardManagerInfo.createShardManagerMBean("shard-manager-" + this.type,
390 datastoreContext.getDataStoreMXBeanType(), localShardActorNames);
394 * Given the name of the shard find the addresses of all it's peers
399 private Map<ShardIdentifier, String> getPeerAddresses(String shardName){
401 Map<ShardIdentifier, String> peerAddresses = new HashMap<>();
403 List<String> members =
404 this.configuration.getMembersFromShardName(shardName);
406 String currentMemberName = this.cluster.getCurrentMemberName();
408 for(String memberName : members){
409 if(!currentMemberName.equals(memberName)){
410 ShardIdentifier shardId = getShardIdentifier(memberName,
413 getShardActorPath(shardName, currentMemberName);
414 peerAddresses.put(shardId, path);
417 return peerAddresses;
421 public SupervisorStrategy supervisorStrategy() {
423 return new OneForOneStrategy(10, Duration.create("1 minute"),
424 new Function<Throwable, SupervisorStrategy.Directive>() {
426 public SupervisorStrategy.Directive apply(Throwable t) {
427 StringBuilder sb = new StringBuilder();
428 for(StackTraceElement element : t.getStackTrace()) {
430 .append(element.toString());
432 LOG.warning("Supervisor Strategy of resume applied {}",sb.toString());
433 return SupervisorStrategy.resume();
441 public String persistenceId() {
442 return "shard-manager-" + type;
446 Collection<String> getKnownModules() {
451 DataPersistenceProvider getDataPersistenceProvider() {
452 return dataPersistenceProvider;
455 private class ShardInformation {
456 private final ShardIdentifier shardId;
457 private final String shardName;
458 private ActorRef actor;
459 private ActorPath actorPath;
460 private final Map<ShardIdentifier, String> peerAddresses;
462 // flag that determines if the actor is ready for business
463 private boolean actorInitialized = false;
465 private final List<Runnable> runnablesOnInitialized = Lists.newArrayList();
467 private ShardInformation(String shardName, ShardIdentifier shardId,
468 Map<ShardIdentifier, String> peerAddresses) {
469 this.shardName = shardName;
470 this.shardId = shardId;
471 this.peerAddresses = peerAddresses;
474 String getShardName() {
482 ActorPath getActorPath() {
486 void setActor(ActorRef actor) {
488 this.actorPath = actor.path();
491 ShardIdentifier getShardId() {
495 Map<ShardIdentifier, String> getPeerAddresses() {
496 return peerAddresses;
499 void updatePeerAddress(ShardIdentifier peerId, String peerAddress){
500 LOG.info("updatePeerAddress for peer {} with address {}", peerId,
502 if(peerAddresses.containsKey(peerId)){
503 peerAddresses.put(peerId, peerAddress);
506 if(LOG.isDebugEnabled()) {
507 LOG.debug("Sending PeerAddressResolved for peer {} with address {} to {}",
508 peerId, peerAddress, actor.path());
511 actor.tell(new PeerAddressResolved(peerId, peerAddress), getSelf());
516 boolean isShardInitialized() {
517 return getActor() != null && actorInitialized;
520 void setActorInitialized() {
521 this.actorInitialized = true;
523 for(Runnable runnable: runnablesOnInitialized) {
527 runnablesOnInitialized.clear();
530 void addRunnableOnInitialized(Runnable runnable) {
531 runnablesOnInitialized.add(runnable);
535 private static class ShardManagerCreator implements Creator<ShardManager> {
536 private static final long serialVersionUID = 1L;
539 final ClusterWrapper cluster;
540 final Configuration configuration;
541 final DatastoreContext datastoreContext;
543 ShardManagerCreator(String type, ClusterWrapper cluster,
544 Configuration configuration, DatastoreContext datastoreContext) {
546 this.cluster = cluster;
547 this.configuration = configuration;
548 this.datastoreContext = datastoreContext;
552 public ShardManager create() throws Exception {
553 return new ShardManager(type, cluster, configuration, datastoreContext);
557 static class SchemaContextModules implements Serializable {
558 private static final long serialVersionUID = -8884620101025936590L;
560 private final Set<String> modules;
562 SchemaContextModules(Set<String> modules){
563 this.modules = modules;
566 public Set<String> getModules() {