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.utils;
11 import akka.actor.ActorPath;
12 import akka.actor.ActorRef;
13 import akka.actor.ActorSelection;
14 import akka.actor.ActorSystem;
15 import akka.actor.Address;
16 import akka.actor.PoisonPill;
17 import akka.dispatch.Mapper;
18 import akka.pattern.AskTimeoutException;
19 import akka.util.Timeout;
20 import com.google.common.base.Optional;
21 import com.google.common.base.Preconditions;
22 import com.google.common.base.Strings;
23 import java.util.concurrent.TimeUnit;
24 import org.opendaylight.controller.cluster.datastore.ClusterWrapper;
25 import org.opendaylight.controller.cluster.datastore.Configuration;
26 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
27 import org.opendaylight.controller.cluster.datastore.exceptions.LocalShardNotFoundException;
28 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
29 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
30 import org.opendaylight.controller.cluster.datastore.exceptions.TimeoutException;
31 import org.opendaylight.controller.cluster.datastore.exceptions.UnknownMessageException;
32 import org.opendaylight.controller.cluster.datastore.messages.ActorNotInitialized;
33 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
34 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
35 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
36 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
37 import org.opendaylight.controller.cluster.datastore.messages.PrimaryFound;
38 import org.opendaylight.controller.cluster.datastore.messages.PrimaryNotFound;
39 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
40 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import scala.concurrent.Await;
44 import scala.concurrent.Future;
45 import scala.concurrent.duration.Duration;
46 import scala.concurrent.duration.FiniteDuration;
48 import static akka.pattern.Patterns.ask;
51 * The ActorContext class contains utility methods which could be used by
52 * non-actors (like DistributedDataStore) to work with actors a little more
53 * easily. An ActorContext can be freely passed around to local object instances
54 * but should not be passed to actors especially remote actors
56 public class ActorContext {
57 private static final Logger
58 LOG = LoggerFactory.getLogger(ActorContext.class);
60 public static final String MAILBOX = "bounded-mailbox";
62 private static final Mapper<Throwable, Throwable> FIND_PRIMARY_FAILURE_TRANSFORMER =
63 new Mapper<Throwable, Throwable>() {
65 public Throwable apply(Throwable failure) {
66 Throwable actualFailure = failure;
67 if(failure instanceof AskTimeoutException) {
68 // A timeout exception most likely means the shard isn't initialized.
69 actualFailure = new NotInitializedException(
70 "Timed out trying to find the primary shard. Most likely cause is the " +
71 "shard is not initialized yet.");
78 private final ActorSystem actorSystem;
79 private final ActorRef shardManager;
80 private final ClusterWrapper clusterWrapper;
81 private final Configuration configuration;
82 private final DatastoreContext datastoreContext;
83 private volatile SchemaContext schemaContext;
84 private final FiniteDuration operationDuration;
85 private final Timeout operationTimeout;
86 private final String selfAddressHostPort;
88 public ActorContext(ActorSystem actorSystem, ActorRef shardManager,
89 ClusterWrapper clusterWrapper, Configuration configuration) {
90 this(actorSystem, shardManager, clusterWrapper, configuration,
91 DatastoreContext.newBuilder().build());
94 public ActorContext(ActorSystem actorSystem, ActorRef shardManager,
95 ClusterWrapper clusterWrapper, Configuration configuration,
96 DatastoreContext datastoreContext) {
97 this.actorSystem = actorSystem;
98 this.shardManager = shardManager;
99 this.clusterWrapper = clusterWrapper;
100 this.configuration = configuration;
101 this.datastoreContext = datastoreContext;
103 operationDuration = Duration.create(datastoreContext.getOperationTimeoutInSeconds(),
105 operationTimeout = new Timeout(operationDuration);
107 Address selfAddress = clusterWrapper.getSelfAddress();
108 if (selfAddress != null && !selfAddress.host().isEmpty()) {
109 selfAddressHostPort = selfAddress.host().get() + ":" + selfAddress.port().get();
111 selfAddressHostPort = null;
115 public DatastoreContext getDatastoreContext() {
116 return datastoreContext;
119 public ActorSystem getActorSystem() {
123 public ActorRef getShardManager() {
127 public ActorSelection actorSelection(String actorPath) {
128 return actorSystem.actorSelection(actorPath);
131 public ActorSelection actorSelection(ActorPath actorPath) {
132 return actorSystem.actorSelection(actorPath);
135 public void setSchemaContext(SchemaContext schemaContext) {
136 this.schemaContext = schemaContext;
138 if(shardManager != null) {
139 shardManager.tell(new UpdateSchemaContext(schemaContext), null);
143 public SchemaContext getSchemaContext() {
144 return schemaContext;
148 * Finds the primary shard for the given shard name
153 public Optional<ActorSelection> findPrimaryShard(String shardName) {
154 String path = findPrimaryPathOrNull(shardName);
156 return Optional.absent();
158 return Optional.of(actorSystem.actorSelection(path));
161 public Future<ActorSelection> findPrimaryShardAsync(final String shardName) {
162 Future<Object> future = executeOperationAsync(shardManager,
163 new FindPrimary(shardName, true).toSerializable(),
164 datastoreContext.getShardInitializationTimeout());
166 return future.transform(new Mapper<Object, ActorSelection>() {
168 public ActorSelection checkedApply(Object response) throws Exception {
169 if(response.getClass().equals(PrimaryFound.SERIALIZABLE_CLASS)) {
170 PrimaryFound found = PrimaryFound.fromSerializable(response);
172 LOG.debug("Primary found {}", found.getPrimaryPath());
173 return actorSystem.actorSelection(found.getPrimaryPath());
174 } else if(response instanceof ActorNotInitialized) {
175 throw new NotInitializedException(
176 String.format("Found primary shard %s but it's not initialized yet. " +
177 "Please try again later", shardName));
178 } else if(response instanceof PrimaryNotFound) {
179 throw new PrimaryNotFoundException(
180 String.format("No primary shard found for %S.", shardName));
183 throw new UnknownMessageException(String.format(
184 "FindPrimary returned unkown response: %s", response));
186 }, FIND_PRIMARY_FAILURE_TRANSFORMER, getActorSystem().dispatcher());
190 * Finds a local shard given its shard name and return it's ActorRef
192 * @param shardName the name of the local shard that needs to be found
193 * @return a reference to a local shard actor which represents the shard
194 * specified by the shardName
196 public Optional<ActorRef> findLocalShard(String shardName) {
197 Object result = executeOperation(shardManager, new FindLocalShard(shardName, false));
199 if (result instanceof LocalShardFound) {
200 LocalShardFound found = (LocalShardFound) result;
201 LOG.debug("Local shard found {}", found.getPath());
202 return Optional.of(found.getPath());
205 return Optional.absent();
209 * Finds a local shard async given its shard name and return a Future from which to obtain the
212 * @param shardName the name of the local shard that needs to be found
214 public Future<ActorRef> findLocalShardAsync( final String shardName) {
215 Future<Object> future = executeOperationAsync(shardManager,
216 new FindLocalShard(shardName, true), datastoreContext.getShardInitializationTimeout());
218 return future.map(new Mapper<Object, ActorRef>() {
220 public ActorRef checkedApply(Object response) throws Throwable {
221 if(response instanceof LocalShardFound) {
222 LocalShardFound found = (LocalShardFound)response;
223 LOG.debug("Local shard found {}", found.getPath());
224 return found.getPath();
225 } else if(response instanceof ActorNotInitialized) {
226 throw new NotInitializedException(
227 String.format("Found local shard for %s but it's not initialized yet.",
229 } else if(response instanceof LocalShardNotFound) {
230 throw new LocalShardNotFoundException(
231 String.format("Local shard for %s does not exist.", shardName));
234 throw new UnknownMessageException(String.format(
235 "FindLocalShard returned unkown response: %s", response));
237 }, getActorSystem().dispatcher());
240 private String findPrimaryPathOrNull(String shardName) {
241 Object result = executeOperation(shardManager, new FindPrimary(shardName, false).toSerializable());
243 if (result.getClass().equals(PrimaryFound.SERIALIZABLE_CLASS)) {
244 PrimaryFound found = PrimaryFound.fromSerializable(result);
246 LOG.debug("Primary found {}", found.getPrimaryPath());
247 return found.getPrimaryPath();
249 } else if (result.getClass().equals(ActorNotInitialized.class)){
250 throw new NotInitializedException(
251 String.format("Found primary shard[%s] but its not initialized yet. Please try again later", shardName)
261 * Executes an operation on a local actor and wait for it's response
265 * @return The response of the operation
267 public Object executeOperation(ActorRef actor, Object message) {
268 Future<Object> future = executeOperationAsync(actor, message, operationTimeout);
271 return Await.result(future, operationDuration);
272 } catch (Exception e) {
273 throw new TimeoutException("Sending message " + message.getClass().toString() +
274 " to actor " + actor.toString() + " failed. Try again later.", e);
278 public Future<Object> executeOperationAsync(ActorRef actor, Object message, Timeout timeout) {
279 Preconditions.checkArgument(actor != null, "actor must not be null");
280 Preconditions.checkArgument(message != null, "message must not be null");
282 LOG.debug("Sending message {} to {}", message.getClass().toString(), actor.toString());
283 return ask(actor, message, timeout);
287 * Execute an operation on a remote actor and wait for it's response
293 public Object executeOperation(ActorSelection actor, Object message) {
294 Future<Object> future = executeOperationAsync(actor, message);
297 return Await.result(future, operationDuration);
298 } catch (Exception e) {
299 throw new TimeoutException("Sending message " + message.getClass().toString() +
300 " to actor " + actor.toString() + " failed. Try again later.", e);
305 * Execute an operation on a remote actor asynchronously.
307 * @param actor the ActorSelection
308 * @param message the message to send
309 * @param timeout the operation timeout
310 * @return a Future containing the eventual result
312 public Future<Object> executeOperationAsync(ActorSelection actor, Object message,
314 Preconditions.checkArgument(actor != null, "actor must not be null");
315 Preconditions.checkArgument(message != null, "message must not be null");
317 LOG.debug("Sending message {} to {}", message.getClass().toString(), actor.toString());
319 return ask(actor, message, timeout);
323 * Execute an operation on a remote actor asynchronously.
325 * @param actor the ActorSelection
326 * @param message the message to send
327 * @return a Future containing the eventual result
329 public Future<Object> executeOperationAsync(ActorSelection actor, Object message) {
330 return executeOperationAsync(actor, message, operationTimeout);
334 * Sends an operation to be executed by a remote actor asynchronously without waiting for a
335 * reply (essentially set and forget).
337 * @param actor the ActorSelection
338 * @param message the message to send
340 public void sendOperationAsync(ActorSelection actor, Object message) {
341 Preconditions.checkArgument(actor != null, "actor must not be null");
342 Preconditions.checkArgument(message != null, "message must not be null");
344 LOG.debug("Sending message {} to {}", message.getClass().toString(), actor.toString());
346 actor.tell(message, ActorRef.noSender());
349 public void shutdown() {
350 shardManager.tell(PoisonPill.getInstance(), null);
351 actorSystem.shutdown();
354 public ClusterWrapper getClusterWrapper() {
355 return clusterWrapper;
358 public String getCurrentMemberName(){
359 return clusterWrapper.getCurrentMemberName();
363 * Send the message to each and every shard
367 public void broadcast(Object message){
368 for(String shardName : configuration.getAllShardNames()){
370 Optional<ActorSelection> primary = findPrimaryShard(shardName);
371 if (primary.isPresent()) {
372 primary.get().tell(message, ActorRef.noSender());
374 LOG.warn("broadcast failed to send message {} to shard {}. Primary not found",
375 message.getClass().getSimpleName(), shardName);
380 public FiniteDuration getOperationDuration() {
381 return operationDuration;
384 public boolean isPathLocal(String path) {
385 if (Strings.isNullOrEmpty(path)) {
389 int pathAtIndex = path.indexOf("@");
390 if (pathAtIndex == -1) {
391 //if the path is of local format, then its local and is co-located
394 } else if (selfAddressHostPort != null) {
395 // self-address and tx actor path, both are of remote path format
396 int slashIndex = path.indexOf("/", pathAtIndex);
398 if (slashIndex == -1) {
402 String hostPort = path.substring(pathAtIndex + 1, slashIndex);
403 return hostPort.equals(selfAddressHostPort);
406 // self address is local format and tx actor path is remote format
412 * @deprecated This method is present only to support backward compatibility with Helium and should not be
417 * @param localPathOfRemoteActor
421 public String resolvePath(final String primaryPath,
422 final String localPathOfRemoteActor) {
423 StringBuilder builder = new StringBuilder();
424 String[] primaryPathElements = primaryPath.split("/");
425 builder.append(primaryPathElements[0]).append("//")
426 .append(primaryPathElements[1]).append(primaryPathElements[2]);
427 String[] remotePathElements = localPathOfRemoteActor.split("/");
428 for (int i = 3; i < remotePathElements.length; i++) {
429 builder.append("/").append(remotePathElements[i]);
432 return builder.toString();