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
8 package org.opendaylight.controller.cluster.datastore;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
13 import akka.actor.ActorRef;
14 import akka.actor.ActorSystem;
15 import akka.actor.PoisonPill;
16 import akka.actor.Props;
17 import com.google.common.annotations.Beta;
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.common.base.Throwables;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import com.google.common.util.concurrent.SettableFuture;
22 import com.google.common.util.concurrent.Uninterruptibles;
23 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
24 import java.util.List;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.TimeUnit;
28 import java.util.concurrent.TimeoutException;
29 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
30 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
31 import org.opendaylight.controller.cluster.databroker.actors.dds.DataStoreClient;
32 import org.opendaylight.controller.cluster.databroker.actors.dds.DistributedDataStoreClientActor;
33 import org.opendaylight.controller.cluster.datastore.config.Configuration;
34 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
35 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
36 import org.opendaylight.controller.cluster.datastore.shardmanager.AbstractShardManagerCreator;
37 import org.opendaylight.controller.cluster.datastore.shardmanager.ShardManagerCreator;
38 import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
39 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
40 import org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener;
41 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
42 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohort;
43 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistration;
44 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistry;
45 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
46 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTreeChangePublisher;
47 import org.opendaylight.yangtools.concepts.ListenerRegistration;
48 import org.opendaylight.yangtools.yang.common.Empty;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
50 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
51 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
52 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextListener;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import scala.concurrent.duration.Duration;
58 * Base implementation of a distributed DOMStore.
60 public abstract class AbstractDataStore implements DistributedDataStoreInterface, EffectiveModelContextListener,
61 DatastoreContextPropertiesUpdater.Listener, DOMStoreTreeChangePublisher,
62 DOMDataTreeCommitCohortRegistry, AutoCloseable {
64 private static final Logger LOG = LoggerFactory.getLogger(AbstractDataStore.class);
66 private final SettableFuture<Empty> readinessFuture = SettableFuture.create();
67 private final ClientIdentifier identifier;
68 private final DataStoreClient client;
69 private final ActorUtils actorUtils;
71 private AutoCloseable closeable;
72 private DatastoreConfigurationMXBeanImpl datastoreConfigMXBean;
73 private DatastoreInfoMXBeanImpl datastoreInfoMXBean;
75 @SuppressWarnings("checkstyle:IllegalCatch")
76 @SuppressFBWarnings(value = "MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR", justification = "Testing overrides")
77 protected AbstractDataStore(final ActorSystem actorSystem, final ClusterWrapper cluster,
78 final Configuration configuration, final DatastoreContextFactory datastoreContextFactory,
79 final DatastoreSnapshot restoreFromSnapshot) {
80 requireNonNull(actorSystem, "actorSystem should not be null");
81 requireNonNull(cluster, "cluster should not be null");
82 requireNonNull(configuration, "configuration should not be null");
83 requireNonNull(datastoreContextFactory, "datastoreContextFactory should not be null");
85 String shardManagerId = ShardManagerIdentifier.builder()
86 .type(datastoreContextFactory.getBaseDatastoreContext().getDataStoreName()).build().toString();
88 LOG.info("Creating ShardManager : {}", shardManagerId);
90 String shardDispatcher =
91 new Dispatchers(actorSystem.dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
93 PrimaryShardInfoFutureCache primaryShardInfoCache = new PrimaryShardInfoFutureCache();
95 AbstractShardManagerCreator<?> creator = getShardManagerCreator().cluster(cluster).configuration(configuration)
96 .datastoreContextFactory(datastoreContextFactory)
97 .readinessFuture(readinessFuture)
98 .primaryShardInfoCache(primaryShardInfoCache)
99 .restoreFromSnapshot(restoreFromSnapshot)
100 .distributedDataStore(this);
102 actorUtils = new ActorUtils(actorSystem, createShardManager(actorSystem, creator, shardDispatcher,
103 shardManagerId), cluster, configuration, datastoreContextFactory.getBaseDatastoreContext(),
104 primaryShardInfoCache);
106 final Props clientProps = DistributedDataStoreClientActor.props(cluster.getCurrentMemberName(),
107 datastoreContextFactory.getBaseDatastoreContext().getDataStoreName(), actorUtils);
108 final ActorRef clientActor = actorSystem.actorOf(clientProps);
110 client = DistributedDataStoreClientActor.getDistributedDataStoreClient(clientActor, 30, TimeUnit.SECONDS);
111 } catch (Exception e) {
112 LOG.error("Failed to get actor for {}", clientProps, e);
113 clientActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
114 Throwables.throwIfUnchecked(e);
115 throw new IllegalStateException(e);
118 identifier = client.getIdentifier();
119 LOG.debug("Distributed data store client {} started", identifier);
121 datastoreConfigMXBean = new DatastoreConfigurationMXBeanImpl(
122 datastoreContextFactory.getBaseDatastoreContext().getDataStoreMXBeanType());
123 datastoreConfigMXBean.setContext(datastoreContextFactory.getBaseDatastoreContext());
124 datastoreConfigMXBean.registerMBean();
126 datastoreInfoMXBean = new DatastoreInfoMXBeanImpl(datastoreContextFactory.getBaseDatastoreContext()
127 .getDataStoreMXBeanType(), actorUtils);
128 datastoreInfoMXBean.registerMBean();
132 protected AbstractDataStore(final ActorUtils actorUtils, final ClientIdentifier identifier,
133 final DataStoreClient clientActor) {
134 this.actorUtils = requireNonNull(actorUtils, "actorContext should not be null");
135 client = clientActor;
136 this.identifier = requireNonNull(identifier);
139 protected AbstractShardManagerCreator<?> getShardManagerCreator() {
140 return new ShardManagerCreator();
143 protected final DataStoreClient getClient() {
147 final ClientIdentifier getIdentifier() {
151 public void setCloseable(final AutoCloseable closeable) {
152 this.closeable = closeable;
156 public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerTreeChangeListener(
157 final YangInstanceIdentifier treeId, final L listener) {
158 requireNonNull(treeId, "treeId should not be null");
159 requireNonNull(listener, "listener should not be null");
162 * We need to potentially deal with multi-shard composition for registration targeting the root of the data
163 * store. If that is the case, we delegate to a more complicated setup invol
165 if (treeId.isEmpty()) {
166 // User is targeting root of the datastore. If there is more than one shard, we have to register with them
167 // all and perform data composition.
168 final Set<String> shardNames = actorUtils.getConfiguration().getAllShardNames();
169 if (shardNames.size() > 1) {
170 checkArgument(listener instanceof ClusteredDOMDataTreeChangeListener,
171 "Cannot listen on root without non-clustered listener %s", listener);
172 return new RootDataTreeChangeListenerProxy<>(actorUtils, listener, shardNames);
176 final String shardName = actorUtils.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
177 LOG.debug("Registering tree listener: {} for tree: {} shard: {}", listener, treeId, shardName);
179 final DataTreeChangeListenerProxy<L> listenerRegistrationProxy =
180 new DataTreeChangeListenerProxy<>(actorUtils, listener, treeId);
181 listenerRegistrationProxy.init(shardName);
183 return listenerRegistrationProxy;
187 public <C extends DOMDataTreeCommitCohort> DOMDataTreeCommitCohortRegistration<C> registerCommitCohort(
188 final DOMDataTreeIdentifier subtree, final C cohort) {
189 YangInstanceIdentifier treeId = requireNonNull(subtree, "subtree should not be null").getRootIdentifier();
190 requireNonNull(cohort, "listener should not be null");
193 final String shardName = actorUtils.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
194 LOG.debug("Registering cohort: {} for tree: {} shard: {}", cohort, treeId, shardName);
196 DataTreeCohortRegistrationProxy<C> cohortProxy =
197 new DataTreeCohortRegistrationProxy<>(actorUtils, subtree, cohort);
198 cohortProxy.init(shardName);
203 public void onModelContextUpdated(final EffectiveModelContext newModelContext) {
204 actorUtils.setSchemaContext(newModelContext);
208 public void onDatastoreContextUpdated(final DatastoreContextFactory contextFactory) {
209 LOG.info("DatastoreContext updated for data store {}", actorUtils.getDataStoreName());
211 actorUtils.setDatastoreContext(contextFactory);
212 datastoreConfigMXBean.setContext(contextFactory.getBaseDatastoreContext());
216 @SuppressWarnings("checkstyle:IllegalCatch")
217 public void close() {
218 LOG.info("Closing data store {}", identifier);
220 if (datastoreConfigMXBean != null) {
221 datastoreConfigMXBean.unregisterMBean();
223 if (datastoreInfoMXBean != null) {
224 datastoreInfoMXBean.unregisterMBean();
227 if (closeable != null) {
230 } catch (Exception e) {
231 LOG.debug("Error closing instance", e);
235 actorUtils.shutdown();
237 if (client != null) {
243 public final ActorUtils getActorUtils() {
247 // TODO: consider removing this in favor of awaitReadiness()
249 public void waitTillReady() {
250 LOG.info("Beginning to wait for data store to become ready : {}", identifier);
252 final Duration toWait = initialSettleTime();
254 if (!awaitReadiness(toWait)) {
255 LOG.error("Shard leaders failed to settle in {}, giving up", toWait);
258 } catch (InterruptedException e) {
259 LOG.error("Interrupted while waiting for shards to settle", e);
263 LOG.debug("Data store {} is now ready", identifier);
268 public boolean awaitReadiness() throws InterruptedException {
269 return awaitReadiness(initialSettleTime());
274 public boolean awaitReadiness(final Duration toWait) throws InterruptedException {
276 if (toWait.isFinite()) {
278 readinessFuture.get(toWait.toNanos(), TimeUnit.NANOSECONDS);
279 } catch (TimeoutException e) {
280 LOG.debug("Timed out waiting for shards to settle", e);
284 readinessFuture.get();
286 } catch (ExecutionException e) {
287 LOG.warn("Unexpected readiness failure, assuming convergence", e);
295 public void awaitReadiness(final long timeout, final TimeUnit unit) throws InterruptedException, TimeoutException {
296 if (!awaitReadiness(Duration.create(timeout, unit))) {
297 throw new TimeoutException("Shard leaders failed to settle");
301 @SuppressWarnings("checkstyle:IllegalCatch")
302 private static ActorRef createShardManager(final ActorSystem actorSystem,
303 final AbstractShardManagerCreator<?> creator, final String shardDispatcher,
304 final String shardManagerId) {
305 Exception lastException = null;
307 for (int i = 0; i < 100; i++) {
309 return actorSystem.actorOf(creator.props().withDispatcher(shardDispatcher), shardManagerId);
310 } catch (Exception e) {
312 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
313 LOG.debug("Could not create actor {} because of {} - waiting for sometime before retrying "
314 + "(retry count = {})", shardManagerId, e.getMessage(), i);
318 throw new IllegalStateException("Failed to create Shard Manager", lastException);
322 * Future which completes when all shards settle for the first time.
324 * @return A Listenable future.
326 public final ListenableFuture<?> initialSettleFuture() {
327 return readinessFuture;
331 public final SettableFuture<Empty> readinessFuture() {
332 return readinessFuture;
336 @SuppressWarnings("unchecked")
337 public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerProxyListener(
338 final YangInstanceIdentifier shardLookup, final YangInstanceIdentifier insideShard,
339 final DOMDataTreeChangeListener delegate) {
341 requireNonNull(shardLookup, "shardLookup should not be null");
342 requireNonNull(insideShard, "insideShard should not be null");
343 requireNonNull(delegate, "delegate should not be null");
345 final String shardName = actorUtils.getShardStrategyFactory().getStrategy(shardLookup).findShard(shardLookup);
346 LOG.debug("Registering tree listener: {} for tree: {} shard: {}, path inside shard: {}",
347 delegate,shardLookup, shardName, insideShard);
349 // wrap this in the ClusteredDOMDataTreeChangeLister interface
350 // since we always want clustered registration
351 final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> listenerRegistrationProxy =
352 new DataTreeChangeListenerProxy<>(actorUtils, new ClusteredDOMDataTreeChangeListener() {
354 public void onDataTreeChanged(final List<DataTreeCandidate> changes) {
355 delegate.onDataTreeChanged(changes);
359 public void onInitialData() {
360 delegate.onInitialData();
363 listenerRegistrationProxy.init(shardName);
365 return (ListenerRegistration<L>) listenerRegistrationProxy;
368 private Duration initialSettleTime() {
369 final DatastoreContext context = actorUtils.getDatastoreContext();
370 final int multiplier = context.getInitialSettleTimeoutMultiplier();
371 return multiplier == 0 ? Duration.Inf() : context.getShardLeaderElectionTimeout().duration().$times(multiplier);