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.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.ActorContext;
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 ActorContext actorContext;
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 Preconditions.checkNotNull(actorSystem, "actorSystem should not be null");
78 Preconditions.checkNotNull(cluster, "cluster should not be null");
79 Preconditions.checkNotNull(configuration, "configuration should not be null");
80 Preconditions.checkNotNull(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 actorContext = new ActorContext(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(), actorContext);
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 = actorContext.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(), actorContext);
128 datastoreInfoMXBean.registerMBean();
132 protected AbstractDataStore(final ActorContext actorContext, final ClientIdentifier identifier) {
133 this.actorContext = Preconditions.checkNotNull(actorContext, "actorContext should not be null");
135 this.identifier = Preconditions.checkNotNull(identifier);
136 this.waitTillReadyTimeInMillis = actorContext.getDatastoreContext().getShardLeaderElectionTimeout()
137 .duration().toMillis() * READY_WAIT_FACTOR;
141 protected AbstractDataStore(final ActorContext actorContext, final ClientIdentifier identifier,
142 final DataStoreClient clientActor) {
143 this.actorContext = Preconditions.checkNotNull(actorContext, "actorContext should not be null");
144 this.client = clientActor;
145 this.identifier = Preconditions.checkNotNull(identifier);
146 this.waitTillReadyTimeInMillis = actorContext.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 Preconditions.checkNotNull(treeId, "treeId should not be null");
166 Preconditions.checkNotNull(listener, "listener should not be null");
168 final String shardName = actorContext.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<>(actorContext, 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 =
183 Preconditions.checkNotNull(subtree, "subtree should not be null").getRootIdentifier();
184 Preconditions.checkNotNull(cohort, "listener should not be null");
187 final String shardName = actorContext.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
188 LOG.debug("Registering cohort: {} for tree: {} shard: {}", cohort, treeId, shardName);
190 DataTreeCohortRegistrationProxy<C> cohortProxy =
191 new DataTreeCohortRegistrationProxy<>(actorContext, subtree, cohort);
192 cohortProxy.init(shardName);
197 public void onGlobalContextUpdated(final SchemaContext schemaContext) {
198 actorContext.setSchemaContext(schemaContext);
202 public void onDatastoreContextUpdated(final DatastoreContextFactory contextFactory) {
203 LOG.info("DatastoreContext updated for data store {}", actorContext.getDataStoreName());
205 actorContext.setDatastoreContext(contextFactory);
206 datastoreConfigMXBean.setContext(contextFactory.getBaseDatastoreContext());
210 @SuppressWarnings("checkstyle:IllegalCatch")
211 public void close() {
212 LOG.info("Closing data store {}", identifier);
214 if (datastoreConfigMXBean != null) {
215 datastoreConfigMXBean.unregisterMBean();
217 if (datastoreInfoMXBean != null) {
218 datastoreInfoMXBean.unregisterMBean();
221 if (closeable != null) {
224 } catch (Exception e) {
225 LOG.debug("Error closing instance", e);
229 actorContext.shutdown();
231 if (client != null) {
237 public ActorContext getActorContext() {
241 public void waitTillReady() {
242 LOG.info("Beginning to wait for data store to become ready : {}", identifier);
245 if (waitTillReadyCountDownLatch.await(waitTillReadyTimeInMillis, TimeUnit.MILLISECONDS)) {
246 LOG.debug("Data store {} is now ready", identifier);
248 LOG.error("Shard leaders failed to settle in {} seconds, giving up",
249 TimeUnit.MILLISECONDS.toSeconds(waitTillReadyTimeInMillis));
251 } catch (InterruptedException e) {
252 LOG.error("Interrupted while waiting for shards to settle", e);
256 @SuppressWarnings("checkstyle:IllegalCatch")
257 private static ActorRef createShardManager(final ActorSystem actorSystem, final ShardManagerCreator creator,
258 final String shardDispatcher, final String shardManagerId) {
259 Exception lastException = null;
261 for (int i = 0; i < 100; i++) {
263 return actorSystem.actorOf(creator.props().withDispatcher(shardDispatcher), shardManagerId);
264 } catch (Exception e) {
266 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
267 LOG.debug("Could not create actor {} because of {} - waiting for sometime before retrying "
268 + "(retry count = {})", shardManagerId, e.getMessage(), i);
272 throw new IllegalStateException("Failed to create Shard Manager", lastException);
276 public CountDownLatch getWaitTillReadyCountDownLatch() {
277 return waitTillReadyCountDownLatch;
280 @SuppressWarnings("unchecked")
281 public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerProxyListener(
282 final YangInstanceIdentifier shardLookup,
283 final YangInstanceIdentifier insideShard,
284 final org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener delegate) {
286 Preconditions.checkNotNull(shardLookup, "shardLookup should not be null");
287 Preconditions.checkNotNull(insideShard, "insideShard should not be null");
288 Preconditions.checkNotNull(delegate, "delegate should not be null");
290 final String shardName = actorContext.getShardStrategyFactory().getStrategy(shardLookup).findShard(shardLookup);
291 LOG.debug("Registering tree listener: {} for tree: {} shard: {}, path inside shard: {}",
292 delegate,shardLookup, shardName, insideShard);
294 final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> listenerRegistrationProxy =
295 new DataTreeChangeListenerProxy<>(actorContext,
296 // wrap this in the ClusteredDOMDataTreeChangeLister interface
297 // since we always want clustered registration
298 (ClusteredDOMDataTreeChangeListener) delegate::onDataTreeChanged, insideShard);
299 listenerRegistrationProxy.init(shardName);
301 return (ListenerRegistration<L>) listenerRegistrationProxy;
304 @SuppressWarnings("unchecked")
305 public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerShardConfigListener(
306 final YangInstanceIdentifier internalPath,
307 final DOMDataTreeChangeListener delegate) {
308 Preconditions.checkNotNull(delegate, "delegate should not be null");
310 LOG.debug("Registering a listener for the configuration shard: {}", internalPath);
312 final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy =
313 new DataTreeChangeListenerProxy<>(actorContext, delegate, internalPath);
314 proxy.init(ClusterUtils.PREFIX_CONFIG_SHARD_ID);
316 return (ListenerRegistration<L>) proxy;