Merge "BUG 2792 : Serialize phase processing in ConcurrentDOMDatBroker"
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / utils / ActorContext.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.cluster.datastore.utils;
10
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;
58
59 /**
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
64  */
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>() {
73         @Override
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.");
81             }
82
83             return actualFailure;
84         }
85     };
86     public static final String MAILBOX = "bounded-mailbox";
87
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;
104
105     private volatile SchemaContext schemaContext;
106     private volatile boolean updated;
107
108     public ActorContext(ActorSystem actorSystem, ActorRef shardManager,
109             ClusterWrapper clusterWrapper, Configuration configuration) {
110         this(actorSystem, shardManager, clusterWrapper, configuration,
111                 DatastoreContext.newBuilder().build());
112     }
113
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());
123
124         setCachedProperties();
125
126         Address selfAddress = clusterWrapper.getSelfAddress();
127         if (selfAddress != null && !selfAddress.host().isEmpty()) {
128             selfAddressHostPort = selfAddress.host().get() + ":" + selfAddress.port().get();
129         } else {
130             selfAddressHostPort = null;
131         }
132
133         transactionOutstandingOperationLimit = new CommonConfig(this.getActorSystem().settings().config()).getMailBoxCapacity();
134         jmxReporter.start();
135
136     }
137
138     private void setCachedProperties() {
139         txRateLimiter = RateLimiter.create(datastoreContext.getTransactionCreationInitialRateLimit());
140
141         operationDuration = Duration.create(datastoreContext.getOperationTimeoutInSeconds(), TimeUnit.SECONDS);
142         operationTimeout = new Timeout(operationDuration);
143
144         transactionCommitOperationTimeout =  new Timeout(Duration.create(
145                 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS));
146
147         shardInitializationTimeout = new Timeout(datastoreContext.getShardInitializationTimeout().duration().$times(2));
148
149         primaryShardActorSelectionCache = CacheBuilder.newBuilder()
150                 .expireAfterWrite(datastoreContext.getShardLeaderElectionTimeout().duration().toMillis(), TimeUnit.MILLISECONDS)
151                 .build();
152     }
153
154     public DatastoreContext getDatastoreContext() {
155         return datastoreContext;
156     }
157
158     public ActorSystem getActorSystem() {
159         return actorSystem;
160     }
161
162     public ActorRef getShardManager() {
163         return shardManager;
164     }
165
166     public ActorSelection actorSelection(String actorPath) {
167         return actorSystem.actorSelection(actorPath);
168     }
169
170     public ActorSelection actorSelection(ActorPath actorPath) {
171         return actorSystem.actorSelection(actorPath);
172     }
173
174     public void setSchemaContext(SchemaContext schemaContext) {
175         this.schemaContext = schemaContext;
176
177         if(shardManager != null) {
178             shardManager.tell(new UpdateSchemaContext(schemaContext), ActorRef.noSender());
179         }
180     }
181
182     public void setDatastoreContext(DatastoreContext context) {
183         this.datastoreContext = context;
184         setCachedProperties();
185
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.
192
193         updated = true;
194
195         if(shardManager != null) {
196             shardManager.tell(context, ActorRef.noSender());
197         }
198     }
199
200     public SchemaContext getSchemaContext() {
201         return schemaContext;
202     }
203
204     public Future<ActorSelection> findPrimaryShardAsync(final String shardName) {
205         Future<ActorSelection> ret = primaryShardActorSelectionCache.getIfPresent(shardName);
206         if(ret != null){
207             return ret;
208         }
209         Future<Object> future = executeOperationAsync(shardManager,
210                 new FindPrimary(shardName, true), shardInitializationTimeout);
211
212         return future.transform(new Mapper<Object, ActorSelection>() {
213             @Override
214             public ActorSelection checkedApply(Object response) throws Exception {
215                 if(response instanceof PrimaryFound) {
216                     PrimaryFound found = (PrimaryFound)response;
217
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;
228                 }
229
230                 throw new UnknownMessageException(String.format(
231                         "FindPrimary returned unkown response: %s", response));
232             }
233         }, FIND_PRIMARY_FAILURE_TRANSFORMER, getClientDispatcher());
234     }
235
236     /**
237      * Finds a local shard given its shard name and return it's ActorRef
238      *
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
242      */
243     public Optional<ActorRef> findLocalShard(String shardName) {
244         Object result = executeOperation(shardManager, new FindLocalShard(shardName, false));
245
246         if (result instanceof LocalShardFound) {
247             LocalShardFound found = (LocalShardFound) result;
248             LOG.debug("Local shard found {}", found.getPath());
249             return Optional.of(found.getPath());
250         }
251
252         return Optional.absent();
253     }
254
255     /**
256      * Finds a local shard async given its shard name and return a Future from which to obtain the
257      * ActorRef.
258      *
259      * @param shardName the name of the local shard that needs to be found
260      */
261     public Future<ActorRef> findLocalShardAsync( final String shardName) {
262         Future<Object> future = executeOperationAsync(shardManager,
263                 new FindLocalShard(shardName, true), shardInitializationTimeout);
264
265         return future.map(new Mapper<Object, ActorRef>() {
266             @Override
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));
277                 }
278
279                 throw new UnknownMessageException(String.format(
280                         "FindLocalShard returned unkown response: %s", response));
281             }
282         }, getClientDispatcher());
283     }
284
285     /**
286      * Executes an operation on a local actor and wait for it's response
287      *
288      * @param actor
289      * @param message
290      * @return The response of the operation
291      */
292     public Object executeOperation(ActorRef actor, Object message) {
293         Future<Object> future = executeOperationAsync(actor, message, operationTimeout);
294
295         try {
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);
300         }
301     }
302
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");
306
307         LOG.debug("Sending message {} to {}", message.getClass(), actor);
308         return doAsk(actor, message, timeout);
309     }
310
311     /**
312      * Execute an operation on a remote actor and wait for it's response
313      *
314      * @param actor
315      * @param message
316      * @return
317      */
318     public Object executeOperation(ActorSelection actor, Object message) {
319         Future<Object> future = executeOperationAsync(actor, message);
320
321         try {
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);
326         }
327     }
328
329     /**
330      * Execute an operation on a remote actor asynchronously.
331      *
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
336      */
337     public Future<Object> executeOperationAsync(ActorSelection actor, Object message,
338             Timeout timeout) {
339         Preconditions.checkArgument(actor != null, "actor must not be null");
340         Preconditions.checkArgument(message != null, "message must not be null");
341
342         LOG.debug("Sending message {} to {}", message.getClass(), actor);
343
344         return doAsk(actor, message, timeout);
345     }
346
347     /**
348      * Execute an operation on a remote actor asynchronously.
349      *
350      * @param actor the ActorSelection
351      * @param message the message to send
352      * @return a Future containing the eventual result
353      */
354     public Future<Object> executeOperationAsync(ActorSelection actor, Object message) {
355         return executeOperationAsync(actor, message, operationTimeout);
356     }
357
358     /**
359      * Sends an operation to be executed by a remote actor asynchronously without waiting for a
360      * reply (essentially set and forget).
361      *
362      * @param actor the ActorSelection
363      * @param message the message to send
364      */
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");
368
369         LOG.debug("Sending message {} to {}", message.getClass(), actor);
370
371         actor.tell(message, ActorRef.noSender());
372     }
373
374     public void shutdown() {
375         shardManager.tell(PoisonPill.getInstance(), null);
376         actorSystem.shutdown();
377     }
378
379     public ClusterWrapper getClusterWrapper() {
380         return clusterWrapper;
381     }
382
383     public String getCurrentMemberName(){
384         return clusterWrapper.getCurrentMemberName();
385     }
386
387     /**
388      * Send the message to each and every shard
389      *
390      * @param message
391      */
392     public void broadcast(final Object message){
393         for(final String shardName : configuration.getAllShardNames()){
394
395             Future<ActorSelection> primaryFuture = findPrimaryShardAsync(shardName);
396             primaryFuture.onComplete(new OnComplete<ActorSelection>() {
397                 @Override
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);
402                     } else {
403                         primaryShard.tell(message, ActorRef.noSender());
404                     }
405                 }
406             }, getClientDispatcher());
407         }
408     }
409
410     public FiniteDuration getOperationDuration() {
411         return operationDuration;
412     }
413
414     public boolean isPathLocal(String path) {
415         if (Strings.isNullOrEmpty(path)) {
416             return false;
417         }
418
419         int pathAtIndex = path.indexOf('@');
420         if (pathAtIndex == -1) {
421             //if the path is of local format, then its local and is co-located
422             return true;
423
424         } else if (selfAddressHostPort != null) {
425             // self-address and tx actor path, both are of remote path format
426             int slashIndex = path.indexOf('/', pathAtIndex);
427
428             if (slashIndex == -1) {
429                 return false;
430             }
431
432             String hostPort = path.substring(pathAtIndex + 1, slashIndex);
433             return hostPort.equals(selfAddressHostPort);
434
435         } else {
436             // self address is local format and tx actor path is remote format
437             return false;
438         }
439     }
440
441     /**
442      * @deprecated This method is present only to support backward compatibility with Helium and should not be
443      * used any further
444      *
445      *
446      * @param primaryPath
447      * @param localPathOfRemoteActor
448      * @return
449     */
450     @Deprecated
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]);
460             }
461
462         return builder.toString();
463     }
464
465     /**
466      * Get the maximum number of operations that are to be permitted within a transaction before the transaction
467      * should begin throttling the operations
468      *
469      * Parking reading this configuration here because we need to get to the actor system settings
470      *
471      * @return
472      */
473     public int getTransactionOutstandingOperationLimit(){
474         return transactionOutstandingOperationLimit;
475     }
476
477     /**
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.
480      *
481      * @param operationName
482      * @return
483      */
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);
487     }
488
489     /**
490      * Get the type of the data store to which this ActorContext belongs
491      *
492      * @return
493      */
494     public String getDataStoreType() {
495         return datastoreContext.getDataStoreType();
496     }
497
498     /**
499      * Set the number of transaction creation permits that are to be allowed
500      *
501      * @param permitsPerSecond
502      */
503     public void setTxCreationLimit(double permitsPerSecond){
504         txRateLimiter.setRate(permitsPerSecond);
505     }
506
507     /**
508      * Get the current transaction creation rate limit
509      * @return
510      */
511     public double getTxCreationLimit(){
512         return txRateLimiter.getRate();
513     }
514
515     /**
516      * Try to acquire a transaction creation permit. Will block if no permits are available.
517      */
518     public void acquireTxCreationPermit(){
519         txRateLimiter.acquire();
520     }
521
522     /**
523      * Return the operation timeout to be used when committing transactions
524      * @return
525      */
526     public Timeout getTransactionCommitOperationTimeout(){
527         return transactionCommitOperationTimeout;
528     }
529
530     /**
531      * An akka dispatcher that is meant to be used when processing ask Futures which were triggered by client
532      * code on the datastore
533      * @return
534      */
535     public ExecutionContext getClientDispatcher() {
536         return this.dispatchers.getDispatcher(Dispatchers.DispatcherType.Client);
537     }
538
539     public String getNotificationDispatcherPath(){
540         return this.dispatchers.getDispatcherPath(Dispatchers.DispatcherType.Notification);
541     }
542
543     protected Future<Object> doAsk(ActorRef actorRef, Object message, Timeout timeout){
544         return ask(actorRef, message, timeout);
545     }
546
547     protected Future<Object> doAsk(ActorSelection actorRef, Object message, Timeout timeout){
548         return ask(actorRef, message, timeout);
549     }
550
551     @VisibleForTesting
552     Cache<String, Future<ActorSelection>> getPrimaryShardActorSelectionCache() {
553         return primaryShardActorSelectionCache;
554     }
555 }