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.MetricRegistry;
24 import com.codahale.metrics.Timer;
25 import com.google.common.annotations.VisibleForTesting;
26 import com.google.common.base.Optional;
27 import com.google.common.base.Preconditions;
28 import com.google.common.base.Strings;
29 import com.google.common.cache.Cache;
30 import com.google.common.cache.CacheBuilder;
31 import com.google.common.util.concurrent.RateLimiter;
32 import java.util.concurrent.TimeUnit;
33 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
34 import org.opendaylight.controller.cluster.datastore.ClusterWrapper;
35 import org.opendaylight.controller.cluster.datastore.Configuration;
36 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
37 import org.opendaylight.controller.cluster.datastore.exceptions.LocalShardNotFoundException;
38 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
39 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
40 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
41 import org.opendaylight.controller.cluster.datastore.exceptions.TimeoutException;
42 import org.opendaylight.controller.cluster.datastore.exceptions.UnknownMessageException;
43 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
44 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
45 import org.opendaylight.controller.cluster.datastore.messages.LocalPrimaryShardFound;
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.PrimaryShardInfo;
49 import org.opendaylight.controller.cluster.datastore.messages.RemotePrimaryShardFound;
50 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
51 import org.opendaylight.controller.cluster.reporting.MetricsReporter;
52 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
53 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import scala.concurrent.Await;
57 import scala.concurrent.ExecutionContext;
58 import scala.concurrent.Future;
59 import scala.concurrent.duration.Duration;
60 import scala.concurrent.duration.FiniteDuration;
63 * The ActorContext class contains utility methods which could be used by
64 * non-actors (like DistributedDataStore) to work with actors a little more
65 * easily. An ActorContext can be freely passed around to local object instances
66 * but should not be passed to actors especially remote actors
68 public class ActorContext {
69 private static final Logger LOG = LoggerFactory.getLogger(ActorContext.class);
70 private static final String DISTRIBUTED_DATA_STORE_METRIC_REGISTRY = "distributed-data-store";
71 private static final String METRIC_RATE = "rate";
72 private static final Mapper<Throwable, Throwable> FIND_PRIMARY_FAILURE_TRANSFORMER =
73 new Mapper<Throwable, Throwable>() {
75 public Throwable apply(Throwable failure) {
76 Throwable actualFailure = failure;
77 if(failure instanceof AskTimeoutException) {
78 // A timeout exception most likely means the shard isn't initialized.
79 actualFailure = new NotInitializedException(
80 "Timed out trying to find the primary shard. Most likely cause is the " +
81 "shard is not initialized yet.");
87 public static final String MAILBOX = "bounded-mailbox";
89 private final ActorSystem actorSystem;
90 private final ActorRef shardManager;
91 private final ClusterWrapper clusterWrapper;
92 private final Configuration configuration;
93 private DatastoreContext datastoreContext;
94 private FiniteDuration operationDuration;
95 private Timeout operationTimeout;
96 private final String selfAddressHostPort;
97 private RateLimiter txRateLimiter;
98 private final int transactionOutstandingOperationLimit;
99 private Timeout transactionCommitOperationTimeout;
100 private Timeout shardInitializationTimeout;
101 private final Dispatchers dispatchers;
102 private Cache<String, Future<PrimaryShardInfo>> primaryShardInfoCache;
104 private volatile SchemaContext schemaContext;
105 private volatile boolean updated;
106 private final MetricRegistry metricRegistry = MetricsReporter.getInstance(DatastoreContext.METRICS_DOMAIN).getMetricsRegistry();
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();
136 private void setCachedProperties() {
137 txRateLimiter = RateLimiter.create(datastoreContext.getTransactionCreationInitialRateLimit());
139 operationDuration = Duration.create(datastoreContext.getOperationTimeoutInSeconds(), TimeUnit.SECONDS);
140 operationTimeout = new Timeout(operationDuration);
142 transactionCommitOperationTimeout = new Timeout(Duration.create(
143 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS));
145 shardInitializationTimeout = new Timeout(datastoreContext.getShardInitializationTimeout().duration().$times(2));
147 primaryShardInfoCache = CacheBuilder.newBuilder()
148 .expireAfterWrite(datastoreContext.getShardLeaderElectionTimeout().duration().toMillis(), TimeUnit.MILLISECONDS)
152 public DatastoreContext getDatastoreContext() {
153 return datastoreContext;
156 public ActorSystem getActorSystem() {
160 public ActorRef getShardManager() {
164 public ActorSelection actorSelection(String actorPath) {
165 return actorSystem.actorSelection(actorPath);
168 public ActorSelection actorSelection(ActorPath actorPath) {
169 return actorSystem.actorSelection(actorPath);
172 public void setSchemaContext(SchemaContext schemaContext) {
173 this.schemaContext = schemaContext;
175 if(shardManager != null) {
176 shardManager.tell(new UpdateSchemaContext(schemaContext), ActorRef.noSender());
180 public void setDatastoreContext(DatastoreContext context) {
181 this.datastoreContext = context;
182 setCachedProperties();
184 // We write the 'updated' volatile to trigger a write memory barrier so that the writes above
185 // will be published immediately even though they may not be immediately visible to other
186 // threads due to unsynchronized reads. That's OK though - we're going for eventual
187 // consistency here as immediately visible updates to these members aren't critical. These
188 // members could've been made volatile but wanted to avoid volatile reads as these are
189 // accessed often and updates will be infrequent.
193 if(shardManager != null) {
194 shardManager.tell(context, ActorRef.noSender());
198 public SchemaContext getSchemaContext() {
199 return schemaContext;
202 public Future<PrimaryShardInfo> findPrimaryShardAsync(final String shardName) {
203 Future<PrimaryShardInfo> ret = primaryShardInfoCache.getIfPresent(shardName);
207 Future<Object> future = executeOperationAsync(shardManager,
208 new FindPrimary(shardName, true), shardInitializationTimeout);
210 return future.transform(new Mapper<Object, PrimaryShardInfo>() {
212 public PrimaryShardInfo checkedApply(Object response) throws Exception {
213 if(response instanceof RemotePrimaryShardFound) {
214 LOG.debug("findPrimaryShardAsync received: {}", response);
215 return onPrimaryShardFound(shardName, ((RemotePrimaryShardFound)response).getPrimaryPath(), null);
216 } else if(response instanceof LocalPrimaryShardFound) {
217 LOG.debug("findPrimaryShardAsync received: {}", response);
218 LocalPrimaryShardFound found = (LocalPrimaryShardFound)response;
219 return onPrimaryShardFound(shardName, found.getPrimaryPath(), found.getLocalShardDataTree());
220 } else if(response instanceof NotInitializedException) {
221 throw (NotInitializedException)response;
222 } else if(response instanceof PrimaryNotFoundException) {
223 throw (PrimaryNotFoundException)response;
224 } else if(response instanceof NoShardLeaderException) {
225 throw (NoShardLeaderException)response;
228 throw new UnknownMessageException(String.format(
229 "FindPrimary returned unkown response: %s", response));
231 }, FIND_PRIMARY_FAILURE_TRANSFORMER, getClientDispatcher());
234 private PrimaryShardInfo onPrimaryShardFound(String shardName, String primaryActorPath,
235 DataTree localShardDataTree) {
236 ActorSelection actorSelection = actorSystem.actorSelection(primaryActorPath);
237 PrimaryShardInfo info = new PrimaryShardInfo(actorSelection, Optional.fromNullable(localShardDataTree));
238 primaryShardInfoCache.put(shardName, Futures.successful(info));
243 * Finds a local shard given its shard name and return it's ActorRef
245 * @param shardName the name of the local shard that needs to be found
246 * @return a reference to a local shard actor which represents the shard
247 * specified by the shardName
249 public Optional<ActorRef> findLocalShard(String shardName) {
250 Object result = executeOperation(shardManager, new FindLocalShard(shardName, false));
252 if (result instanceof LocalShardFound) {
253 LocalShardFound found = (LocalShardFound) result;
254 LOG.debug("Local shard found {}", found.getPath());
255 return Optional.of(found.getPath());
258 return Optional.absent();
262 * Finds a local shard async given its shard name and return a Future from which to obtain the
265 * @param shardName the name of the local shard that needs to be found
267 public Future<ActorRef> findLocalShardAsync( final String shardName) {
268 Future<Object> future = executeOperationAsync(shardManager,
269 new FindLocalShard(shardName, true), shardInitializationTimeout);
271 return future.map(new Mapper<Object, ActorRef>() {
273 public ActorRef checkedApply(Object response) throws Throwable {
274 if(response instanceof LocalShardFound) {
275 LocalShardFound found = (LocalShardFound)response;
276 LOG.debug("Local shard found {}", found.getPath());
277 return found.getPath();
278 } else if(response instanceof NotInitializedException) {
279 throw (NotInitializedException)response;
280 } else if(response instanceof LocalShardNotFound) {
281 throw new LocalShardNotFoundException(
282 String.format("Local shard for %s does not exist.", shardName));
285 throw new UnknownMessageException(String.format(
286 "FindLocalShard returned unkown response: %s", response));
288 }, getClientDispatcher());
292 * Executes an operation on a local actor and wait for it's response
296 * @return The response of the operation
298 public Object executeOperation(ActorRef actor, Object message) {
299 Future<Object> future = executeOperationAsync(actor, message, operationTimeout);
302 return Await.result(future, operationDuration);
303 } catch (Exception e) {
304 throw new TimeoutException("Sending message " + message.getClass().toString() +
305 " to actor " + actor.toString() + " failed. Try again later.", e);
309 public Future<Object> executeOperationAsync(ActorRef actor, Object message, Timeout timeout) {
310 Preconditions.checkArgument(actor != null, "actor must not be null");
311 Preconditions.checkArgument(message != null, "message must not be null");
313 LOG.debug("Sending message {} to {}", message.getClass(), actor);
314 return doAsk(actor, message, timeout);
318 * Execute an operation on a remote actor and wait for it's response
324 public Object executeOperation(ActorSelection actor, Object message) {
325 Future<Object> future = executeOperationAsync(actor, message);
328 return Await.result(future, operationDuration);
329 } catch (Exception e) {
330 throw new TimeoutException("Sending message " + message.getClass().toString() +
331 " to actor " + actor.toString() + " failed. Try again later.", e);
336 * Execute an operation on a remote actor asynchronously.
338 * @param actor the ActorSelection
339 * @param message the message to send
340 * @param timeout the operation timeout
341 * @return a Future containing the eventual result
343 public Future<Object> executeOperationAsync(ActorSelection actor, Object message,
345 Preconditions.checkArgument(actor != null, "actor must not be null");
346 Preconditions.checkArgument(message != null, "message must not be null");
348 LOG.debug("Sending message {} to {}", message.getClass(), actor);
350 return doAsk(actor, message, timeout);
354 * Execute an operation on a remote actor asynchronously.
356 * @param actor the ActorSelection
357 * @param message the message to send
358 * @return a Future containing the eventual result
360 public Future<Object> executeOperationAsync(ActorSelection actor, Object message) {
361 return executeOperationAsync(actor, message, operationTimeout);
365 * Sends an operation to be executed by a remote actor asynchronously without waiting for a
366 * reply (essentially set and forget).
368 * @param actor the ActorSelection
369 * @param message the message to send
371 public void sendOperationAsync(ActorSelection actor, Object message) {
372 Preconditions.checkArgument(actor != null, "actor must not be null");
373 Preconditions.checkArgument(message != null, "message must not be null");
375 LOG.debug("Sending message {} to {}", message.getClass(), actor);
377 actor.tell(message, ActorRef.noSender());
380 public void shutdown() {
381 shardManager.tell(PoisonPill.getInstance(), ActorRef.noSender());
384 public ClusterWrapper getClusterWrapper() {
385 return clusterWrapper;
388 public String getCurrentMemberName(){
389 return clusterWrapper.getCurrentMemberName();
393 * Send the message to each and every shard
397 public void broadcast(final Object message){
398 for(final String shardName : configuration.getAllShardNames()){
400 Future<PrimaryShardInfo> primaryFuture = findPrimaryShardAsync(shardName);
401 primaryFuture.onComplete(new OnComplete<PrimaryShardInfo>() {
403 public void onComplete(Throwable failure, PrimaryShardInfo primaryShardInfo) {
404 if(failure != null) {
405 LOG.warn("broadcast failed to send message {} to shard {}: {}",
406 message.getClass().getSimpleName(), shardName, failure);
408 primaryShardInfo.getPrimaryShardActor().tell(message, ActorRef.noSender());
411 }, getClientDispatcher());
415 public FiniteDuration getOperationDuration() {
416 return operationDuration;
419 public boolean isPathLocal(String path) {
420 if (Strings.isNullOrEmpty(path)) {
424 int pathAtIndex = path.indexOf('@');
425 if (pathAtIndex == -1) {
426 //if the path is of local format, then its local and is co-located
429 } else if (selfAddressHostPort != null) {
430 // self-address and tx actor path, both are of remote path format
431 int slashIndex = path.indexOf('/', pathAtIndex);
433 if (slashIndex == -1) {
437 String hostPort = path.substring(pathAtIndex + 1, slashIndex);
438 return hostPort.equals(selfAddressHostPort);
441 // self address is local format and tx actor path is remote format
447 * @deprecated This method is present only to support backward compatibility with Helium and should not be
452 * @param localPathOfRemoteActor
456 public String resolvePath(final String primaryPath,
457 final String localPathOfRemoteActor) {
458 StringBuilder builder = new StringBuilder();
459 String[] primaryPathElements = primaryPath.split("/");
460 builder.append(primaryPathElements[0]).append("//")
461 .append(primaryPathElements[1]).append(primaryPathElements[2]);
462 String[] remotePathElements = localPathOfRemoteActor.split("/");
463 for (int i = 3; i < remotePathElements.length; i++) {
464 builder.append("/").append(remotePathElements[i]);
467 return builder.toString();
471 * Get the maximum number of operations that are to be permitted within a transaction before the transaction
472 * should begin throttling the operations
474 * Parking reading this configuration here because we need to get to the actor system settings
478 public int getTransactionOutstandingOperationLimit(){
479 return transactionOutstandingOperationLimit;
483 * This is a utility method that lets us get a Timer object for any operation. This is a little open-ended to allow
484 * us to create a timer for pretty much anything.
486 * @param operationName
489 public Timer getOperationTimer(String operationName){
490 return getOperationTimer(datastoreContext.getDataStoreType(), operationName);
493 public Timer getOperationTimer(String dataStoreType, String operationName){
494 final String rate = MetricRegistry.name(DISTRIBUTED_DATA_STORE_METRIC_REGISTRY, dataStoreType,
495 operationName, METRIC_RATE);
496 return metricRegistry.timer(rate);
500 * Get the type of the data store to which this ActorContext belongs
504 public String getDataStoreType() {
505 return datastoreContext.getDataStoreType();
509 * Set the number of transaction creation permits that are to be allowed
511 * @param permitsPerSecond
513 public void setTxCreationLimit(double permitsPerSecond){
514 txRateLimiter.setRate(permitsPerSecond);
518 * Get the current transaction creation rate limit
521 public double getTxCreationLimit(){
522 return txRateLimiter.getRate();
526 * Try to acquire a transaction creation permit. Will block if no permits are available.
528 public void acquireTxCreationPermit(){
529 txRateLimiter.acquire();
533 * Return the operation timeout to be used when committing transactions
536 public Timeout getTransactionCommitOperationTimeout(){
537 return transactionCommitOperationTimeout;
541 * An akka dispatcher that is meant to be used when processing ask Futures which were triggered by client
542 * code on the datastore
545 public ExecutionContext getClientDispatcher() {
546 return this.dispatchers.getDispatcher(Dispatchers.DispatcherType.Client);
549 public String getNotificationDispatcherPath(){
550 return this.dispatchers.getDispatcherPath(Dispatchers.DispatcherType.Notification);
553 public Configuration getConfiguration() {
554 return configuration;
557 protected Future<Object> doAsk(ActorRef actorRef, Object message, Timeout timeout){
558 return ask(actorRef, message, timeout);
561 protected Future<Object> doAsk(ActorSelection actorRef, Object message, Timeout timeout){
562 return ask(actorRef, message, timeout);
566 Cache<String, Future<PrimaryShardInfo>> getPrimaryShardInfoCache() {
567 return primaryShardInfoCache;