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;
24 import java.util.concurrent.ExecutionException;
25 import java.util.concurrent.TimeUnit;
26 import java.util.concurrent.TimeoutException;
27 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
28 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
29 import org.opendaylight.controller.cluster.databroker.actors.dds.DataStoreClient;
30 import org.opendaylight.controller.cluster.databroker.actors.dds.DistributedDataStoreClientActor;
31 import org.opendaylight.controller.cluster.datastore.config.Configuration;
32 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
33 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
34 import org.opendaylight.controller.cluster.datastore.shardmanager.AbstractShardManagerCreator;
35 import org.opendaylight.controller.cluster.datastore.shardmanager.ShardManagerCreator;
36 import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
37 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
38 import org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener;
39 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
40 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohort;
41 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistration;
42 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistry;
43 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
44 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTreeChangePublisher;
45 import org.opendaylight.yangtools.concepts.ListenerRegistration;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
47 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
48 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextListener;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51 import scala.concurrent.duration.Duration;
54 * Base implementation of a distributed DOMStore.
56 public abstract class AbstractDataStore implements DistributedDataStoreInterface, EffectiveModelContextListener,
57 DatastoreContextPropertiesUpdater.Listener, DOMStoreTreeChangePublisher,
58 DOMDataTreeCommitCohortRegistry, AutoCloseable {
60 private static final Logger LOG = LoggerFactory.getLogger(AbstractDataStore.class);
62 private final SettableFuture<Void> readinessFuture = SettableFuture.create();
63 private final ClientIdentifier identifier;
64 private final DataStoreClient client;
65 private final ActorUtils actorUtils;
67 private AutoCloseable closeable;
68 private DatastoreConfigurationMXBeanImpl datastoreConfigMXBean;
69 private DatastoreInfoMXBeanImpl datastoreInfoMXBean;
71 @SuppressWarnings("checkstyle:IllegalCatch")
72 protected AbstractDataStore(final ActorSystem actorSystem, final ClusterWrapper cluster,
73 final Configuration configuration, final DatastoreContextFactory datastoreContextFactory,
74 final DatastoreSnapshot restoreFromSnapshot) {
75 requireNonNull(actorSystem, "actorSystem should not be null");
76 requireNonNull(cluster, "cluster should not be null");
77 requireNonNull(configuration, "configuration should not be null");
78 requireNonNull(datastoreContextFactory, "datastoreContextFactory should not be null");
80 String shardManagerId = ShardManagerIdentifier.builder()
81 .type(datastoreContextFactory.getBaseDatastoreContext().getDataStoreName()).build().toString();
83 LOG.info("Creating ShardManager : {}", shardManagerId);
85 String shardDispatcher =
86 new Dispatchers(actorSystem.dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
88 PrimaryShardInfoFutureCache primaryShardInfoCache = new PrimaryShardInfoFutureCache();
90 AbstractShardManagerCreator<?> creator = getShardManagerCreator().cluster(cluster).configuration(configuration)
91 .datastoreContextFactory(datastoreContextFactory)
92 .readinessFuture(readinessFuture)
93 .primaryShardInfoCache(primaryShardInfoCache)
94 .restoreFromSnapshot(restoreFromSnapshot)
95 .distributedDataStore(this);
97 actorUtils = new ActorUtils(actorSystem, createShardManager(actorSystem, creator, shardDispatcher,
98 shardManagerId), cluster, configuration, datastoreContextFactory.getBaseDatastoreContext(),
99 primaryShardInfoCache);
101 final Props clientProps = DistributedDataStoreClientActor.props(cluster.getCurrentMemberName(),
102 datastoreContextFactory.getBaseDatastoreContext().getDataStoreName(), actorUtils);
103 final ActorRef clientActor = actorSystem.actorOf(clientProps);
105 client = DistributedDataStoreClientActor.getDistributedDataStoreClient(clientActor, 30, TimeUnit.SECONDS);
106 } catch (Exception e) {
107 LOG.error("Failed to get actor for {}", clientProps, e);
108 clientActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
109 Throwables.throwIfUnchecked(e);
110 throw new RuntimeException(e);
113 identifier = client.getIdentifier();
114 LOG.debug("Distributed data store client {} started", identifier);
116 datastoreConfigMXBean = new DatastoreConfigurationMXBeanImpl(
117 datastoreContextFactory.getBaseDatastoreContext().getDataStoreMXBeanType());
118 datastoreConfigMXBean.setContext(datastoreContextFactory.getBaseDatastoreContext());
119 datastoreConfigMXBean.registerMBean();
121 datastoreInfoMXBean = new DatastoreInfoMXBeanImpl(datastoreContextFactory.getBaseDatastoreContext()
122 .getDataStoreMXBeanType(), actorUtils);
123 datastoreInfoMXBean.registerMBean();
127 protected AbstractDataStore(final ActorUtils actorUtils, final ClientIdentifier identifier) {
128 this.actorUtils = requireNonNull(actorUtils, "actorContext should not be null");
130 this.identifier = requireNonNull(identifier);
134 protected AbstractDataStore(final ActorUtils actorUtils, final ClientIdentifier identifier,
135 final DataStoreClient clientActor) {
136 this.actorUtils = requireNonNull(actorUtils, "actorContext should not be null");
137 this.client = clientActor;
138 this.identifier = requireNonNull(identifier);
141 protected AbstractShardManagerCreator<?> getShardManagerCreator() {
142 return new ShardManagerCreator();
145 protected final DataStoreClient getClient() {
149 final ClientIdentifier getIdentifier() {
153 public void setCloseable(final AutoCloseable closeable) {
154 this.closeable = closeable;
158 public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerTreeChangeListener(
159 final YangInstanceIdentifier treeId, final L listener) {
160 requireNonNull(treeId, "treeId should not be null");
161 requireNonNull(listener, "listener should not be null");
164 * We need to potentially deal with multi-shard composition for registration targeting the root of the data
165 * store. If that is the case, we delegate to a more complicated setup invol
167 if (treeId.isEmpty()) {
168 // User is targeting root of the datastore. If there is more than one shard, we have to register with them
169 // all and perform data composition.
170 final Set<String> shardNames = actorUtils.getConfiguration().getAllShardNames();
171 if (shardNames.size() > 1) {
172 checkArgument(listener instanceof ClusteredDOMDataTreeChangeListener,
173 "Cannot listen on root without non-clustered listener %s", listener);
174 return new RootDataTreeChangeListenerProxy<>(actorUtils, listener, shardNames);
178 final String shardName = actorUtils.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
179 LOG.debug("Registering tree listener: {} for tree: {} shard: {}", listener, treeId, shardName);
181 final DataTreeChangeListenerProxy<L> listenerRegistrationProxy =
182 new DataTreeChangeListenerProxy<>(actorUtils, listener, treeId);
183 listenerRegistrationProxy.init(shardName);
185 return listenerRegistrationProxy;
189 public <C extends DOMDataTreeCommitCohort> DOMDataTreeCommitCohortRegistration<C> registerCommitCohort(
190 final DOMDataTreeIdentifier subtree, final C cohort) {
191 YangInstanceIdentifier treeId = requireNonNull(subtree, "subtree should not be null").getRootIdentifier();
192 requireNonNull(cohort, "listener should not be null");
195 final String shardName = actorUtils.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
196 LOG.debug("Registering cohort: {} for tree: {} shard: {}", cohort, treeId, shardName);
198 DataTreeCohortRegistrationProxy<C> cohortProxy =
199 new DataTreeCohortRegistrationProxy<>(actorUtils, subtree, cohort);
200 cohortProxy.init(shardName);
205 public void onModelContextUpdated(final EffectiveModelContext newModelContext) {
206 actorUtils.setSchemaContext(newModelContext);
210 public void onDatastoreContextUpdated(final DatastoreContextFactory contextFactory) {
211 LOG.info("DatastoreContext updated for data store {}", actorUtils.getDataStoreName());
213 actorUtils.setDatastoreContext(contextFactory);
214 datastoreConfigMXBean.setContext(contextFactory.getBaseDatastoreContext());
218 @SuppressWarnings("checkstyle:IllegalCatch")
219 public void close() {
220 LOG.info("Closing data store {}", identifier);
222 if (datastoreConfigMXBean != null) {
223 datastoreConfigMXBean.unregisterMBean();
225 if (datastoreInfoMXBean != null) {
226 datastoreInfoMXBean.unregisterMBean();
229 if (closeable != null) {
232 } catch (Exception e) {
233 LOG.debug("Error closing instance", e);
237 actorUtils.shutdown();
239 if (client != null) {
245 public ActorUtils getActorUtils() {
249 // TODO: consider removing this in favor of awaitReadiness()
251 public void waitTillReady() {
252 LOG.info("Beginning to wait for data store to become ready : {}", identifier);
254 final Duration toWait = initialSettleTime();
256 if (!awaitReadiness(toWait)) {
257 LOG.error("Shard leaders failed to settle in {}, giving up", toWait);
260 } catch (InterruptedException e) {
261 LOG.error("Interrupted while waiting for shards to settle", e);
265 LOG.debug("Data store {} is now ready", identifier);
270 public boolean awaitReadiness() throws InterruptedException {
271 return awaitReadiness(initialSettleTime());
276 public boolean awaitReadiness(final Duration toWait) throws InterruptedException {
278 if (toWait.isFinite()) {
280 readinessFuture.get(toWait.toNanos(), TimeUnit.NANOSECONDS);
281 } catch (TimeoutException e) {
282 LOG.debug("Timed out waiting for shards to settle", e);
286 readinessFuture.get();
288 } catch (ExecutionException e) {
289 LOG.warn("Unexpected readiness failure, assuming convergence", e);
297 public void awaitReadiness(final long timeout, final TimeUnit unit) throws InterruptedException, TimeoutException {
298 if (!awaitReadiness(Duration.create(timeout, unit))) {
299 throw new TimeoutException("Shard leaders failed to settle");
303 @SuppressWarnings("checkstyle:IllegalCatch")
304 private static ActorRef createShardManager(final ActorSystem actorSystem,
305 final AbstractShardManagerCreator<?> creator, final String shardDispatcher,
306 final String shardManagerId) {
307 Exception lastException = null;
309 for (int i = 0; i < 100; i++) {
311 return actorSystem.actorOf(creator.props().withDispatcher(shardDispatcher), shardManagerId);
312 } catch (Exception e) {
314 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
315 LOG.debug("Could not create actor {} because of {} - waiting for sometime before retrying "
316 + "(retry count = {})", shardManagerId, e.getMessage(), i);
320 throw new IllegalStateException("Failed to create Shard Manager", lastException);
324 * Future which completes when all shards settle for the first time.
326 * @return A Listenable future.
328 public final ListenableFuture<?> initialSettleFuture() {
329 return readinessFuture;
333 SettableFuture<Void> readinessFuture() {
334 return readinessFuture;
338 @SuppressWarnings("unchecked")
339 public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerProxyListener(
340 final YangInstanceIdentifier shardLookup, final YangInstanceIdentifier insideShard,
341 final DOMDataTreeChangeListener delegate) {
343 requireNonNull(shardLookup, "shardLookup should not be null");
344 requireNonNull(insideShard, "insideShard should not be null");
345 requireNonNull(delegate, "delegate should not be null");
347 final String shardName = actorUtils.getShardStrategyFactory().getStrategy(shardLookup).findShard(shardLookup);
348 LOG.debug("Registering tree listener: {} for tree: {} shard: {}, path inside shard: {}",
349 delegate,shardLookup, shardName, insideShard);
351 final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> listenerRegistrationProxy =
352 new DataTreeChangeListenerProxy<>(actorUtils,
353 // wrap this in the ClusteredDOMDataTreeChangeLister interface
354 // since we always want clustered registration
355 (ClusteredDOMDataTreeChangeListener) delegate::onDataTreeChanged, insideShard);
356 listenerRegistrationProxy.init(shardName);
358 return (ListenerRegistration<L>) listenerRegistrationProxy;
361 private Duration initialSettleTime() {
362 final DatastoreContext context = actorUtils.getDatastoreContext();
363 final int multiplier = context.getInitialSettleTimeoutMultiplier();
364 return multiplier == 0 ? Duration.Inf() : context.getShardLeaderElectionTimeout().duration().$times(multiplier);