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.japi.Creator;
19 import akka.japi.Function;
20 import akka.japi.Procedure;
21 import akka.persistence.RecoveryCompleted;
22 import akka.persistence.RecoveryFailure;
23 import com.google.common.annotations.VisibleForTesting;
24 import com.google.common.base.Preconditions;
25 import com.google.common.base.Supplier;
26 import com.google.common.collect.ImmutableSet;
27 import com.google.common.collect.Lists;
28 import java.io.Serializable;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.HashMap;
33 import java.util.HashSet;
34 import java.util.List;
37 import org.opendaylight.controller.cluster.DataPersistenceProvider;
38 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActorWithMetering;
39 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
40 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
41 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfo;
42 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfoMBean;
43 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
44 import org.opendaylight.controller.cluster.datastore.messages.ActorNotInitialized;
45 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
46 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
47 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
48 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
49 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
50 import org.opendaylight.controller.cluster.datastore.messages.PrimaryFound;
51 import org.opendaylight.controller.cluster.datastore.messages.PrimaryNotFound;
52 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
53 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
54 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
55 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58 import scala.concurrent.duration.Duration;
61 * The ShardManager has the following jobs,
63 * <li> Create all the local shard replicas that belong on this cluster member
64 * <li> Find the address of the local shard
65 * <li> Find the primary replica for any given shard
66 * <li> Monitor the cluster members and store their addresses
69 public class ShardManager extends AbstractUntypedPersistentActorWithMetering {
71 private final Logger LOG = LoggerFactory.getLogger(getClass());
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 final String shardDispatcherPath;
93 private ShardManagerInfoMBean mBean;
95 private final DatastoreContext datastoreContext;
97 private Collection<String> knownModules = Collections.emptySet();
99 private final DataPersistenceProvider dataPersistenceProvider;
103 protected ShardManager(ClusterWrapper cluster, Configuration configuration,
104 DatastoreContext datastoreContext) {
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());
110 this.type = datastoreContext.getDataStoreType();
111 this.shardDispatcherPath =
112 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
114 // Subscribe this actor to cluster member events
115 cluster.subscribeToMemberEvents(getSelf());
120 protected DataPersistenceProvider createDataPersistenceProvider(boolean persistent) {
121 return (persistent) ? new PersistentDataProvider() : new NonPersistentDataProvider();
124 public static Props props(
125 final ClusterWrapper cluster,
126 final Configuration configuration,
127 final DatastoreContext datastoreContext) {
129 Preconditions.checkNotNull(cluster, "cluster should not be null");
130 Preconditions.checkNotNull(configuration, "configuration should not be null");
132 return Props.create(new ShardManagerCreator(cluster, configuration, datastoreContext));
136 public void handleCommand(Object message) throws Exception {
137 if (message.getClass().equals(FindPrimary.SERIALIZABLE_CLASS)) {
138 findPrimary(FindPrimary.fromSerializable(message));
139 } else if(message instanceof FindLocalShard){
140 findLocalShard((FindLocalShard) message);
141 } else if (message instanceof UpdateSchemaContext) {
142 updateSchemaContext(message);
143 } else if(message instanceof ActorInitialized) {
144 onActorInitialized(message);
145 } else if (message instanceof ClusterEvent.MemberUp){
146 memberUp((ClusterEvent.MemberUp) message);
147 } else if(message instanceof ClusterEvent.MemberRemoved) {
148 memberRemoved((ClusterEvent.MemberRemoved) message);
149 } else if(message instanceof ClusterEvent.UnreachableMember) {
150 ignoreMessage(message);
152 unknownMessage(message);
157 private void onActorInitialized(Object message) {
158 final ActorRef sender = getSender();
160 if (sender == null) {
161 return; //why is a non-actor sending this message? Just ignore.
164 String actorName = sender.path().name();
165 //find shard name from actor name; actor name is stringified shardId
166 ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(actorName).build();
168 if (shardId.getShardName() == null) {
171 markShardAsInitialized(shardId.getShardName());
174 private void markShardAsInitialized(String shardName) {
175 LOG.debug("Initializing shard [{}]", shardName);
176 ShardInformation shardInformation = localShards.get(shardName);
177 if (shardInformation != null) {
178 shardInformation.setActorInitialized();
183 protected void handleRecover(Object message) throws Exception {
184 if(dataPersistenceProvider.isRecoveryApplicable()) {
185 if (message instanceof SchemaContextModules) {
186 SchemaContextModules msg = (SchemaContextModules) message;
187 knownModules = ImmutableSet.copyOf(msg.getModules());
188 } else if (message instanceof RecoveryFailure) {
189 RecoveryFailure failure = (RecoveryFailure) message;
190 LOG.error("Recovery failed", failure.cause());
191 } else if (message instanceof RecoveryCompleted) {
192 LOG.info("Recovery complete : {}", persistenceId());
194 // Delete all the messages from the akka journal except the last one
195 deleteMessages(lastSequenceNr() - 1);
198 if (message instanceof RecoveryCompleted) {
199 LOG.info("Recovery complete : {}", persistenceId());
201 // Delete all the messages from the akka journal
202 deleteMessages(lastSequenceNr());
207 private void findLocalShard(FindLocalShard message) {
208 final ShardInformation shardInformation = localShards.get(message.getShardName());
210 if(shardInformation == null){
211 getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
215 sendResponse(shardInformation, message.isWaitUntilInitialized(), new Supplier<Object>() {
217 public Object get() {
218 return new LocalShardFound(shardInformation.getActor());
223 private void sendResponse(ShardInformation shardInformation, boolean waitUntilInitialized,
224 final Supplier<Object> messageSupplier) {
225 if (!shardInformation.isShardInitialized()) {
226 if(waitUntilInitialized) {
227 final ActorRef sender = getSender();
228 final ActorRef self = self();
229 shardInformation.addRunnableOnInitialized(new Runnable() {
232 sender.tell(messageSupplier.get(), self);
236 getSender().tell(new ActorNotInitialized(), getSelf());
242 getSender().tell(messageSupplier.get(), getSelf());
245 private void memberRemoved(ClusterEvent.MemberRemoved message) {
246 memberNameToAddress.remove(message.member().roles().head());
249 private void memberUp(ClusterEvent.MemberUp message) {
250 String memberName = message.member().roles().head();
252 memberNameToAddress.put(memberName, message.member().address());
254 for(ShardInformation info : localShards.values()){
255 String shardName = info.getShardName();
256 info.updatePeerAddress(getShardIdentifier(memberName, shardName),
257 getShardActorPath(shardName, memberName));
262 * Notifies all the local shards of a change in the schema context
266 private void updateSchemaContext(final Object message) {
267 final SchemaContext schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
269 Set<ModuleIdentifier> allModuleIdentifiers = schemaContext.getAllModuleIdentifiers();
270 Set<String> newModules = new HashSet<>(128);
272 for(ModuleIdentifier moduleIdentifier : allModuleIdentifiers){
273 String s = moduleIdentifier.getNamespace().toString();
277 if(newModules.containsAll(knownModules)) {
279 LOG.debug("New SchemaContext has a super set of current knownModules - persisting info");
281 knownModules = ImmutableSet.copyOf(newModules);
283 dataPersistenceProvider.persist(new SchemaContextModules(newModules), new Procedure<SchemaContextModules>() {
286 public void apply(SchemaContextModules param) throws Exception {
287 LOG.debug("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 .withDispatcher(shardDispatcherPath), info.getShardId().toString()));
294 info.getActor().tell(message, getSelf());
301 LOG.debug("Rejecting schema context update - not a super set of previously known modules:\nUPDATE: {}\nKNOWN: {}",
302 newModules, knownModules);
307 private void findPrimary(FindPrimary message) {
308 String shardName = message.getShardName();
310 // First see if the there is a local replica for the shard
311 final ShardInformation info = localShards.get(shardName);
313 sendResponse(info, message.isWaitUntilInitialized(), new Supplier<Object>() {
315 public Object get() {
316 return new PrimaryFound(info.getActorPath().toString()).toSerializable();
323 List<String> members = configuration.getMembersFromShardName(shardName);
325 if(cluster.getCurrentMemberName() != null) {
326 members.remove(cluster.getCurrentMemberName());
330 * FIXME: Instead of sending remote shard actor path back to sender,
331 * forward FindPrimary message to remote shard manager
333 // There is no way for us to figure out the primary (for now) so assume
334 // that one of the remote nodes is a primary
335 for(String memberName : members) {
336 Address address = memberNameToAddress.get(memberName);
339 getShardActorPath(shardName, memberName);
340 getSender().tell(new PrimaryFound(path).toSerializable(), getSelf());
344 getSender().tell(new PrimaryNotFound(shardName).toSerializable(), getSelf());
347 private String getShardActorPath(String shardName, String memberName) {
348 Address address = memberNameToAddress.get(memberName);
349 if(address != null) {
350 StringBuilder builder = new StringBuilder();
351 builder.append(address.toString())
353 .append(ShardManagerIdentifier.builder().type(type).build().toString())
355 .append(getShardIdentifier(memberName, shardName));
356 return builder.toString();
362 * Construct the name of the shard actor given the name of the member on
363 * which the shard resides and the name of the shard
369 private ShardIdentifier getShardIdentifier(String memberName, String shardName){
370 return ShardIdentifier.builder().memberName(memberName).shardName(shardName).type(type).build();
374 * Create shards that are local to the member on which the ShardManager
378 private void createLocalShards() {
379 String memberName = this.cluster.getCurrentMemberName();
380 List<String> memberShardNames =
381 this.configuration.getMemberShardNames(memberName);
383 List<String> localShardActorNames = new ArrayList<>();
384 for(String shardName : memberShardNames){
385 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
386 Map<ShardIdentifier, String> peerAddresses = getPeerAddresses(shardName);
387 localShardActorNames.add(shardId.toString());
388 localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses));
391 mBean = ShardManagerInfo.createShardManagerMBean("shard-manager-" + this.type,
392 datastoreContext.getDataStoreMXBeanType(), localShardActorNames);
396 * Given the name of the shard find the addresses of all it's peers
401 private Map<ShardIdentifier, String> getPeerAddresses(String shardName){
403 Map<ShardIdentifier, String> peerAddresses = new HashMap<>();
405 List<String> members =
406 this.configuration.getMembersFromShardName(shardName);
408 String currentMemberName = this.cluster.getCurrentMemberName();
410 for(String memberName : members){
411 if(!currentMemberName.equals(memberName)){
412 ShardIdentifier shardId = getShardIdentifier(memberName,
415 getShardActorPath(shardName, currentMemberName);
416 peerAddresses.put(shardId, path);
419 return peerAddresses;
423 public SupervisorStrategy supervisorStrategy() {
425 return new OneForOneStrategy(10, Duration.create("1 minute"),
426 new Function<Throwable, SupervisorStrategy.Directive>() {
428 public SupervisorStrategy.Directive apply(Throwable t) {
429 LOG.warn("Supervisor Strategy caught unexpected exception - resuming", t);
430 return SupervisorStrategy.resume();
438 public String persistenceId() {
439 return "shard-manager-" + type;
443 Collection<String> getKnownModules() {
448 DataPersistenceProvider getDataPersistenceProvider() {
449 return dataPersistenceProvider;
452 private class ShardInformation {
453 private final ShardIdentifier shardId;
454 private final String shardName;
455 private ActorRef actor;
456 private ActorPath actorPath;
457 private final Map<ShardIdentifier, String> peerAddresses;
459 // flag that determines if the actor is ready for business
460 private boolean actorInitialized = false;
462 private final List<Runnable> runnablesOnInitialized = Lists.newArrayList();
464 private ShardInformation(String shardName, ShardIdentifier shardId,
465 Map<ShardIdentifier, String> peerAddresses) {
466 this.shardName = shardName;
467 this.shardId = shardId;
468 this.peerAddresses = peerAddresses;
471 String getShardName() {
479 ActorPath getActorPath() {
483 void setActor(ActorRef actor) {
485 this.actorPath = actor.path();
488 ShardIdentifier getShardId() {
492 Map<ShardIdentifier, String> getPeerAddresses() {
493 return peerAddresses;
496 void updatePeerAddress(ShardIdentifier peerId, String peerAddress){
497 LOG.info("updatePeerAddress for peer {} with address {}", peerId,
499 if(peerAddresses.containsKey(peerId)){
500 peerAddresses.put(peerId, peerAddress);
503 if(LOG.isDebugEnabled()) {
504 LOG.debug("Sending PeerAddressResolved for peer {} with address {} to {}",
505 peerId, peerAddress, actor.path());
508 actor.tell(new PeerAddressResolved(peerId, peerAddress), getSelf());
513 boolean isShardInitialized() {
514 return getActor() != null && actorInitialized;
517 void setActorInitialized() {
518 this.actorInitialized = true;
520 for(Runnable runnable: runnablesOnInitialized) {
524 runnablesOnInitialized.clear();
527 void addRunnableOnInitialized(Runnable runnable) {
528 runnablesOnInitialized.add(runnable);
532 private static class ShardManagerCreator implements Creator<ShardManager> {
533 private static final long serialVersionUID = 1L;
535 final ClusterWrapper cluster;
536 final Configuration configuration;
537 final DatastoreContext datastoreContext;
539 ShardManagerCreator(ClusterWrapper cluster,
540 Configuration configuration, DatastoreContext datastoreContext) {
541 this.cluster = cluster;
542 this.configuration = configuration;
543 this.datastoreContext = datastoreContext;
547 public ShardManager create() throws Exception {
548 return new ShardManager(cluster, configuration, datastoreContext);
552 static class SchemaContextModules implements Serializable {
553 private static final long serialVersionUID = -8884620101025936590L;
555 private final Set<String> modules;
557 SchemaContextModules(Set<String> modules){
558 this.modules = modules;
561 public Set<String> getModules() {