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.common.actor.AbstractUntypedPersistentActorWithMetering;
30 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
31 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
32 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfo;
33 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfoMBean;
34 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
35 import org.opendaylight.controller.cluster.datastore.messages.ActorNotInitialized;
36 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
37 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
38 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
39 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
40 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
41 import org.opendaylight.controller.cluster.datastore.messages.PrimaryFound;
42 import org.opendaylight.controller.cluster.datastore.messages.PrimaryNotFound;
43 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
44 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
45 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
46 import scala.concurrent.duration.Duration;
47 import java.io.Serializable;
48 import java.util.ArrayList;
49 import java.util.Collection;
50 import java.util.HashMap;
51 import java.util.HashSet;
52 import java.util.List;
57 * The ShardManager has the following jobs,
59 * <li> Create all the local shard replicas that belong on this cluster member
60 * <li> Find the address of the local shard
61 * <li> Find the primary replica for any given shard
62 * <li> Monitor the cluster members and store their addresses
65 public class ShardManager extends AbstractUntypedPersistentActorWithMetering {
67 protected final LoggingAdapter LOG =
68 Logging.getLogger(getContext().system(), this);
70 // Stores a mapping between a member name and the address of the member
71 // Member names look like "member-1", "member-2" etc and are as specified
73 private final Map<String, Address> memberNameToAddress = new HashMap<>();
75 // Stores a mapping between a shard name and it's corresponding information
76 // Shard names look like inventory, topology etc and are as specified in
78 private final Map<String, ShardInformation> localShards = new HashMap<>();
80 // The type of a ShardManager reflects the type of the datastore itself
81 // A data store could be of type config/operational
82 private final String type;
84 private final ClusterWrapper cluster;
86 private final Configuration configuration;
88 private ShardManagerInfoMBean mBean;
90 private final DatastoreContext datastoreContext;
92 private final Collection<String> knownModules = new HashSet<>(128);
95 * @param type defines the kind of data that goes into shards created by this shard manager. Examples of type would be
96 * configuration or operational
98 protected ShardManager(String type, ClusterWrapper cluster, Configuration configuration,
99 DatastoreContext datastoreContext) {
101 this.type = Preconditions.checkNotNull(type, "type should not be null");
102 this.cluster = Preconditions.checkNotNull(cluster, "cluster should not be null");
103 this.configuration = Preconditions.checkNotNull(configuration, "configuration should not be null");
104 this.datastoreContext = datastoreContext;
106 // Subscribe this actor to cluster member events
107 cluster.subscribeToMemberEvents(getSelf());
112 public static Props props(final String type,
113 final ClusterWrapper cluster,
114 final Configuration configuration,
115 final DatastoreContext datastoreContext) {
117 Preconditions.checkNotNull(type, "type should not be null");
118 Preconditions.checkNotNull(cluster, "cluster should not be null");
119 Preconditions.checkNotNull(configuration, "configuration should not be null");
121 return Props.create(new ShardManagerCreator(type, cluster, configuration, datastoreContext));
125 public void handleCommand(Object message) throws Exception {
126 if (message.getClass().equals(FindPrimary.SERIALIZABLE_CLASS)) {
127 findPrimary(FindPrimary.fromSerializable(message));
128 } else if(message instanceof FindLocalShard){
129 findLocalShard((FindLocalShard) message);
130 } else if (message instanceof UpdateSchemaContext) {
131 updateSchemaContext(message);
132 } else if(message instanceof ActorInitialized) {
133 onActorInitialized(message);
134 } else if (message instanceof ClusterEvent.MemberUp){
135 memberUp((ClusterEvent.MemberUp) message);
136 } else if(message instanceof ClusterEvent.MemberRemoved) {
137 memberRemoved((ClusterEvent.MemberRemoved) message);
138 } else if(message instanceof ClusterEvent.UnreachableMember) {
139 ignoreMessage(message);
141 unknownMessage(message);
146 private void onActorInitialized(Object message) {
147 final ActorRef sender = getSender();
149 if (sender == null) {
150 return; //why is a non-actor sending this message? Just ignore.
153 String actorName = sender.path().name();
154 //find shard name from actor name; actor name is stringified shardId
155 ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(actorName).build();
157 if (shardId.getShardName() == null) {
160 markShardAsInitialized(shardId.getShardName());
163 private void markShardAsInitialized(String shardName) {
164 LOG.debug("Initializing shard [{}]", shardName);
165 ShardInformation shardInformation = localShards.get(shardName);
166 if (shardInformation != null) {
167 shardInformation.setActorInitialized();
172 protected void handleRecover(Object message) throws Exception {
173 if(message instanceof SchemaContextModules){
174 SchemaContextModules msg = (SchemaContextModules) message;
175 knownModules.clear();
176 knownModules.addAll(msg.getModules());
177 } else if(message instanceof RecoveryFailure){
178 RecoveryFailure failure = (RecoveryFailure) message;
179 LOG.error(failure.cause(), "Recovery failed");
180 } else if(message instanceof RecoveryCompleted){
181 LOG.info("Recovery complete : {}", persistenceId());
183 // Delete all the messages from the akka journal except the last one
184 deleteMessages(lastSequenceNr() - 1);
188 private void findLocalShard(FindLocalShard message) {
189 final ShardInformation shardInformation = localShards.get(message.getShardName());
191 if(shardInformation == null){
192 getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
196 sendResponse(shardInformation, message.isWaitUntilInitialized(), new Supplier<Object>() {
198 public Object get() {
199 return new LocalShardFound(shardInformation.getActor());
204 private void sendResponse(ShardInformation shardInformation, boolean waitUntilInitialized,
205 final Supplier<Object> messageSupplier) {
206 if (!shardInformation.isShardInitialized()) {
207 if(waitUntilInitialized) {
208 final ActorRef sender = getSender();
209 final ActorRef self = self();
210 shardInformation.addRunnableOnInitialized(new Runnable() {
213 sender.tell(messageSupplier.get(), self);
217 getSender().tell(new ActorNotInitialized(), getSelf());
223 getSender().tell(messageSupplier.get(), getSelf());
226 private void memberRemoved(ClusterEvent.MemberRemoved message) {
227 memberNameToAddress.remove(message.member().roles().head());
230 private void memberUp(ClusterEvent.MemberUp message) {
231 String memberName = message.member().roles().head();
233 memberNameToAddress.put(memberName, message.member().address());
235 for(ShardInformation info : localShards.values()){
236 String shardName = info.getShardName();
237 info.updatePeerAddress(getShardIdentifier(memberName, shardName),
238 getShardActorPath(shardName, memberName));
243 * Notifies all the local shards of a change in the schema context
247 private void updateSchemaContext(final Object message) {
248 final SchemaContext schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
250 Set<ModuleIdentifier> allModuleIdentifiers = schemaContext.getAllModuleIdentifiers();
251 Set<String> newModules = new HashSet<>(128);
253 for(ModuleIdentifier moduleIdentifier : allModuleIdentifiers){
254 String s = moduleIdentifier.getNamespace().toString();
258 if(newModules.containsAll(knownModules)) {
260 LOG.info("New SchemaContext has a super set of current knownModules - persisting info");
262 knownModules.clear();
263 knownModules.addAll(newModules);
265 persist(new SchemaContextModules(newModules), new Procedure<SchemaContextModules>() {
268 public void apply(SchemaContextModules param) throws Exception {
269 LOG.info("Sending new SchemaContext to Shards");
270 for (ShardInformation info : localShards.values()) {
271 if(info.getActor() == null) {
272 info.setActor(getContext().actorOf(Shard.props(info.getShardId(),
273 info.getPeerAddresses(), datastoreContext, schemaContext),
274 info.getShardId().toString()));
276 info.getActor().tell(message, getSelf());
283 LOG.info("Rejecting schema context update because it is not a super set of previously known modules");
288 private void findPrimary(FindPrimary message) {
289 String shardName = message.getShardName();
291 // First see if the there is a local replica for the shard
292 final ShardInformation info = localShards.get(shardName);
294 sendResponse(info, message.isWaitUntilInitialized(), new Supplier<Object>() {
296 public Object get() {
297 return new PrimaryFound(info.getActorPath().toString()).toSerializable();
304 List<String> members = configuration.getMembersFromShardName(shardName);
306 if(cluster.getCurrentMemberName() != null) {
307 members.remove(cluster.getCurrentMemberName());
311 * FIXME: Instead of sending remote shard actor path back to sender,
312 * forward FindPrimary message to remote shard manager
314 // There is no way for us to figure out the primary (for now) so assume
315 // that one of the remote nodes is a primary
316 for(String memberName : members) {
317 Address address = memberNameToAddress.get(memberName);
320 getShardActorPath(shardName, memberName);
321 getSender().tell(new PrimaryFound(path).toSerializable(), getSelf());
325 getSender().tell(new PrimaryNotFound(shardName).toSerializable(), getSelf());
328 private String getShardActorPath(String shardName, String memberName) {
329 Address address = memberNameToAddress.get(memberName);
330 if(address != null) {
331 StringBuilder builder = new StringBuilder();
332 builder.append(address.toString())
334 .append(ShardManagerIdentifier.builder().type(type).build().toString())
336 .append(getShardIdentifier(memberName, shardName));
337 return builder.toString();
343 * Construct the name of the shard actor given the name of the member on
344 * which the shard resides and the name of the shard
350 private ShardIdentifier getShardIdentifier(String memberName, String shardName){
351 return ShardIdentifier.builder().memberName(memberName).shardName(shardName).type(type).build();
355 * Create shards that are local to the member on which the ShardManager
359 private void createLocalShards() {
360 String memberName = this.cluster.getCurrentMemberName();
361 List<String> memberShardNames =
362 this.configuration.getMemberShardNames(memberName);
364 List<String> localShardActorNames = new ArrayList<>();
365 for(String shardName : memberShardNames){
366 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
367 Map<ShardIdentifier, String> peerAddresses = getPeerAddresses(shardName);
368 localShardActorNames.add(shardId.toString());
369 localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses));
372 mBean = ShardManagerInfo.createShardManagerMBean("shard-manager-" + this.type,
373 datastoreContext.getDataStoreMXBeanType(), localShardActorNames);
377 * Given the name of the shard find the addresses of all it's peers
382 private Map<ShardIdentifier, String> getPeerAddresses(String shardName){
384 Map<ShardIdentifier, String> peerAddresses = new HashMap<>();
386 List<String> members =
387 this.configuration.getMembersFromShardName(shardName);
389 String currentMemberName = this.cluster.getCurrentMemberName();
391 for(String memberName : members){
392 if(!currentMemberName.equals(memberName)){
393 ShardIdentifier shardId = getShardIdentifier(memberName,
396 getShardActorPath(shardName, currentMemberName);
397 peerAddresses.put(shardId, path);
400 return peerAddresses;
404 public SupervisorStrategy supervisorStrategy() {
406 return new OneForOneStrategy(10, Duration.create("1 minute"),
407 new Function<Throwable, SupervisorStrategy.Directive>() {
409 public SupervisorStrategy.Directive apply(Throwable t) {
410 StringBuilder sb = new StringBuilder();
411 for(StackTraceElement element : t.getStackTrace()) {
413 .append(element.toString());
415 LOG.warning("Supervisor Strategy of resume applied {}",sb.toString());
416 return SupervisorStrategy.resume();
424 public String persistenceId() {
425 return "shard-manager-" + type;
429 Collection<String> getKnownModules() {
433 private class ShardInformation {
434 private final ShardIdentifier shardId;
435 private final String shardName;
436 private ActorRef actor;
437 private ActorPath actorPath;
438 private final Map<ShardIdentifier, String> peerAddresses;
440 // flag that determines if the actor is ready for business
441 private boolean actorInitialized = false;
443 private final List<Runnable> runnablesOnInitialized = Lists.newArrayList();
445 private ShardInformation(String shardName, ShardIdentifier shardId,
446 Map<ShardIdentifier, String> peerAddresses) {
447 this.shardName = shardName;
448 this.shardId = shardId;
449 this.peerAddresses = peerAddresses;
452 String getShardName() {
460 ActorPath getActorPath() {
464 void setActor(ActorRef actor) {
466 this.actorPath = actor.path();
469 ShardIdentifier getShardId() {
473 Map<ShardIdentifier, String> getPeerAddresses() {
474 return peerAddresses;
477 void updatePeerAddress(ShardIdentifier peerId, String peerAddress){
478 LOG.info("updatePeerAddress for peer {} with address {}", peerId,
480 if(peerAddresses.containsKey(peerId)){
481 peerAddresses.put(peerId, peerAddress);
484 if(LOG.isDebugEnabled()) {
485 LOG.debug("Sending PeerAddressResolved for peer {} with address {} to {}",
486 peerId, peerAddress, actor.path());
489 actor.tell(new PeerAddressResolved(peerId, peerAddress), getSelf());
494 boolean isShardInitialized() {
495 return getActor() != null && actorInitialized;
498 void setActorInitialized() {
499 this.actorInitialized = true;
501 for(Runnable runnable: runnablesOnInitialized) {
505 runnablesOnInitialized.clear();
508 void addRunnableOnInitialized(Runnable runnable) {
509 runnablesOnInitialized.add(runnable);
513 private static class ShardManagerCreator implements Creator<ShardManager> {
514 private static final long serialVersionUID = 1L;
517 final ClusterWrapper cluster;
518 final Configuration configuration;
519 final DatastoreContext datastoreContext;
521 ShardManagerCreator(String type, ClusterWrapper cluster,
522 Configuration configuration, DatastoreContext datastoreContext) {
524 this.cluster = cluster;
525 this.configuration = configuration;
526 this.datastoreContext = datastoreContext;
530 public ShardManager create() throws Exception {
531 return new ShardManager(type, cluster, configuration, datastoreContext);
535 static class SchemaContextModules implements Serializable {
536 private final Set<String> modules;
538 SchemaContextModules(Set<String> modules){
539 this.modules = modules;
542 public Set<String> getModules() {