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 java.util.Collection;
25 import java.util.concurrent.ExecutionException;
26 import java.util.concurrent.TimeUnit;
27 import java.util.concurrent.TimeoutException;
28 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
29 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
30 import org.opendaylight.controller.cluster.databroker.actors.dds.DataStoreClient;
31 import org.opendaylight.controller.cluster.databroker.actors.dds.DistributedDataStoreClientActor;
32 import org.opendaylight.controller.cluster.datastore.config.Configuration;
33 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
34 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.DatastoreConfigurationMXBeanImpl;
35 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.DatastoreInfoMXBeanImpl;
36 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
37 import org.opendaylight.controller.cluster.datastore.shardmanager.AbstractShardManagerCreator;
38 import org.opendaylight.controller.cluster.datastore.shardmanager.ShardManagerCreator;
39 import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
40 import org.opendaylight.controller.cluster.datastore.utils.ClusterUtils;
41 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
42 import org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener;
43 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
44 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohort;
45 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistration;
46 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistry;
47 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
48 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTreeChangePublisher;
49 import org.opendaylight.yangtools.concepts.ListenerRegistration;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
51 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
52 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
53 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextListener;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import scala.concurrent.duration.Duration;
59 * Base implementation of a distributed DOMStore.
61 public abstract class AbstractDataStore implements DistributedDataStoreInterface, EffectiveModelContextListener,
62 DatastoreContextPropertiesUpdater.Listener, DOMStoreTreeChangePublisher,
63 DOMDataTreeCommitCohortRegistry, AutoCloseable {
65 private static final Logger LOG = LoggerFactory.getLogger(AbstractDataStore.class);
67 private final SettableFuture<Void> readinessFuture = SettableFuture.create();
68 private final ClientIdentifier identifier;
69 private final DataStoreClient client;
70 private final ActorUtils actorUtils;
72 private AutoCloseable closeable;
73 private DatastoreConfigurationMXBeanImpl datastoreConfigMXBean;
74 private DatastoreInfoMXBeanImpl datastoreInfoMXBean;
76 @SuppressWarnings("checkstyle:IllegalCatch")
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 RuntimeException(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 this.actorUtils = requireNonNull(actorUtils, "actorContext should not be null");
135 this.identifier = requireNonNull(identifier);
139 protected AbstractDataStore(final ActorUtils actorUtils, final ClientIdentifier identifier,
140 final DataStoreClient clientActor) {
141 this.actorUtils = requireNonNull(actorUtils, "actorContext should not be null");
142 this.client = clientActor;
143 this.identifier = requireNonNull(identifier);
146 protected AbstractShardManagerCreator<?> getShardManagerCreator() {
147 return new ShardManagerCreator();
150 protected final DataStoreClient getClient() {
154 final ClientIdentifier getIdentifier() {
158 public void setCloseable(final AutoCloseable closeable) {
159 this.closeable = closeable;
163 public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerTreeChangeListener(
164 final YangInstanceIdentifier treeId, final L listener) {
165 requireNonNull(treeId, "treeId should not be null");
166 requireNonNull(listener, "listener should not be null");
169 * We need to potentially deal with multi-shard composition for registration targeting the root of the data
170 * store. If that is the case, we delegate to a more complicated setup invol
172 if (treeId.isEmpty()) {
173 // User is targeting root of the datastore. If there is more than one shard, we have to register with them
174 // all and perform data composition.
175 final Set<String> shardNames = actorUtils.getConfiguration().getAllShardNames();
176 if (shardNames.size() > 1) {
177 checkArgument(listener instanceof ClusteredDOMDataTreeChangeListener,
178 "Cannot listen on root without non-clustered listener %s", listener);
179 return new RootDataTreeChangeListenerProxy<>(actorUtils, listener, shardNames);
183 final String shardName = actorUtils.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
184 LOG.debug("Registering tree listener: {} for tree: {} shard: {}", listener, treeId, shardName);
186 final DataTreeChangeListenerProxy<L> listenerRegistrationProxy =
187 new DataTreeChangeListenerProxy<>(actorUtils, listener, treeId);
188 listenerRegistrationProxy.init(shardName);
190 return listenerRegistrationProxy;
194 public <C extends DOMDataTreeCommitCohort> DOMDataTreeCommitCohortRegistration<C> registerCommitCohort(
195 final DOMDataTreeIdentifier subtree, final C cohort) {
196 YangInstanceIdentifier treeId = requireNonNull(subtree, "subtree should not be null").getRootIdentifier();
197 requireNonNull(cohort, "listener should not be null");
200 final String shardName = actorUtils.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
201 LOG.debug("Registering cohort: {} for tree: {} shard: {}", cohort, treeId, shardName);
203 DataTreeCohortRegistrationProxy<C> cohortProxy =
204 new DataTreeCohortRegistrationProxy<>(actorUtils, subtree, cohort);
205 cohortProxy.init(shardName);
210 public void onModelContextUpdated(final EffectiveModelContext newModelContext) {
211 actorUtils.setSchemaContext(newModelContext);
215 public void onDatastoreContextUpdated(final DatastoreContextFactory contextFactory) {
216 LOG.info("DatastoreContext updated for data store {}", actorUtils.getDataStoreName());
218 actorUtils.setDatastoreContext(contextFactory);
219 datastoreConfigMXBean.setContext(contextFactory.getBaseDatastoreContext());
223 @SuppressWarnings("checkstyle:IllegalCatch")
224 public void close() {
225 LOG.info("Closing data store {}", identifier);
227 if (datastoreConfigMXBean != null) {
228 datastoreConfigMXBean.unregisterMBean();
230 if (datastoreInfoMXBean != null) {
231 datastoreInfoMXBean.unregisterMBean();
234 if (closeable != null) {
237 } catch (Exception e) {
238 LOG.debug("Error closing instance", e);
242 actorUtils.shutdown();
244 if (client != null) {
250 public ActorUtils getActorUtils() {
254 // TODO: consider removing this in favor of awaitReadiness()
256 public void waitTillReady() {
257 LOG.info("Beginning to wait for data store to become ready : {}", identifier);
259 final Duration toWait = initialSettleTime();
261 if (!awaitReadiness(toWait)) {
262 LOG.error("Shard leaders failed to settle in {}, giving up", toWait);
265 } catch (InterruptedException e) {
266 LOG.error("Interrupted while waiting for shards to settle", e);
270 LOG.debug("Data store {} is now ready", identifier);
275 public boolean awaitReadiness() throws InterruptedException {
276 return awaitReadiness(initialSettleTime());
281 public boolean awaitReadiness(final Duration toWait) throws InterruptedException {
283 if (toWait.isFinite()) {
285 readinessFuture.get(toWait.toNanos(), TimeUnit.NANOSECONDS);
286 } catch (TimeoutException e) {
287 LOG.debug("Timed out waiting for shards to settle", e);
291 readinessFuture.get();
293 } catch (ExecutionException e) {
294 LOG.warn("Unexpected readiness failure, assuming convergence", e);
302 public void awaitReadiness(final long timeout, final TimeUnit unit) throws InterruptedException, TimeoutException {
303 if (!awaitReadiness(Duration.create(timeout, unit))) {
304 throw new TimeoutException("Shard leaders failed to settle");
308 @SuppressWarnings("checkstyle:IllegalCatch")
309 private static ActorRef createShardManager(final ActorSystem actorSystem,
310 final AbstractShardManagerCreator<?> creator, final String shardDispatcher,
311 final String shardManagerId) {
312 Exception lastException = null;
314 for (int i = 0; i < 100; i++) {
316 return actorSystem.actorOf(creator.props().withDispatcher(shardDispatcher), shardManagerId);
317 } catch (Exception e) {
319 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
320 LOG.debug("Could not create actor {} because of {} - waiting for sometime before retrying "
321 + "(retry count = {})", shardManagerId, e.getMessage(), i);
325 throw new IllegalStateException("Failed to create Shard Manager", lastException);
329 * Future which completes when all shards settle for the first time.
331 * @return A Listenable future.
333 public final ListenableFuture<?> initialSettleFuture() {
334 return readinessFuture;
338 SettableFuture<Void> readinessFuture() {
339 return readinessFuture;
343 @SuppressWarnings("unchecked")
344 public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerProxyListener(
345 final YangInstanceIdentifier shardLookup, final YangInstanceIdentifier insideShard,
346 final DOMDataTreeChangeListener delegate) {
348 requireNonNull(shardLookup, "shardLookup should not be null");
349 requireNonNull(insideShard, "insideShard should not be null");
350 requireNonNull(delegate, "delegate should not be null");
352 final String shardName = actorUtils.getShardStrategyFactory().getStrategy(shardLookup).findShard(shardLookup);
353 LOG.debug("Registering tree listener: {} for tree: {} shard: {}, path inside shard: {}",
354 delegate,shardLookup, shardName, insideShard);
356 // wrap this in the ClusteredDOMDataTreeChangeLister interface
357 // since we always want clustered registration
358 final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> listenerRegistrationProxy =
359 new DataTreeChangeListenerProxy<>(actorUtils, new ClusteredDOMDataTreeChangeListener() {
361 public void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
362 delegate.onDataTreeChanged(changes);
366 public void onInitialData() {
367 delegate.onInitialData();
370 listenerRegistrationProxy.init(shardName);
372 return (ListenerRegistration<L>) listenerRegistrationProxy;
376 @SuppressWarnings("unchecked")
377 public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerShardConfigListener(
378 final YangInstanceIdentifier internalPath, final DOMDataTreeChangeListener delegate) {
379 requireNonNull(delegate, "delegate should not be null");
381 LOG.debug("Registering a listener for the configuration shard: {}", internalPath);
383 final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy =
384 new DataTreeChangeListenerProxy<>(actorUtils, delegate, internalPath);
385 proxy.init(ClusterUtils.PREFIX_CONFIG_SHARD_ID);
387 return (ListenerRegistration<L>) proxy;
390 private Duration initialSettleTime() {
391 final DatastoreContext context = actorUtils.getDatastoreContext();
392 final int multiplier = context.getInitialSettleTimeoutMultiplier();
393 return multiplier == 0 ? Duration.Inf() : context.getShardLeaderElectionTimeout().duration().$times(multiplier);