2 * Copyright (c) 2017 Inocybe Technologies 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
8 package org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard;
10 import akka.actor.ActorRef;
11 import akka.pattern.Patterns;
12 import akka.util.Timeout;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Stopwatch;
15 import com.google.common.base.Throwables;
16 import com.google.common.cache.Cache;
17 import com.google.common.cache.CacheBuilder;
18 import com.google.common.util.concurrent.ExecutionError;
19 import com.google.common.util.concurrent.UncheckedExecutionException;
20 import java.util.concurrent.ExecutionException;
21 import java.util.concurrent.TimeUnit;
22 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
23 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
24 import scala.concurrent.Await;
27 * Maintains a short-lived shared cache of OnDemandShardState.
29 * @author Thomas Pantelis
31 class OnDemandShardStateCache {
32 private static final Cache<String, OnDemandShardState> ONDEMAND_SHARD_STATE_CACHE =
33 CacheBuilder.newBuilder().expireAfterWrite(2, TimeUnit.SECONDS).build();
35 private final ActorRef shardActor;
36 private final String shardName;
37 private volatile String stateRetrievalTime;
39 OnDemandShardStateCache(String shardName, ActorRef shardActor) {
40 this.shardName = Preconditions.checkNotNull(shardName);
41 this.shardActor = shardActor;
44 OnDemandShardState get() throws Exception {
45 if (shardActor == null) {
46 return OnDemandShardState.newBuilder().build();
50 return ONDEMAND_SHARD_STATE_CACHE.get(shardName, this::retrieveState);
51 } catch (ExecutionException | UncheckedExecutionException | ExecutionError e) {
52 if (e.getCause() != null) {
53 Throwables.propagateIfPossible(e.getCause(), Exception.class);
54 throw new RuntimeException("unexpected", e.getCause());
61 String getStatRetrievaelTime() {
62 return stateRetrievalTime;
65 private OnDemandShardState retrieveState() throws Exception {
66 stateRetrievalTime = null;
67 Timeout timeout = new Timeout(10, TimeUnit.SECONDS);
68 Stopwatch timer = Stopwatch.createStarted();
70 OnDemandShardState state = (OnDemandShardState) Await.result(Patterns.ask(shardActor,
71 GetOnDemandRaftState.INSTANCE, timeout), timeout.duration());
73 stateRetrievalTime = timer.stop().toString();