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.persisted.DatastoreSnapshot;
35 import org.opendaylight.controller.cluster.datastore.shardmanager.AbstractShardManagerCreator;
36 import org.opendaylight.controller.cluster.datastore.shardmanager.ShardManagerCreator;
37 import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
38 import org.opendaylight.controller.cluster.datastore.utils.ClusterUtils;
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.data.api.YangInstanceIdentifier;
49 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
50 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
51 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextListener;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import scala.concurrent.duration.Duration;
57 * Base implementation of a distributed DOMStore.
59 public abstract class AbstractDataStore implements DistributedDataStoreInterface, EffectiveModelContextListener,
60 DatastoreContextPropertiesUpdater.Listener, DOMStoreTreeChangePublisher,
61 DOMDataTreeCommitCohortRegistry, AutoCloseable {
63 private static final Logger LOG = LoggerFactory.getLogger(AbstractDataStore.class);
65 private final SettableFuture<Void> readinessFuture = SettableFuture.create();
66 private final ClientIdentifier identifier;
67 private final DataStoreClient client;
68 private final ActorUtils actorUtils;
70 private AutoCloseable closeable;
71 private DatastoreConfigurationMXBeanImpl datastoreConfigMXBean;
72 private DatastoreInfoMXBeanImpl datastoreInfoMXBean;
74 @SuppressWarnings("checkstyle:IllegalCatch")
75 protected AbstractDataStore(final ActorSystem actorSystem, final ClusterWrapper cluster,
76 final Configuration configuration, final DatastoreContextFactory datastoreContextFactory,
77 final DatastoreSnapshot restoreFromSnapshot) {
78 requireNonNull(actorSystem, "actorSystem should not be null");
79 requireNonNull(cluster, "cluster should not be null");
80 requireNonNull(configuration, "configuration should not be null");
81 requireNonNull(datastoreContextFactory, "datastoreContextFactory should not be null");
83 String shardManagerId = ShardManagerIdentifier.builder()
84 .type(datastoreContextFactory.getBaseDatastoreContext().getDataStoreName()).build().toString();
86 LOG.info("Creating ShardManager : {}", shardManagerId);
88 String shardDispatcher =
89 new Dispatchers(actorSystem.dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
91 PrimaryShardInfoFutureCache primaryShardInfoCache = new PrimaryShardInfoFutureCache();
93 AbstractShardManagerCreator<?> creator = getShardManagerCreator().cluster(cluster).configuration(configuration)
94 .datastoreContextFactory(datastoreContextFactory)
95 .readinessFuture(readinessFuture)
96 .primaryShardInfoCache(primaryShardInfoCache)
97 .restoreFromSnapshot(restoreFromSnapshot)
98 .distributedDataStore(this);
100 actorUtils = new ActorUtils(actorSystem, createShardManager(actorSystem, creator, shardDispatcher,
101 shardManagerId), cluster, configuration, datastoreContextFactory.getBaseDatastoreContext(),
102 primaryShardInfoCache);
104 final Props clientProps = DistributedDataStoreClientActor.props(cluster.getCurrentMemberName(),
105 datastoreContextFactory.getBaseDatastoreContext().getDataStoreName(), actorUtils);
106 final ActorRef clientActor = actorSystem.actorOf(clientProps);
108 client = DistributedDataStoreClientActor.getDistributedDataStoreClient(clientActor, 30, TimeUnit.SECONDS);
109 } catch (Exception e) {
110 LOG.error("Failed to get actor for {}", clientProps, e);
111 clientActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
112 Throwables.throwIfUnchecked(e);
113 throw new RuntimeException(e);
116 identifier = client.getIdentifier();
117 LOG.debug("Distributed data store client {} started", identifier);
119 datastoreConfigMXBean = new DatastoreConfigurationMXBeanImpl(
120 datastoreContextFactory.getBaseDatastoreContext().getDataStoreMXBeanType());
121 datastoreConfigMXBean.setContext(datastoreContextFactory.getBaseDatastoreContext());
122 datastoreConfigMXBean.registerMBean();
124 datastoreInfoMXBean = new DatastoreInfoMXBeanImpl(datastoreContextFactory.getBaseDatastoreContext()
125 .getDataStoreMXBeanType(), actorUtils);
126 datastoreInfoMXBean.registerMBean();
130 protected AbstractDataStore(final ActorUtils actorUtils, final ClientIdentifier identifier) {
131 this.actorUtils = requireNonNull(actorUtils, "actorContext should not be null");
133 this.identifier = requireNonNull(identifier);
137 protected AbstractDataStore(final ActorUtils actorUtils, final ClientIdentifier identifier,
138 final DataStoreClient clientActor) {
139 this.actorUtils = requireNonNull(actorUtils, "actorContext should not be null");
140 this.client = clientActor;
141 this.identifier = requireNonNull(identifier);
144 protected AbstractShardManagerCreator<?> getShardManagerCreator() {
145 return new ShardManagerCreator();
148 protected final DataStoreClient getClient() {
152 final ClientIdentifier getIdentifier() {
156 public void setCloseable(final AutoCloseable closeable) {
157 this.closeable = closeable;
161 public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerTreeChangeListener(
162 final YangInstanceIdentifier treeId, final L listener) {
163 requireNonNull(treeId, "treeId should not be null");
164 requireNonNull(listener, "listener should not be null");
167 * We need to potentially deal with multi-shard composition for registration targeting the root of the data
168 * store. If that is the case, we delegate to a more complicated setup invol
170 if (treeId.isEmpty()) {
171 // User is targeting root of the datastore. If there is more than one shard, we have to register with them
172 // all and perform data composition.
173 final Set<String> shardNames = actorUtils.getConfiguration().getAllShardNames();
174 if (shardNames.size() > 1) {
175 checkArgument(listener instanceof ClusteredDOMDataTreeChangeListener,
176 "Cannot listen on root without non-clustered listener %s", listener);
177 return new RootDataTreeChangeListenerProxy<>(actorUtils, listener, shardNames);
181 final String shardName = actorUtils.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
182 LOG.debug("Registering tree listener: {} for tree: {} shard: {}", listener, treeId, shardName);
184 final DataTreeChangeListenerProxy<L> listenerRegistrationProxy =
185 new DataTreeChangeListenerProxy<>(actorUtils, listener, treeId);
186 listenerRegistrationProxy.init(shardName);
188 return listenerRegistrationProxy;
192 public <C extends DOMDataTreeCommitCohort> DOMDataTreeCommitCohortRegistration<C> registerCommitCohort(
193 final DOMDataTreeIdentifier subtree, final C cohort) {
194 YangInstanceIdentifier treeId = requireNonNull(subtree, "subtree should not be null").getRootIdentifier();
195 requireNonNull(cohort, "listener should not be null");
198 final String shardName = actorUtils.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
199 LOG.debug("Registering cohort: {} for tree: {} shard: {}", cohort, treeId, shardName);
201 DataTreeCohortRegistrationProxy<C> cohortProxy =
202 new DataTreeCohortRegistrationProxy<>(actorUtils, subtree, cohort);
203 cohortProxy.init(shardName);
208 public void onModelContextUpdated(final EffectiveModelContext newModelContext) {
209 actorUtils.setSchemaContext(newModelContext);
213 public void onDatastoreContextUpdated(final DatastoreContextFactory contextFactory) {
214 LOG.info("DatastoreContext updated for data store {}", actorUtils.getDataStoreName());
216 actorUtils.setDatastoreContext(contextFactory);
217 datastoreConfigMXBean.setContext(contextFactory.getBaseDatastoreContext());
221 @SuppressWarnings("checkstyle:IllegalCatch")
222 public void close() {
223 LOG.info("Closing data store {}", identifier);
225 if (datastoreConfigMXBean != null) {
226 datastoreConfigMXBean.unregisterMBean();
228 if (datastoreInfoMXBean != null) {
229 datastoreInfoMXBean.unregisterMBean();
232 if (closeable != null) {
235 } catch (Exception e) {
236 LOG.debug("Error closing instance", e);
240 actorUtils.shutdown();
242 if (client != null) {
248 public ActorUtils getActorUtils() {
252 // TODO: consider removing this in favor of awaitReadiness()
254 public void waitTillReady() {
255 LOG.info("Beginning to wait for data store to become ready : {}", identifier);
257 final Duration toWait = initialSettleTime();
259 if (!awaitReadiness(toWait)) {
260 LOG.error("Shard leaders failed to settle in {}, giving up", toWait);
263 } catch (InterruptedException e) {
264 LOG.error("Interrupted while waiting for shards to settle", e);
268 LOG.debug("Data store {} is now ready", identifier);
273 public boolean awaitReadiness() throws InterruptedException {
274 return awaitReadiness(initialSettleTime());
279 public boolean awaitReadiness(final Duration toWait) throws InterruptedException {
281 if (toWait.isFinite()) {
283 readinessFuture.get(toWait.toNanos(), TimeUnit.NANOSECONDS);
284 } catch (TimeoutException e) {
285 LOG.debug("Timed out waiting for shards to settle", e);
289 readinessFuture.get();
291 } catch (ExecutionException e) {
292 LOG.warn("Unexpected readiness failure, assuming convergence", e);
300 public void awaitReadiness(final long timeout, final TimeUnit unit) throws InterruptedException, TimeoutException {
301 if (!awaitReadiness(Duration.create(timeout, unit))) {
302 throw new TimeoutException("Shard leaders failed to settle");
306 @SuppressWarnings("checkstyle:IllegalCatch")
307 private static ActorRef createShardManager(final ActorSystem actorSystem,
308 final AbstractShardManagerCreator<?> creator, final String shardDispatcher,
309 final String shardManagerId) {
310 Exception lastException = null;
312 for (int i = 0; i < 100; i++) {
314 return actorSystem.actorOf(creator.props().withDispatcher(shardDispatcher), shardManagerId);
315 } catch (Exception e) {
317 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
318 LOG.debug("Could not create actor {} because of {} - waiting for sometime before retrying "
319 + "(retry count = {})", shardManagerId, e.getMessage(), i);
323 throw new IllegalStateException("Failed to create Shard Manager", lastException);
327 * Future which completes when all shards settle for the first time.
329 * @return A Listenable future.
331 public final ListenableFuture<?> initialSettleFuture() {
332 return readinessFuture;
336 SettableFuture<Void> readinessFuture() {
337 return readinessFuture;
341 @SuppressWarnings("unchecked")
342 public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerProxyListener(
343 final YangInstanceIdentifier shardLookup, final YangInstanceIdentifier insideShard,
344 final DOMDataTreeChangeListener delegate) {
346 requireNonNull(shardLookup, "shardLookup should not be null");
347 requireNonNull(insideShard, "insideShard should not be null");
348 requireNonNull(delegate, "delegate should not be null");
350 final String shardName = actorUtils.getShardStrategyFactory().getStrategy(shardLookup).findShard(shardLookup);
351 LOG.debug("Registering tree listener: {} for tree: {} shard: {}, path inside shard: {}",
352 delegate,shardLookup, shardName, insideShard);
354 // wrap this in the ClusteredDOMDataTreeChangeLister interface
355 // since we always want clustered registration
356 final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> listenerRegistrationProxy =
357 new DataTreeChangeListenerProxy<>(actorUtils, new ClusteredDOMDataTreeChangeListener() {
359 public void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
360 delegate.onDataTreeChanged(changes);
364 public void onInitialData() {
365 delegate.onInitialData();
368 listenerRegistrationProxy.init(shardName);
370 return (ListenerRegistration<L>) listenerRegistrationProxy;
374 @SuppressWarnings("unchecked")
375 public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerShardConfigListener(
376 final YangInstanceIdentifier internalPath, final DOMDataTreeChangeListener delegate) {
377 requireNonNull(delegate, "delegate should not be null");
379 LOG.debug("Registering a listener for the configuration shard: {}", internalPath);
381 final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy =
382 new DataTreeChangeListenerProxy<>(actorUtils, delegate, internalPath);
383 proxy.init(ClusterUtils.PREFIX_CONFIG_SHARD_ID);
385 return (ListenerRegistration<L>) proxy;
388 private Duration initialSettleTime() {
389 final DatastoreContext context = actorUtils.getDatastoreContext();
390 final int multiplier = context.getInitialSettleTimeoutMultiplier();
391 return multiplier == 0 ? Duration.Inf() : context.getShardLeaderElectionTimeout().duration().$times(multiplier);