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 org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActorWithMetering;
29 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
30 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
31 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfo;
32 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfoMBean;
33 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
34 import org.opendaylight.controller.cluster.datastore.messages.ActorNotInitialized;
35 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
36 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
37 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
38 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
39 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
40 import org.opendaylight.controller.cluster.datastore.messages.PrimaryFound;
41 import org.opendaylight.controller.cluster.datastore.messages.PrimaryNotFound;
42 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
43 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
44 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
45 import scala.concurrent.duration.Duration;
46 import java.io.Serializable;
47 import java.util.ArrayList;
48 import java.util.Collection;
49 import java.util.HashMap;
50 import java.util.HashSet;
51 import java.util.List;
56 * The ShardManager has the following jobs,
58 * <li> Create all the local shard replicas that belong on this cluster member
59 * <li> Find the address of the local shard
60 * <li> Find the primary replica for any given shard
61 * <li> Monitor the cluster members and store their addresses
64 public class ShardManager extends AbstractUntypedPersistentActorWithMetering {
66 protected final LoggingAdapter LOG =
67 Logging.getLogger(getContext().system(), this);
69 // Stores a mapping between a member name and the address of the member
70 // Member names look like "member-1", "member-2" etc and are as specified
72 private final Map<String, Address> memberNameToAddress = new HashMap<>();
74 // Stores a mapping between a shard name and it's corresponding information
75 // Shard names look like inventory, topology etc and are as specified in
77 private final Map<String, ShardInformation> localShards = new HashMap<>();
79 // The type of a ShardManager reflects the type of the datastore itself
80 // A data store could be of type config/operational
81 private final String type;
83 private final ClusterWrapper cluster;
85 private final Configuration configuration;
87 private ShardManagerInfoMBean mBean;
89 private final DatastoreContext datastoreContext;
91 private final Collection<String> knownModules = new HashSet<>(128);
94 * @param type defines the kind of data that goes into shards created by this shard manager. Examples of type would be
95 * configuration or operational
97 protected ShardManager(String type, ClusterWrapper cluster, Configuration configuration,
98 DatastoreContext datastoreContext) {
100 this.type = Preconditions.checkNotNull(type, "type should not be null");
101 this.cluster = Preconditions.checkNotNull(cluster, "cluster should not be null");
102 this.configuration = Preconditions.checkNotNull(configuration, "configuration should not be null");
103 this.datastoreContext = datastoreContext;
105 // Subscribe this actor to cluster member events
106 cluster.subscribeToMemberEvents(getSelf());
111 public static Props props(final String type,
112 final ClusterWrapper cluster,
113 final Configuration configuration,
114 final DatastoreContext datastoreContext) {
116 Preconditions.checkNotNull(type, "type should not be null");
117 Preconditions.checkNotNull(cluster, "cluster should not be null");
118 Preconditions.checkNotNull(configuration, "configuration should not be null");
120 return Props.create(new ShardManagerCreator(type, cluster, configuration, datastoreContext));
124 public void handleCommand(Object message) throws Exception {
125 if (message.getClass().equals(FindPrimary.SERIALIZABLE_CLASS)) {
126 findPrimary(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 ActorInitialized) {
132 onActorInitialized(message);
133 } else if (message instanceof ClusterEvent.MemberUp){
134 memberUp((ClusterEvent.MemberUp) message);
135 } else if(message instanceof ClusterEvent.MemberRemoved) {
136 memberRemoved((ClusterEvent.MemberRemoved) message);
137 } else if(message instanceof ClusterEvent.UnreachableMember) {
138 ignoreMessage(message);
140 unknownMessage(message);
145 private void onActorInitialized(Object message) {
146 final ActorRef sender = getSender();
148 if (sender == null) {
149 return; //why is a non-actor sending this message? Just ignore.
152 String actorName = sender.path().name();
153 //find shard name from actor name; actor name is stringified shardId
154 ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(actorName).build();
156 if (shardId.getShardName() == null) {
159 markShardAsInitialized(shardId.getShardName());
162 private void markShardAsInitialized(String shardName) {
163 LOG.debug("Initializing shard [{}]", shardName);
164 ShardInformation shardInformation = localShards.get(shardName);
165 if (shardInformation != null) {
166 shardInformation.setShardInitialized(true);
171 protected void handleRecover(Object message) throws Exception {
172 if(message instanceof SchemaContextModules){
173 SchemaContextModules msg = (SchemaContextModules) message;
174 knownModules.clear();
175 knownModules.addAll(msg.getModules());
176 } else if(message instanceof RecoveryFailure){
177 RecoveryFailure failure = (RecoveryFailure) message;
178 LOG.error(failure.cause(), "Recovery failed");
179 } else if(message instanceof RecoveryCompleted){
180 LOG.info("Recovery complete : {}", persistenceId());
182 // Delete all the messages from the akka journal except the last one
183 deleteMessages(lastSequenceNr() - 1);
187 private void findLocalShard(FindLocalShard message) {
188 final ShardInformation shardInformation = localShards.get(message.getShardName());
190 if(shardInformation == null){
191 getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
195 sendResponse(shardInformation, new Supplier<Object>() {
197 public Object get() {
198 return new LocalShardFound(shardInformation.getActor());
203 private void sendResponse(ShardInformation shardInformation, Supplier<Object> messageSupplier) {
204 if (shardInformation.getActor() == null || !shardInformation.isShardInitialized()) {
205 getSender().tell(new ActorNotInitialized(), getSelf());
209 getSender().tell(messageSupplier.get(), getSelf());
212 private void memberRemoved(ClusterEvent.MemberRemoved message) {
213 memberNameToAddress.remove(message.member().roles().head());
216 private void memberUp(ClusterEvent.MemberUp message) {
217 String memberName = message.member().roles().head();
219 memberNameToAddress.put(memberName, message.member().address());
221 for(ShardInformation info : localShards.values()){
222 String shardName = info.getShardName();
223 info.updatePeerAddress(getShardIdentifier(memberName, shardName),
224 getShardActorPath(shardName, memberName));
229 * Notifies all the local shards of a change in the schema context
233 private void updateSchemaContext(final Object message) {
234 final SchemaContext schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
236 Set<ModuleIdentifier> allModuleIdentifiers = schemaContext.getAllModuleIdentifiers();
237 Set<String> newModules = new HashSet<>(128);
239 for(ModuleIdentifier moduleIdentifier : allModuleIdentifiers){
240 String s = moduleIdentifier.getNamespace().toString();
244 if(newModules.containsAll(knownModules)) {
246 LOG.info("New SchemaContext has a super set of current knownModules - persisting info");
248 knownModules.clear();
249 knownModules.addAll(newModules);
251 persist(new SchemaContextModules(newModules), new Procedure<SchemaContextModules>() {
254 public void apply(SchemaContextModules param) throws Exception {
255 LOG.info("Sending new SchemaContext to Shards");
256 for (ShardInformation info : localShards.values()) {
257 if(info.getActor() == null) {
258 info.setActor(getContext().actorOf(Shard.props(info.getShardId(),
259 info.getPeerAddresses(), datastoreContext, schemaContext),
260 info.getShardId().toString()));
262 info.getActor().tell(message, getSelf());
269 LOG.info("Rejecting schema context update because it is not a super set of previously known modules");
274 private void findPrimary(FindPrimary message) {
275 String shardName = message.getShardName();
277 // First see if the there is a local replica for the shard
278 final ShardInformation info = localShards.get(shardName);
280 sendResponse(info, new Supplier<Object>() {
282 public Object get() {
283 return new PrimaryFound(info.getActorPath().toString()).toSerializable();
290 List<String> members = configuration.getMembersFromShardName(shardName);
292 if(cluster.getCurrentMemberName() != null) {
293 members.remove(cluster.getCurrentMemberName());
297 * FIXME: Instead of sending remote shard actor path back to sender,
298 * forward FindPrimary message to remote shard manager
300 // There is no way for us to figure out the primary (for now) so assume
301 // that one of the remote nodes is a primary
302 for(String memberName : members) {
303 Address address = memberNameToAddress.get(memberName);
306 getShardActorPath(shardName, memberName);
307 getSender().tell(new PrimaryFound(path).toSerializable(), getSelf());
311 getSender().tell(new PrimaryNotFound(shardName).toSerializable(), getSelf());
314 private String getShardActorPath(String shardName, String memberName) {
315 Address address = memberNameToAddress.get(memberName);
316 if(address != null) {
317 StringBuilder builder = new StringBuilder();
318 builder.append(address.toString())
320 .append(ShardManagerIdentifier.builder().type(type).build().toString())
322 .append(getShardIdentifier(memberName, shardName));
323 return builder.toString();
329 * Construct the name of the shard actor given the name of the member on
330 * which the shard resides and the name of the shard
336 private ShardIdentifier getShardIdentifier(String memberName, String shardName){
337 return ShardIdentifier.builder().memberName(memberName).shardName(shardName).type(type).build();
341 * Create shards that are local to the member on which the ShardManager
345 private void createLocalShards() {
346 String memberName = this.cluster.getCurrentMemberName();
347 List<String> memberShardNames =
348 this.configuration.getMemberShardNames(memberName);
350 List<String> localShardActorNames = new ArrayList<>();
351 for(String shardName : memberShardNames){
352 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
353 Map<ShardIdentifier, String> peerAddresses = getPeerAddresses(shardName);
354 localShardActorNames.add(shardId.toString());
355 localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses));
358 mBean = ShardManagerInfo.createShardManagerMBean("shard-manager-" + this.type,
359 datastoreContext.getDataStoreMXBeanType(), localShardActorNames);
363 * Given the name of the shard find the addresses of all it's peers
368 private Map<ShardIdentifier, String> getPeerAddresses(String shardName){
370 Map<ShardIdentifier, String> peerAddresses = new HashMap<>();
372 List<String> members =
373 this.configuration.getMembersFromShardName(shardName);
375 String currentMemberName = this.cluster.getCurrentMemberName();
377 for(String memberName : members){
378 if(!currentMemberName.equals(memberName)){
379 ShardIdentifier shardId = getShardIdentifier(memberName,
382 getShardActorPath(shardName, currentMemberName);
383 peerAddresses.put(shardId, path);
386 return peerAddresses;
390 public SupervisorStrategy supervisorStrategy() {
392 return new OneForOneStrategy(10, Duration.create("1 minute"),
393 new Function<Throwable, SupervisorStrategy.Directive>() {
395 public SupervisorStrategy.Directive apply(Throwable t) {
396 StringBuilder sb = new StringBuilder();
397 for(StackTraceElement element : t.getStackTrace()) {
399 .append(element.toString());
401 LOG.warning("Supervisor Strategy of resume applied {}",sb.toString());
402 return SupervisorStrategy.resume();
410 public String persistenceId() {
411 return "shard-manager-" + type;
415 Collection<String> getKnownModules() {
419 private class ShardInformation {
420 private final ShardIdentifier shardId;
421 private final String shardName;
422 private ActorRef actor;
423 private ActorPath actorPath;
424 private final Map<ShardIdentifier, String> peerAddresses;
425 private boolean shardInitialized = false; // flag that determines if the actor is ready for business
427 private ShardInformation(String shardName, ShardIdentifier shardId,
428 Map<ShardIdentifier, String> peerAddresses) {
429 this.shardName = shardName;
430 this.shardId = shardId;
431 this.peerAddresses = peerAddresses;
434 String getShardName() {
442 ActorPath getActorPath() {
446 void setActor(ActorRef actor) {
448 this.actorPath = actor.path();
451 ShardIdentifier getShardId() {
455 Map<ShardIdentifier, String> getPeerAddresses() {
456 return peerAddresses;
459 void updatePeerAddress(ShardIdentifier peerId, String peerAddress){
460 LOG.info("updatePeerAddress for peer {} with address {}", peerId,
462 if(peerAddresses.containsKey(peerId)){
463 peerAddresses.put(peerId, peerAddress);
466 if(LOG.isDebugEnabled()) {
467 LOG.debug("Sending PeerAddressResolved for peer {} with address {} to {}",
468 peerId, peerAddress, actor.path());
471 actor.tell(new PeerAddressResolved(peerId, peerAddress), getSelf());
476 boolean isShardInitialized() {
477 return shardInitialized;
480 void setShardInitialized(boolean shardInitialized) {
481 this.shardInitialized = shardInitialized;
485 private static class ShardManagerCreator implements Creator<ShardManager> {
486 private static final long serialVersionUID = 1L;
489 final ClusterWrapper cluster;
490 final Configuration configuration;
491 final DatastoreContext datastoreContext;
493 ShardManagerCreator(String type, ClusterWrapper cluster,
494 Configuration configuration, DatastoreContext datastoreContext) {
496 this.cluster = cluster;
497 this.configuration = configuration;
498 this.datastoreContext = datastoreContext;
502 public ShardManager create() throws Exception {
503 return new ShardManager(type, cluster, configuration, datastoreContext);
507 static class SchemaContextModules implements Serializable {
508 private static final long serialVersionUID = 1L;
510 private final Set<String> modules;
512 SchemaContextModules(Set<String> modules){
513 this.modules = modules;
516 public Set<String> getModules() {