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
9 package org.opendaylight.controller.cluster.datastore;
11 import akka.actor.ActorRef;
12 import akka.actor.ActorSystem;
13 import akka.actor.PoisonPill;
14 import akka.actor.Props;
15 import com.google.common.annotations.VisibleForTesting;
16 import com.google.common.base.Preconditions;
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.databroker.actors.dds.DistributedDataStoreClient;
23 import org.opendaylight.controller.cluster.databroker.actors.dds.DistributedDataStoreClientActor;
24 import org.opendaylight.controller.cluster.datastore.config.Configuration;
25 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
26 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.DatastoreConfigurationMXBeanImpl;
27 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.DatastoreInfoMXBeanImpl;
28 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot;
29 import org.opendaylight.controller.cluster.datastore.shardmanager.ShardManagerCreator;
30 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
31 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
32 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
33 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
34 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
35 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
36 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
37 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
38 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
39 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTreeChangePublisher;
40 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
41 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohort;
42 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistration;
43 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistry;
44 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
45 import org.opendaylight.yangtools.concepts.ListenerRegistration;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
48 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
49 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
54 * Implements a distributed DOMStore.
56 public class DistributedDataStore implements DistributedDataStoreInterface, SchemaContextListener,
57 DatastoreContextConfigAdminOverlay.Listener, DOMStoreTreeChangePublisher,
58 DOMDataTreeCommitCohortRegistry, AutoCloseable {
60 private static final Logger LOG = LoggerFactory.getLogger(DistributedDataStore.class);
62 private static final long READY_WAIT_FACTOR = 3;
64 private final ActorContext actorContext;
65 private final long waitTillReadyTimeInMillis;
67 private AutoCloseable closeable;
69 private DatastoreConfigurationMXBeanImpl datastoreConfigMXBean;
71 private DatastoreInfoMXBeanImpl datastoreInfoMXBean;
73 private final CountDownLatch waitTillReadyCountDownLatch = new CountDownLatch(1);
75 private final ClientIdentifier identifier;
76 private final DistributedDataStoreClient client;
78 private final TransactionContextFactory txContextFactory;
80 @SuppressWarnings("checkstyle:IllegalCatch")
81 public DistributedDataStore(final ActorSystem actorSystem, final ClusterWrapper cluster,
82 final Configuration configuration, final DatastoreContextFactory datastoreContextFactory,
83 final DatastoreSnapshot restoreFromSnapshot) {
84 Preconditions.checkNotNull(actorSystem, "actorSystem should not be null");
85 Preconditions.checkNotNull(cluster, "cluster should not be null");
86 Preconditions.checkNotNull(configuration, "configuration should not be null");
87 Preconditions.checkNotNull(datastoreContextFactory, "datastoreContextFactory should not be null");
89 String shardManagerId = ShardManagerIdentifier.builder()
90 .type(datastoreContextFactory.getBaseDatastoreContext().getDataStoreName()).build().toString();
92 LOG.info("Creating ShardManager : {}", shardManagerId);
94 String shardDispatcher =
95 new Dispatchers(actorSystem.dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
97 PrimaryShardInfoFutureCache primaryShardInfoCache = new PrimaryShardInfoFutureCache();
99 ShardManagerCreator creator = new ShardManagerCreator().cluster(cluster).configuration(configuration)
100 .datastoreContextFactory(datastoreContextFactory)
101 .waitTillReadyCountdownLatch(waitTillReadyCountDownLatch)
102 .primaryShardInfoCache(primaryShardInfoCache)
103 .restoreFromSnapshot(restoreFromSnapshot);
105 actorContext = new ActorContext(actorSystem, createShardManager(actorSystem, creator, shardDispatcher,
106 shardManagerId), cluster, configuration, datastoreContextFactory.getBaseDatastoreContext(),
107 primaryShardInfoCache);
109 final Props clientProps = DistributedDataStoreClientActor.props(cluster.getCurrentMemberName(),
110 datastoreContextFactory.getBaseDatastoreContext().getDataStoreName(), actorContext);
111 final ActorRef clientActor = actorSystem.actorOf(clientProps);
113 client = DistributedDataStoreClientActor.getDistributedDataStoreClient(clientActor, 30, TimeUnit.SECONDS);
114 } catch (Exception e) {
115 LOG.error("Failed to get actor for {}", clientProps, e);
116 clientActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
117 throw Throwables.propagate(e);
120 identifier = client.getIdentifier();
121 LOG.debug("Distributed data store client {} started", identifier);
123 this.waitTillReadyTimeInMillis = actorContext.getDatastoreContext().getShardLeaderElectionTimeout()
124 .duration().toMillis() * READY_WAIT_FACTOR;
126 this.txContextFactory = new TransactionContextFactory(actorContext, identifier);
128 datastoreConfigMXBean = new DatastoreConfigurationMXBeanImpl(
129 datastoreContextFactory.getBaseDatastoreContext().getDataStoreMXBeanType());
130 datastoreConfigMXBean.setContext(datastoreContextFactory.getBaseDatastoreContext());
131 datastoreConfigMXBean.registerMBean();
133 datastoreInfoMXBean = new DatastoreInfoMXBeanImpl(datastoreContextFactory.getBaseDatastoreContext()
134 .getDataStoreMXBeanType(), actorContext);
135 datastoreInfoMXBean.registerMBean();
139 DistributedDataStore(final ActorContext actorContext, final ClientIdentifier identifier) {
140 this.actorContext = Preconditions.checkNotNull(actorContext, "actorContext should not be null");
142 this.identifier = Preconditions.checkNotNull(identifier);
143 this.txContextFactory = new TransactionContextFactory(actorContext, identifier);
144 this.waitTillReadyTimeInMillis = actorContext.getDatastoreContext().getShardLeaderElectionTimeout()
145 .duration().toMillis() * READY_WAIT_FACTOR;
148 public void setCloseable(final AutoCloseable closeable) {
149 this.closeable = closeable;
152 @SuppressWarnings("unchecked")
154 public <L extends AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>
155 ListenerRegistration<L> registerChangeListener(
156 final YangInstanceIdentifier path, final L listener,
157 final AsyncDataBroker.DataChangeScope scope) {
159 Preconditions.checkNotNull(path, "path should not be null");
160 Preconditions.checkNotNull(listener, "listener should not be null");
162 LOG.debug("Registering listener: {} for path: {} scope: {}", listener, path, scope);
164 String shardName = actorContext.getShardStrategyFactory().getStrategy(path).findShard(path);
166 final DataChangeListenerRegistrationProxy listenerRegistrationProxy =
167 new DataChangeListenerRegistrationProxy(shardName, actorContext, listener);
168 listenerRegistrationProxy.init(path, scope);
170 return listenerRegistrationProxy;
174 public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerTreeChangeListener(
175 final YangInstanceIdentifier treeId, final L listener) {
176 Preconditions.checkNotNull(treeId, "treeId should not be null");
177 Preconditions.checkNotNull(listener, "listener should not be null");
179 final String shardName = actorContext.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
180 LOG.debug("Registering tree listener: {} for tree: {} shard: {}", listener, treeId, shardName);
182 final DataTreeChangeListenerProxy<L> listenerRegistrationProxy =
183 new DataTreeChangeListenerProxy<>(actorContext, listener);
184 listenerRegistrationProxy.init(shardName, treeId);
186 return listenerRegistrationProxy;
191 public <C extends DOMDataTreeCommitCohort> DOMDataTreeCommitCohortRegistration<C> registerCommitCohort(
192 final DOMDataTreeIdentifier subtree, final C cohort) {
193 YangInstanceIdentifier treeId =
194 Preconditions.checkNotNull(subtree, "subtree should not be null").getRootIdentifier();
195 Preconditions.checkNotNull(cohort, "listener should not be null");
198 final String shardName = actorContext.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
199 LOG.debug("Registering cohort: {} for tree: {} shard: {}", cohort, treeId, shardName);
201 DataTreeCohortRegistrationProxy<C> cohortProxy =
202 new DataTreeCohortRegistrationProxy<>(actorContext, subtree, cohort);
203 cohortProxy.init(shardName);
208 public DOMStoreTransactionChain createTransactionChain() {
209 return txContextFactory.createTransactionChain();
213 public DOMStoreReadTransaction newReadOnlyTransaction() {
214 return new TransactionProxy(txContextFactory, TransactionType.READ_ONLY);
218 public DOMStoreWriteTransaction newWriteOnlyTransaction() {
219 actorContext.acquireTxCreationPermit();
220 return new TransactionProxy(txContextFactory, TransactionType.WRITE_ONLY);
224 public DOMStoreReadWriteTransaction newReadWriteTransaction() {
225 actorContext.acquireTxCreationPermit();
226 return new TransactionProxy(txContextFactory, TransactionType.READ_WRITE);
230 public void onGlobalContextUpdated(final SchemaContext schemaContext) {
231 actorContext.setSchemaContext(schemaContext);
235 public void onDatastoreContextUpdated(final DatastoreContextFactory contextFactory) {
236 LOG.info("DatastoreContext updated for data store {}", actorContext.getDataStoreName());
238 actorContext.setDatastoreContext(contextFactory);
239 datastoreConfigMXBean.setContext(contextFactory.getBaseDatastoreContext());
243 @SuppressWarnings("checkstyle:IllegalCatch")
244 public void close() {
245 LOG.info("Closing data store {}", identifier);
247 if (datastoreConfigMXBean != null) {
248 datastoreConfigMXBean.unregisterMBean();
250 if (datastoreInfoMXBean != null) {
251 datastoreInfoMXBean.unregisterMBean();
254 if (closeable != null) {
257 } catch (Exception e) {
258 LOG.debug("Error closing instance", e);
262 txContextFactory.close();
263 actorContext.shutdown();
265 if (client != null) {
271 public ActorContext getActorContext() {
275 public void waitTillReady() {
276 LOG.info("Beginning to wait for data store to become ready : {}", identifier);
279 if (waitTillReadyCountDownLatch.await(waitTillReadyTimeInMillis, TimeUnit.MILLISECONDS)) {
280 LOG.debug("Data store {} is now ready", identifier);
282 LOG.error("Shard leaders failed to settle in {} seconds, giving up",
283 TimeUnit.MILLISECONDS.toSeconds(waitTillReadyTimeInMillis));
285 } catch (InterruptedException e) {
286 LOG.error("Interrupted while waiting for shards to settle", e);
290 @SuppressWarnings("checkstyle:IllegalCatch")
291 private static ActorRef createShardManager(final ActorSystem actorSystem, final ShardManagerCreator creator,
292 final String shardDispatcher, final String shardManagerId) {
293 Exception lastException = null;
295 for (int i = 0; i < 100; i++) {
297 return actorSystem.actorOf(creator.props().withDispatcher(shardDispatcher).withMailbox(
298 ActorContext.BOUNDED_MAILBOX), shardManagerId);
299 } catch (Exception e) {
301 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
302 LOG.debug("Could not create actor {} because of {} - waiting for sometime before retrying "
303 + "(retry count = {})", shardManagerId, e.getMessage(), i);
307 throw new IllegalStateException("Failed to create Shard Manager", lastException);
311 public CountDownLatch getWaitTillReadyCountDownLatch() {
312 return waitTillReadyCountDownLatch;