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.DataStoreClient;
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.persisted.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.ClusterUtils;
32 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
33 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
34 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
35 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
36 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
37 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTreeChangePublisher;
38 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohort;
39 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistration;
40 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistry;
41 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
42 import org.opendaylight.yangtools.concepts.ListenerRegistration;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
45 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
46 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
51 * Base implementation of a distributed DOMStore.
53 public abstract class AbstractDataStore implements DistributedDataStoreInterface, SchemaContextListener,
54 DatastoreContextConfigAdminOverlay.Listener, DOMStoreTreeChangePublisher,
55 DOMDataTreeCommitCohortRegistry, AutoCloseable {
57 private static final Logger LOG = LoggerFactory.getLogger(AbstractDataStore.class);
59 private static final long READY_WAIT_FACTOR = 3;
61 private final ActorContext actorContext;
62 private final long waitTillReadyTimeInMillis;
64 private AutoCloseable closeable;
66 private DatastoreConfigurationMXBeanImpl datastoreConfigMXBean;
68 private DatastoreInfoMXBeanImpl datastoreInfoMXBean;
70 private final CountDownLatch waitTillReadyCountDownLatch = new CountDownLatch(1);
72 private final ClientIdentifier identifier;
73 private final DataStoreClient client;
75 @SuppressWarnings("checkstyle:IllegalCatch")
76 protected AbstractDataStore(final ActorSystem actorSystem, final ClusterWrapper cluster,
77 final Configuration configuration, final DatastoreContextFactory datastoreContextFactory,
78 final DatastoreSnapshot restoreFromSnapshot) {
79 Preconditions.checkNotNull(actorSystem, "actorSystem should not be null");
80 Preconditions.checkNotNull(cluster, "cluster should not be null");
81 Preconditions.checkNotNull(configuration, "configuration should not be null");
82 Preconditions.checkNotNull(datastoreContextFactory, "datastoreContextFactory should not be null");
84 String shardManagerId = ShardManagerIdentifier.builder()
85 .type(datastoreContextFactory.getBaseDatastoreContext().getDataStoreName()).build().toString();
87 LOG.info("Creating ShardManager : {}", shardManagerId);
89 String shardDispatcher =
90 new Dispatchers(actorSystem.dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
92 PrimaryShardInfoFutureCache primaryShardInfoCache = new PrimaryShardInfoFutureCache();
94 ShardManagerCreator creator = new ShardManagerCreator().cluster(cluster).configuration(configuration)
95 .datastoreContextFactory(datastoreContextFactory)
96 .waitTillReadyCountDownLatch(waitTillReadyCountDownLatch)
97 .primaryShardInfoCache(primaryShardInfoCache)
98 .restoreFromSnapshot(restoreFromSnapshot)
99 .distributedDataStore(this);
101 actorContext = new ActorContext(actorSystem, createShardManager(actorSystem, creator, shardDispatcher,
102 shardManagerId), cluster, configuration, datastoreContextFactory.getBaseDatastoreContext(),
103 primaryShardInfoCache);
105 final Props clientProps = DistributedDataStoreClientActor.props(cluster.getCurrentMemberName(),
106 datastoreContextFactory.getBaseDatastoreContext().getDataStoreName(), actorContext);
107 final ActorRef clientActor = actorSystem.actorOf(clientProps);
109 client = DistributedDataStoreClientActor.getDistributedDataStoreClient(clientActor, 30, TimeUnit.SECONDS);
110 } catch (Exception e) {
111 LOG.error("Failed to get actor for {}", clientProps, e);
112 clientActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
113 throw Throwables.propagate(e);
116 identifier = client.getIdentifier();
117 LOG.debug("Distributed data store client {} started", identifier);
119 this.waitTillReadyTimeInMillis = actorContext.getDatastoreContext().getShardLeaderElectionTimeout()
120 .duration().toMillis() * READY_WAIT_FACTOR;
122 datastoreConfigMXBean = new DatastoreConfigurationMXBeanImpl(
123 datastoreContextFactory.getBaseDatastoreContext().getDataStoreMXBeanType());
124 datastoreConfigMXBean.setContext(datastoreContextFactory.getBaseDatastoreContext());
125 datastoreConfigMXBean.registerMBean();
127 datastoreInfoMXBean = new DatastoreInfoMXBeanImpl(datastoreContextFactory.getBaseDatastoreContext()
128 .getDataStoreMXBeanType(), actorContext);
129 datastoreInfoMXBean.registerMBean();
133 protected AbstractDataStore(final ActorContext actorContext, final ClientIdentifier identifier) {
134 this.actorContext = Preconditions.checkNotNull(actorContext, "actorContext should not be null");
136 this.identifier = Preconditions.checkNotNull(identifier);
137 this.waitTillReadyTimeInMillis = actorContext.getDatastoreContext().getShardLeaderElectionTimeout()
138 .duration().toMillis() * READY_WAIT_FACTOR;
142 protected AbstractDataStore(final ActorContext actorContext, final ClientIdentifier identifier,
143 final DataStoreClient clientActor) {
144 this.actorContext = Preconditions.checkNotNull(actorContext, "actorContext should not be null");
145 this.client = clientActor;
146 this.identifier = Preconditions.checkNotNull(identifier);
147 this.waitTillReadyTimeInMillis = actorContext.getDatastoreContext().getShardLeaderElectionTimeout()
148 .duration().toMillis() * READY_WAIT_FACTOR;
151 protected final DataStoreClient getClient() {
155 final ClientIdentifier getIdentifier() {
159 public void setCloseable(final AutoCloseable closeable) {
160 this.closeable = closeable;
163 @SuppressWarnings("unchecked")
165 public <L extends AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>
166 ListenerRegistration<L> registerChangeListener(
167 final YangInstanceIdentifier path, final L listener,
168 final AsyncDataBroker.DataChangeScope scope) {
170 Preconditions.checkNotNull(path, "path should not be null");
171 Preconditions.checkNotNull(listener, "listener should not be null");
173 LOG.debug("Registering listener: {} for path: {} scope: {}", listener, path, scope);
175 String shardName = actorContext.getShardStrategyFactory().getStrategy(path).findShard(path);
177 final DataChangeListenerRegistrationProxy listenerRegistrationProxy =
178 new DataChangeListenerRegistrationProxy(shardName, actorContext, listener);
179 listenerRegistrationProxy.init(path, scope);
181 return listenerRegistrationProxy;
185 public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerTreeChangeListener(
186 final YangInstanceIdentifier treeId, final L listener) {
187 Preconditions.checkNotNull(treeId, "treeId should not be null");
188 Preconditions.checkNotNull(listener, "listener should not be null");
190 final String shardName = actorContext.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
191 LOG.debug("Registering tree listener: {} for tree: {} shard: {}", listener, treeId, shardName);
193 final DataTreeChangeListenerProxy<L> listenerRegistrationProxy =
194 new DataTreeChangeListenerProxy<>(actorContext, listener, treeId);
195 listenerRegistrationProxy.init(shardName);
197 return listenerRegistrationProxy;
202 public <C extends DOMDataTreeCommitCohort> DOMDataTreeCommitCohortRegistration<C> registerCommitCohort(
203 final DOMDataTreeIdentifier subtree, final C cohort) {
204 YangInstanceIdentifier treeId =
205 Preconditions.checkNotNull(subtree, "subtree should not be null").getRootIdentifier();
206 Preconditions.checkNotNull(cohort, "listener should not be null");
209 final String shardName = actorContext.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
210 LOG.debug("Registering cohort: {} for tree: {} shard: {}", cohort, treeId, shardName);
212 DataTreeCohortRegistrationProxy<C> cohortProxy =
213 new DataTreeCohortRegistrationProxy<>(actorContext, subtree, cohort);
214 cohortProxy.init(shardName);
219 public void onGlobalContextUpdated(final SchemaContext schemaContext) {
220 actorContext.setSchemaContext(schemaContext);
224 public void onDatastoreContextUpdated(final DatastoreContextFactory contextFactory) {
225 LOG.info("DatastoreContext updated for data store {}", actorContext.getDataStoreName());
227 actorContext.setDatastoreContext(contextFactory);
228 datastoreConfigMXBean.setContext(contextFactory.getBaseDatastoreContext());
232 @SuppressWarnings("checkstyle:IllegalCatch")
233 public void close() {
234 LOG.info("Closing data store {}", identifier);
236 if (datastoreConfigMXBean != null) {
237 datastoreConfigMXBean.unregisterMBean();
239 if (datastoreInfoMXBean != null) {
240 datastoreInfoMXBean.unregisterMBean();
243 if (closeable != null) {
246 } catch (Exception e) {
247 LOG.debug("Error closing instance", e);
251 actorContext.shutdown();
253 if (client != null) {
259 public ActorContext getActorContext() {
263 public void waitTillReady() {
264 LOG.info("Beginning to wait for data store to become ready : {}", identifier);
267 if (waitTillReadyCountDownLatch.await(waitTillReadyTimeInMillis, TimeUnit.MILLISECONDS)) {
268 LOG.debug("Data store {} is now ready", identifier);
270 LOG.error("Shard leaders failed to settle in {} seconds, giving up",
271 TimeUnit.MILLISECONDS.toSeconds(waitTillReadyTimeInMillis));
273 } catch (InterruptedException e) {
274 LOG.error("Interrupted while waiting for shards to settle", e);
278 @SuppressWarnings("checkstyle:IllegalCatch")
279 private static ActorRef createShardManager(final ActorSystem actorSystem, final ShardManagerCreator creator,
280 final String shardDispatcher, final String shardManagerId) {
281 Exception lastException = null;
283 for (int i = 0; i < 100; i++) {
285 return actorSystem.actorOf(creator.props().withDispatcher(shardDispatcher).withMailbox(
286 ActorContext.BOUNDED_MAILBOX), shardManagerId);
287 } catch (Exception e) {
289 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
290 LOG.debug("Could not create actor {} because of {} - waiting for sometime before retrying "
291 + "(retry count = {})", shardManagerId, e.getMessage(), i);
295 throw new IllegalStateException("Failed to create Shard Manager", lastException);
299 public CountDownLatch getWaitTillReadyCountDownLatch() {
300 return waitTillReadyCountDownLatch;
303 @SuppressWarnings("unchecked")
304 public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerProxyListener(
305 final YangInstanceIdentifier shardLookup,
306 final YangInstanceIdentifier insideShard,
307 final org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener delegate) {
309 Preconditions.checkNotNull(shardLookup, "shardLookup should not be null");
310 Preconditions.checkNotNull(insideShard, "insideShard should not be null");
311 Preconditions.checkNotNull(delegate, "delegate should not be null");
313 final String shardName = actorContext.getShardStrategyFactory().getStrategy(shardLookup).findShard(shardLookup);
314 LOG.debug("Registering tree listener: {} for tree: {} shard: {}, path inside shard: {}",
315 delegate,shardLookup, shardName, insideShard);
317 final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> listenerRegistrationProxy =
318 new DataTreeChangeListenerProxy<>(actorContext, delegate::onDataTreeChanged, insideShard);
319 listenerRegistrationProxy.init(shardName);
321 return (ListenerRegistration<L>) listenerRegistrationProxy;
324 @SuppressWarnings("unchecked")
325 public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerShardConfigListener(
326 final YangInstanceIdentifier internalPath,
327 final DOMDataTreeChangeListener delegate) {
328 Preconditions.checkNotNull(delegate, "delegate should not be null");
330 LOG.debug("Registering a listener for the configuration shard: {}", internalPath);
332 final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy =
333 new DataTreeChangeListenerProxy<>(actorContext, delegate, internalPath);
334 proxy.init(ClusterUtils.PREFIX_CONFIG_SHARD_ID);
336 return (ListenerRegistration<L>) proxy;