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 java.util.Objects.requireNonNull;
12 import akka.actor.ActorRef;
13 import akka.actor.ActorSystem;
14 import akka.actor.PoisonPill;
15 import akka.actor.Props;
16 import com.google.common.annotations.VisibleForTesting;
17 import com.google.common.base.Throwables;
18 import com.google.common.util.concurrent.Uninterruptibles;
19 import java.util.concurrent.CountDownLatch;
20 import java.util.concurrent.TimeUnit;
21 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
22 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
23 import org.opendaylight.controller.cluster.databroker.actors.dds.DataStoreClient;
24 import org.opendaylight.controller.cluster.databroker.actors.dds.DistributedDataStoreClientActor;
25 import org.opendaylight.controller.cluster.datastore.config.Configuration;
26 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
27 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.DatastoreConfigurationMXBeanImpl;
28 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.DatastoreInfoMXBeanImpl;
29 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
30 import org.opendaylight.controller.cluster.datastore.shardmanager.ShardManagerCreator;
31 import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
32 import org.opendaylight.controller.cluster.datastore.utils.ClusterUtils;
33 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
34 import org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener;
35 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
36 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohort;
37 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistration;
38 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistry;
39 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
40 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTreeChangePublisher;
41 import org.opendaylight.yangtools.concepts.ListenerRegistration;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
43 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
44 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
49 * Base implementation of a distributed DOMStore.
51 public abstract class AbstractDataStore implements DistributedDataStoreInterface, SchemaContextListener,
52 DatastoreContextPropertiesUpdater.Listener, DOMStoreTreeChangePublisher,
53 DOMDataTreeCommitCohortRegistry, AutoCloseable {
55 private static final Logger LOG = LoggerFactory.getLogger(AbstractDataStore.class);
57 private static final long READY_WAIT_FACTOR = 3;
59 private final ActorUtils actorUtils;
60 private final long waitTillReadyTimeInMillis;
62 private AutoCloseable closeable;
64 private DatastoreConfigurationMXBeanImpl datastoreConfigMXBean;
66 private DatastoreInfoMXBeanImpl datastoreInfoMXBean;
68 private final CountDownLatch waitTillReadyCountDownLatch = new CountDownLatch(1);
70 private final ClientIdentifier identifier;
71 private final DataStoreClient client;
73 @SuppressWarnings("checkstyle:IllegalCatch")
74 protected AbstractDataStore(final ActorSystem actorSystem, final ClusterWrapper cluster,
75 final Configuration configuration, final DatastoreContextFactory datastoreContextFactory,
76 final DatastoreSnapshot restoreFromSnapshot) {
77 requireNonNull(actorSystem, "actorSystem should not be null");
78 requireNonNull(cluster, "cluster should not be null");
79 requireNonNull(configuration, "configuration should not be null");
80 requireNonNull(datastoreContextFactory, "datastoreContextFactory should not be null");
82 String shardManagerId = ShardManagerIdentifier.builder()
83 .type(datastoreContextFactory.getBaseDatastoreContext().getDataStoreName()).build().toString();
85 LOG.info("Creating ShardManager : {}", shardManagerId);
87 String shardDispatcher =
88 new Dispatchers(actorSystem.dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
90 PrimaryShardInfoFutureCache primaryShardInfoCache = new PrimaryShardInfoFutureCache();
92 ShardManagerCreator creator = new ShardManagerCreator().cluster(cluster).configuration(configuration)
93 .datastoreContextFactory(datastoreContextFactory)
94 .waitTillReadyCountDownLatch(waitTillReadyCountDownLatch)
95 .primaryShardInfoCache(primaryShardInfoCache)
96 .restoreFromSnapshot(restoreFromSnapshot)
97 .distributedDataStore(this);
99 actorUtils = new ActorUtils(actorSystem, createShardManager(actorSystem, creator, shardDispatcher,
100 shardManagerId), cluster, configuration, datastoreContextFactory.getBaseDatastoreContext(),
101 primaryShardInfoCache);
103 final Props clientProps = DistributedDataStoreClientActor.props(cluster.getCurrentMemberName(),
104 datastoreContextFactory.getBaseDatastoreContext().getDataStoreName(), actorUtils);
105 final ActorRef clientActor = actorSystem.actorOf(clientProps);
107 client = DistributedDataStoreClientActor.getDistributedDataStoreClient(clientActor, 30, TimeUnit.SECONDS);
108 } catch (Exception e) {
109 LOG.error("Failed to get actor for {}", clientProps, e);
110 clientActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
111 Throwables.throwIfUnchecked(e);
112 throw new RuntimeException(e);
115 identifier = client.getIdentifier();
116 LOG.debug("Distributed data store client {} started", identifier);
118 this.waitTillReadyTimeInMillis = actorUtils.getDatastoreContext().getShardLeaderElectionTimeout()
119 .duration().toMillis() * READY_WAIT_FACTOR;
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);
136 this.waitTillReadyTimeInMillis = actorUtils.getDatastoreContext().getShardLeaderElectionTimeout()
137 .duration().toMillis() * READY_WAIT_FACTOR;
141 protected AbstractDataStore(final ActorUtils actorUtils, final ClientIdentifier identifier,
142 final DataStoreClient clientActor) {
143 this.actorUtils = requireNonNull(actorUtils, "actorContext should not be null");
144 this.client = clientActor;
145 this.identifier = requireNonNull(identifier);
146 this.waitTillReadyTimeInMillis = actorUtils.getDatastoreContext().getShardLeaderElectionTimeout()
147 .duration().toMillis() * READY_WAIT_FACTOR;
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");
168 final String shardName = actorUtils.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
169 LOG.debug("Registering tree listener: {} for tree: {} shard: {}", listener, treeId, shardName);
171 final DataTreeChangeListenerProxy<L> listenerRegistrationProxy =
172 new DataTreeChangeListenerProxy<>(actorUtils, listener, treeId);
173 listenerRegistrationProxy.init(shardName);
175 return listenerRegistrationProxy;
180 public <C extends DOMDataTreeCommitCohort> DOMDataTreeCommitCohortRegistration<C> registerCommitCohort(
181 final DOMDataTreeIdentifier subtree, final C cohort) {
182 YangInstanceIdentifier treeId = requireNonNull(subtree, "subtree should not be null").getRootIdentifier();
183 requireNonNull(cohort, "listener should not be null");
186 final String shardName = actorUtils.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
187 LOG.debug("Registering cohort: {} for tree: {} shard: {}", cohort, treeId, shardName);
189 DataTreeCohortRegistrationProxy<C> cohortProxy =
190 new DataTreeCohortRegistrationProxy<>(actorUtils, subtree, cohort);
191 cohortProxy.init(shardName);
196 public void onGlobalContextUpdated(final SchemaContext schemaContext) {
197 actorUtils.setSchemaContext(schemaContext);
201 public void onDatastoreContextUpdated(final DatastoreContextFactory contextFactory) {
202 LOG.info("DatastoreContext updated for data store {}", actorUtils.getDataStoreName());
204 actorUtils.setDatastoreContext(contextFactory);
205 datastoreConfigMXBean.setContext(contextFactory.getBaseDatastoreContext());
209 @SuppressWarnings("checkstyle:IllegalCatch")
210 public void close() {
211 LOG.info("Closing data store {}", identifier);
213 if (datastoreConfigMXBean != null) {
214 datastoreConfigMXBean.unregisterMBean();
216 if (datastoreInfoMXBean != null) {
217 datastoreInfoMXBean.unregisterMBean();
220 if (closeable != null) {
223 } catch (Exception e) {
224 LOG.debug("Error closing instance", e);
228 actorUtils.shutdown();
230 if (client != null) {
236 public ActorUtils getActorUtils() {
240 public void waitTillReady() {
241 LOG.info("Beginning to wait for data store to become ready : {}", identifier);
244 if (waitTillReadyCountDownLatch.await(waitTillReadyTimeInMillis, TimeUnit.MILLISECONDS)) {
245 LOG.debug("Data store {} is now ready", identifier);
247 LOG.error("Shard leaders failed to settle in {} seconds, giving up",
248 TimeUnit.MILLISECONDS.toSeconds(waitTillReadyTimeInMillis));
250 } catch (InterruptedException e) {
251 LOG.error("Interrupted while waiting for shards to settle", e);
255 @SuppressWarnings("checkstyle:IllegalCatch")
256 private static ActorRef createShardManager(final ActorSystem actorSystem, final ShardManagerCreator creator,
257 final String shardDispatcher, final String shardManagerId) {
258 Exception lastException = null;
260 for (int i = 0; i < 100; i++) {
262 return actorSystem.actorOf(creator.props().withDispatcher(shardDispatcher), shardManagerId);
263 } catch (Exception e) {
265 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
266 LOG.debug("Could not create actor {} because of {} - waiting for sometime before retrying "
267 + "(retry count = {})", shardManagerId, e.getMessage(), i);
271 throw new IllegalStateException("Failed to create Shard Manager", lastException);
275 public CountDownLatch getWaitTillReadyCountDownLatch() {
276 return waitTillReadyCountDownLatch;
279 @SuppressWarnings("unchecked")
280 public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerProxyListener(
281 final YangInstanceIdentifier shardLookup,
282 final YangInstanceIdentifier insideShard,
283 final org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener delegate) {
285 requireNonNull(shardLookup, "shardLookup should not be null");
286 requireNonNull(insideShard, "insideShard should not be null");
287 requireNonNull(delegate, "delegate should not be null");
289 final String shardName = actorUtils.getShardStrategyFactory().getStrategy(shardLookup).findShard(shardLookup);
290 LOG.debug("Registering tree listener: {} for tree: {} shard: {}, path inside shard: {}",
291 delegate,shardLookup, shardName, insideShard);
293 final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> listenerRegistrationProxy =
294 new DataTreeChangeListenerProxy<>(actorUtils,
295 // wrap this in the ClusteredDOMDataTreeChangeLister interface
296 // since we always want clustered registration
297 (ClusteredDOMDataTreeChangeListener) delegate::onDataTreeChanged, insideShard);
298 listenerRegistrationProxy.init(shardName);
300 return (ListenerRegistration<L>) listenerRegistrationProxy;
303 @SuppressWarnings("unchecked")
304 public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerShardConfigListener(
305 final YangInstanceIdentifier internalPath,
306 final DOMDataTreeChangeListener delegate) {
307 requireNonNull(delegate, "delegate should not be null");
309 LOG.debug("Registering a listener for the configuration shard: {}", internalPath);
311 final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy =
312 new DataTreeChangeListenerProxy<>(actorUtils, delegate, internalPath);
313 proxy.init(ClusterUtils.PREFIX_CONFIG_SHARD_ID);
315 return (ListenerRegistration<L>) proxy;