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 static akka.pattern.Patterns.ask;
12 import akka.actor.ActorPath;
13 import akka.actor.ActorRef;
14 import akka.actor.ActorSelection;
15 import akka.actor.ActorSystem;
16 import akka.actor.Address;
17 import akka.actor.PoisonPill;
18 import akka.dispatch.Futures;
19 import akka.dispatch.Mapper;
20 import akka.dispatch.OnComplete;
21 import akka.pattern.AskTimeoutException;
22 import akka.util.Timeout;
23 import com.codahale.metrics.JmxReporter;
24 import com.codahale.metrics.MetricRegistry;
25 import com.codahale.metrics.Timer;
26 import com.google.common.annotations.VisibleForTesting;
27 import com.google.common.base.Optional;
28 import com.google.common.base.Preconditions;
29 import com.google.common.base.Strings;
30 import com.google.common.cache.Cache;
31 import com.google.common.cache.CacheBuilder;
32 import com.google.common.util.concurrent.RateLimiter;
33 import java.util.concurrent.TimeUnit;
34 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
35 import org.opendaylight.controller.cluster.datastore.ClusterWrapper;
36 import org.opendaylight.controller.cluster.datastore.Configuration;
37 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
38 import org.opendaylight.controller.cluster.datastore.exceptions.LocalShardNotFoundException;
39 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
40 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
41 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
42 import org.opendaylight.controller.cluster.datastore.exceptions.TimeoutException;
43 import org.opendaylight.controller.cluster.datastore.exceptions.UnknownMessageException;
44 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
45 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
46 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
47 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
48 import org.opendaylight.controller.cluster.datastore.messages.PrimaryFound;
49 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
50 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import scala.concurrent.Await;
54 import scala.concurrent.ExecutionContext;
55 import scala.concurrent.Future;
56 import scala.concurrent.duration.Duration;
57 import scala.concurrent.duration.FiniteDuration;
60 * The ActorContext class contains utility methods which could be used by
61 * non-actors (like DistributedDataStore) to work with actors a little more
62 * easily. An ActorContext can be freely passed around to local object instances
63 * but should not be passed to actors especially remote actors
65 public class ActorContext {
66 private static final Logger LOG = LoggerFactory.getLogger(ActorContext.class);
67 private static final String UNKNOWN_DATA_STORE_TYPE = "unknown";
68 private static final String DISTRIBUTED_DATA_STORE_METRIC_REGISTRY = "distributed-data-store";
69 private static final String METRIC_RATE = "rate";
70 private static final String DOMAIN = "org.opendaylight.controller.cluster.datastore";
71 private static final Mapper<Throwable, Throwable> FIND_PRIMARY_FAILURE_TRANSFORMER =
72 new Mapper<Throwable, Throwable>() {
74 public Throwable apply(Throwable failure) {
75 Throwable actualFailure = failure;
76 if(failure instanceof AskTimeoutException) {
77 // A timeout exception most likely means the shard isn't initialized.
78 actualFailure = new NotInitializedException(
79 "Timed out trying to find the primary shard. Most likely cause is the " +
80 "shard is not initialized yet.");
86 public static final String MAILBOX = "bounded-mailbox";
88 private final ActorSystem actorSystem;
89 private final ActorRef shardManager;
90 private final ClusterWrapper clusterWrapper;
91 private final Configuration configuration;
92 private DatastoreContext datastoreContext;
93 private FiniteDuration operationDuration;
94 private Timeout operationTimeout;
95 private final String selfAddressHostPort;
96 private RateLimiter txRateLimiter;
97 private final MetricRegistry metricRegistry = new MetricRegistry();
98 private final JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).inDomain(DOMAIN).build();
99 private final int transactionOutstandingOperationLimit;
100 private Timeout transactionCommitOperationTimeout;
101 private Timeout shardInitializationTimeout;
102 private final Dispatchers dispatchers;
103 private Cache<String, Future<ActorSelection>> primaryShardActorSelectionCache;
105 private volatile SchemaContext schemaContext;
106 private volatile boolean updated;
108 public ActorContext(ActorSystem actorSystem, ActorRef shardManager,
109 ClusterWrapper clusterWrapper, Configuration configuration) {
110 this(actorSystem, shardManager, clusterWrapper, configuration,
111 DatastoreContext.newBuilder().build());
114 public ActorContext(ActorSystem actorSystem, ActorRef shardManager,
115 ClusterWrapper clusterWrapper, Configuration configuration,
116 DatastoreContext datastoreContext) {
117 this.actorSystem = actorSystem;
118 this.shardManager = shardManager;
119 this.clusterWrapper = clusterWrapper;
120 this.configuration = configuration;
121 this.datastoreContext = datastoreContext;
122 this.dispatchers = new Dispatchers(actorSystem.dispatchers());
124 setCachedProperties();
126 Address selfAddress = clusterWrapper.getSelfAddress();
127 if (selfAddress != null && !selfAddress.host().isEmpty()) {
128 selfAddressHostPort = selfAddress.host().get() + ":" + selfAddress.port().get();
130 selfAddressHostPort = null;
133 transactionOutstandingOperationLimit = new CommonConfig(this.getActorSystem().settings().config()).getMailBoxCapacity();
138 private void setCachedProperties() {
139 txRateLimiter = RateLimiter.create(datastoreContext.getTransactionCreationInitialRateLimit());
141 operationDuration = Duration.create(datastoreContext.getOperationTimeoutInSeconds(), TimeUnit.SECONDS);
142 operationTimeout = new Timeout(operationDuration);
144 transactionCommitOperationTimeout = new Timeout(Duration.create(
145 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS));
147 shardInitializationTimeout = new Timeout(datastoreContext.getShardInitializationTimeout().duration().$times(2));
149 primaryShardActorSelectionCache = CacheBuilder.newBuilder()
150 .expireAfterWrite(datastoreContext.getShardLeaderElectionTimeout().duration().toMillis(), TimeUnit.MILLISECONDS)
154 public DatastoreContext getDatastoreContext() {
155 return datastoreContext;
158 public ActorSystem getActorSystem() {
162 public ActorRef getShardManager() {
166 public ActorSelection actorSelection(String actorPath) {
167 return actorSystem.actorSelection(actorPath);
170 public ActorSelection actorSelection(ActorPath actorPath) {
171 return actorSystem.actorSelection(actorPath);
174 public void setSchemaContext(SchemaContext schemaContext) {
175 this.schemaContext = schemaContext;
177 if(shardManager != null) {
178 shardManager.tell(new UpdateSchemaContext(schemaContext), ActorRef.noSender());
182 public void setDatastoreContext(DatastoreContext context) {
183 this.datastoreContext = context;
184 setCachedProperties();
186 // We write the 'updated' volatile to trigger a write memory barrier so that the writes above
187 // will be published immediately even though they may not be immediately visible to other
188 // threads due to unsynchronized reads. That's OK though - we're going for eventual
189 // consistency here as immediately visible updates to these members aren't critical. These
190 // members could've been made volatile but wanted to avoid volatile reads as these are
191 // accessed often and updates will be infrequent.
195 if(shardManager != null) {
196 shardManager.tell(context, ActorRef.noSender());
200 public SchemaContext getSchemaContext() {
201 return schemaContext;
204 public Future<ActorSelection> findPrimaryShardAsync(final String shardName) {
205 Future<ActorSelection> ret = primaryShardActorSelectionCache.getIfPresent(shardName);
209 Future<Object> future = executeOperationAsync(shardManager,
210 new FindPrimary(shardName, true), shardInitializationTimeout);
212 return future.transform(new Mapper<Object, ActorSelection>() {
214 public ActorSelection checkedApply(Object response) throws Exception {
215 if(response instanceof PrimaryFound) {
216 PrimaryFound found = (PrimaryFound)response;
218 LOG.debug("Primary found {}", found.getPrimaryPath());
219 ActorSelection actorSelection = actorSystem.actorSelection(found.getPrimaryPath());
220 primaryShardActorSelectionCache.put(shardName, Futures.successful(actorSelection));
221 return actorSelection;
222 } else if(response instanceof NotInitializedException) {
223 throw (NotInitializedException)response;
224 } else if(response instanceof PrimaryNotFoundException) {
225 throw (PrimaryNotFoundException)response;
226 } else if(response instanceof NoShardLeaderException) {
227 throw (NoShardLeaderException)response;
230 throw new UnknownMessageException(String.format(
231 "FindPrimary returned unkown response: %s", response));
233 }, FIND_PRIMARY_FAILURE_TRANSFORMER, getClientDispatcher());
237 * Finds a local shard given its shard name and return it's ActorRef
239 * @param shardName the name of the local shard that needs to be found
240 * @return a reference to a local shard actor which represents the shard
241 * specified by the shardName
243 public Optional<ActorRef> findLocalShard(String shardName) {
244 Object result = executeOperation(shardManager, new FindLocalShard(shardName, false));
246 if (result instanceof LocalShardFound) {
247 LocalShardFound found = (LocalShardFound) result;
248 LOG.debug("Local shard found {}", found.getPath());
249 return Optional.of(found.getPath());
252 return Optional.absent();
256 * Finds a local shard async given its shard name and return a Future from which to obtain the
259 * @param shardName the name of the local shard that needs to be found
261 public Future<ActorRef> findLocalShardAsync( final String shardName) {
262 Future<Object> future = executeOperationAsync(shardManager,
263 new FindLocalShard(shardName, true), shardInitializationTimeout);
265 return future.map(new Mapper<Object, ActorRef>() {
267 public ActorRef checkedApply(Object response) throws Throwable {
268 if(response instanceof LocalShardFound) {
269 LocalShardFound found = (LocalShardFound)response;
270 LOG.debug("Local shard found {}", found.getPath());
271 return found.getPath();
272 } else if(response instanceof NotInitializedException) {
273 throw (NotInitializedException)response;
274 } else if(response instanceof LocalShardNotFound) {
275 throw new LocalShardNotFoundException(
276 String.format("Local shard for %s does not exist.", shardName));
279 throw new UnknownMessageException(String.format(
280 "FindLocalShard returned unkown response: %s", response));
282 }, getClientDispatcher());
286 * Executes an operation on a local actor and wait for it's response
290 * @return The response of the operation
292 public Object executeOperation(ActorRef actor, Object message) {
293 Future<Object> future = executeOperationAsync(actor, message, operationTimeout);
296 return Await.result(future, operationDuration);
297 } catch (Exception e) {
298 throw new TimeoutException("Sending message " + message.getClass().toString() +
299 " to actor " + actor.toString() + " failed. Try again later.", e);
303 public Future<Object> executeOperationAsync(ActorRef actor, Object message, Timeout timeout) {
304 Preconditions.checkArgument(actor != null, "actor must not be null");
305 Preconditions.checkArgument(message != null, "message must not be null");
307 LOG.debug("Sending message {} to {}", message.getClass(), actor);
308 return doAsk(actor, message, timeout);
312 * Execute an operation on a remote actor and wait for it's response
318 public Object executeOperation(ActorSelection actor, Object message) {
319 Future<Object> future = executeOperationAsync(actor, message);
322 return Await.result(future, operationDuration);
323 } catch (Exception e) {
324 throw new TimeoutException("Sending message " + message.getClass().toString() +
325 " to actor " + actor.toString() + " failed. Try again later.", e);
330 * Execute an operation on a remote actor asynchronously.
332 * @param actor the ActorSelection
333 * @param message the message to send
334 * @param timeout the operation timeout
335 * @return a Future containing the eventual result
337 public Future<Object> executeOperationAsync(ActorSelection actor, Object message,
339 Preconditions.checkArgument(actor != null, "actor must not be null");
340 Preconditions.checkArgument(message != null, "message must not be null");
342 LOG.debug("Sending message {} to {}", message.getClass(), actor);
344 return doAsk(actor, message, timeout);
348 * Execute an operation on a remote actor asynchronously.
350 * @param actor the ActorSelection
351 * @param message the message to send
352 * @return a Future containing the eventual result
354 public Future<Object> executeOperationAsync(ActorSelection actor, Object message) {
355 return executeOperationAsync(actor, message, operationTimeout);
359 * Sends an operation to be executed by a remote actor asynchronously without waiting for a
360 * reply (essentially set and forget).
362 * @param actor the ActorSelection
363 * @param message the message to send
365 public void sendOperationAsync(ActorSelection actor, Object message) {
366 Preconditions.checkArgument(actor != null, "actor must not be null");
367 Preconditions.checkArgument(message != null, "message must not be null");
369 LOG.debug("Sending message {} to {}", message.getClass(), actor);
371 actor.tell(message, ActorRef.noSender());
374 public void shutdown() {
375 shardManager.tell(PoisonPill.getInstance(), null);
376 actorSystem.shutdown();
379 public ClusterWrapper getClusterWrapper() {
380 return clusterWrapper;
383 public String getCurrentMemberName(){
384 return clusterWrapper.getCurrentMemberName();
388 * Send the message to each and every shard
392 public void broadcast(final Object message){
393 for(final String shardName : configuration.getAllShardNames()){
395 Future<ActorSelection> primaryFuture = findPrimaryShardAsync(shardName);
396 primaryFuture.onComplete(new OnComplete<ActorSelection>() {
398 public void onComplete(Throwable failure, ActorSelection primaryShard) {
399 if(failure != null) {
400 LOG.warn("broadcast failed to send message {} to shard {}: {}",
401 message.getClass().getSimpleName(), shardName, failure);
403 primaryShard.tell(message, ActorRef.noSender());
406 }, getClientDispatcher());
410 public FiniteDuration getOperationDuration() {
411 return operationDuration;
414 public boolean isPathLocal(String path) {
415 if (Strings.isNullOrEmpty(path)) {
419 int pathAtIndex = path.indexOf('@');
420 if (pathAtIndex == -1) {
421 //if the path is of local format, then its local and is co-located
424 } else if (selfAddressHostPort != null) {
425 // self-address and tx actor path, both are of remote path format
426 int slashIndex = path.indexOf('/', pathAtIndex);
428 if (slashIndex == -1) {
432 String hostPort = path.substring(pathAtIndex + 1, slashIndex);
433 return hostPort.equals(selfAddressHostPort);
436 // self address is local format and tx actor path is remote format
442 * @deprecated This method is present only to support backward compatibility with Helium and should not be
447 * @param localPathOfRemoteActor
451 public String resolvePath(final String primaryPath,
452 final String localPathOfRemoteActor) {
453 StringBuilder builder = new StringBuilder();
454 String[] primaryPathElements = primaryPath.split("/");
455 builder.append(primaryPathElements[0]).append("//")
456 .append(primaryPathElements[1]).append(primaryPathElements[2]);
457 String[] remotePathElements = localPathOfRemoteActor.split("/");
458 for (int i = 3; i < remotePathElements.length; i++) {
459 builder.append("/").append(remotePathElements[i]);
462 return builder.toString();
466 * Get the maximum number of operations that are to be permitted within a transaction before the transaction
467 * should begin throttling the operations
469 * Parking reading this configuration here because we need to get to the actor system settings
473 public int getTransactionOutstandingOperationLimit(){
474 return transactionOutstandingOperationLimit;
478 * This is a utility method that lets us get a Timer object for any operation. This is a little open-ended to allow
479 * us to create a timer for pretty much anything.
481 * @param operationName
484 public Timer getOperationTimer(String operationName){
485 final String rate = MetricRegistry.name(DISTRIBUTED_DATA_STORE_METRIC_REGISTRY, datastoreContext.getDataStoreType(), operationName, METRIC_RATE);
486 return metricRegistry.timer(rate);
490 * Get the type of the data store to which this ActorContext belongs
494 public String getDataStoreType() {
495 return datastoreContext.getDataStoreType();
499 * Set the number of transaction creation permits that are to be allowed
501 * @param permitsPerSecond
503 public void setTxCreationLimit(double permitsPerSecond){
504 txRateLimiter.setRate(permitsPerSecond);
508 * Get the current transaction creation rate limit
511 public double getTxCreationLimit(){
512 return txRateLimiter.getRate();
516 * Try to acquire a transaction creation permit. Will block if no permits are available.
518 public void acquireTxCreationPermit(){
519 txRateLimiter.acquire();
523 * Return the operation timeout to be used when committing transactions
526 public Timeout getTransactionCommitOperationTimeout(){
527 return transactionCommitOperationTimeout;
531 * An akka dispatcher that is meant to be used when processing ask Futures which were triggered by client
532 * code on the datastore
535 public ExecutionContext getClientDispatcher() {
536 return this.dispatchers.getDispatcher(Dispatchers.DispatcherType.Client);
539 public String getNotificationDispatcherPath(){
540 return this.dispatchers.getDispatcherPath(Dispatchers.DispatcherType.Notification);
543 protected Future<Object> doAsk(ActorRef actorRef, Object message, Timeout timeout){
544 return ask(actorRef, message, timeout);
547 protected Future<Object> doAsk(ActorSelection actorRef, Object message, Timeout timeout){
548 return ask(actorRef, message, timeout);
552 Cache<String, Future<ActorSelection>> getPrimaryShardActorSelectionCache() {
553 return primaryShardActorSelectionCache;