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.AbstractShardManagerCreator;
31 import org.opendaylight.controller.cluster.datastore.shardmanager.ShardManagerCreator;
32 import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
33 import org.opendaylight.controller.cluster.datastore.utils.ClusterUtils;
34 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
35 import org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener;
36 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
37 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohort;
38 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistration;
39 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistry;
40 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
41 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTreeChangePublisher;
42 import org.opendaylight.yangtools.concepts.ListenerRegistration;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
45 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
50 * Base implementation of a distributed DOMStore.
52 public abstract class AbstractDataStore implements DistributedDataStoreInterface, SchemaContextListener,
53 DatastoreContextPropertiesUpdater.Listener, DOMStoreTreeChangePublisher,
54 DOMDataTreeCommitCohortRegistry, AutoCloseable {
56 private static final Logger LOG = LoggerFactory.getLogger(AbstractDataStore.class);
58 private static final long READY_WAIT_FACTOR = 3;
60 private final ActorUtils actorUtils;
61 private final long waitTillReadyTimeInMillis;
63 private AutoCloseable closeable;
65 private DatastoreConfigurationMXBeanImpl datastoreConfigMXBean;
67 private DatastoreInfoMXBeanImpl datastoreInfoMXBean;
69 private final CountDownLatch waitTillReadyCountDownLatch = new CountDownLatch(1);
71 private final ClientIdentifier identifier;
72 private final DataStoreClient client;
74 @SuppressWarnings("checkstyle:IllegalCatch")
75 protected AbstractDataStore(final ActorSystem actorSystem, final ClusterWrapper cluster,
76 final Configuration configuration, final DatastoreContextFactory datastoreContextFactory,
77 final DatastoreSnapshot restoreFromSnapshot) {
78 requireNonNull(actorSystem, "actorSystem should not be null");
79 requireNonNull(cluster, "cluster should not be null");
80 requireNonNull(configuration, "configuration should not be null");
81 requireNonNull(datastoreContextFactory, "datastoreContextFactory should not be null");
83 String shardManagerId = ShardManagerIdentifier.builder()
84 .type(datastoreContextFactory.getBaseDatastoreContext().getDataStoreName()).build().toString();
86 LOG.info("Creating ShardManager : {}", shardManagerId);
88 String shardDispatcher =
89 new Dispatchers(actorSystem.dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
91 PrimaryShardInfoFutureCache primaryShardInfoCache = new PrimaryShardInfoFutureCache();
93 AbstractShardManagerCreator<?> creator = getShardManagerCreator().cluster(cluster).configuration(configuration)
94 .datastoreContextFactory(datastoreContextFactory)
95 .waitTillReadyCountDownLatch(waitTillReadyCountDownLatch)
96 .primaryShardInfoCache(primaryShardInfoCache)
97 .restoreFromSnapshot(restoreFromSnapshot)
98 .distributedDataStore(this);
100 actorUtils = new ActorUtils(actorSystem, createShardManager(actorSystem, creator, shardDispatcher,
101 shardManagerId), cluster, configuration, datastoreContextFactory.getBaseDatastoreContext(),
102 primaryShardInfoCache);
104 final Props clientProps = DistributedDataStoreClientActor.props(cluster.getCurrentMemberName(),
105 datastoreContextFactory.getBaseDatastoreContext().getDataStoreName(), actorUtils);
106 final ActorRef clientActor = actorSystem.actorOf(clientProps);
108 client = DistributedDataStoreClientActor.getDistributedDataStoreClient(clientActor, 30, TimeUnit.SECONDS);
109 } catch (Exception e) {
110 LOG.error("Failed to get actor for {}", clientProps, e);
111 clientActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
112 Throwables.throwIfUnchecked(e);
113 throw new RuntimeException(e);
116 identifier = client.getIdentifier();
117 LOG.debug("Distributed data store client {} started", identifier);
119 this.waitTillReadyTimeInMillis = actorUtils.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(), actorUtils);
129 datastoreInfoMXBean.registerMBean();
133 protected AbstractDataStore(final ActorUtils actorUtils, final ClientIdentifier identifier) {
134 this.actorUtils = requireNonNull(actorUtils, "actorContext should not be null");
136 this.identifier = requireNonNull(identifier);
137 this.waitTillReadyTimeInMillis = actorUtils.getDatastoreContext().getShardLeaderElectionTimeout()
138 .duration().toMillis() * READY_WAIT_FACTOR;
142 protected AbstractDataStore(final ActorUtils actorUtils, final ClientIdentifier identifier,
143 final DataStoreClient clientActor) {
144 this.actorUtils = requireNonNull(actorUtils, "actorContext should not be null");
145 this.client = clientActor;
146 this.identifier = requireNonNull(identifier);
147 this.waitTillReadyTimeInMillis = actorUtils.getDatastoreContext().getShardLeaderElectionTimeout()
148 .duration().toMillis() * READY_WAIT_FACTOR;
151 protected AbstractShardManagerCreator<?> getShardManagerCreator() {
152 return new ShardManagerCreator();
155 protected final DataStoreClient getClient() {
159 final ClientIdentifier getIdentifier() {
163 public void setCloseable(final AutoCloseable closeable) {
164 this.closeable = closeable;
168 public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerTreeChangeListener(
169 final YangInstanceIdentifier treeId, final L listener) {
170 requireNonNull(treeId, "treeId should not be null");
171 requireNonNull(listener, "listener should not be null");
173 final String shardName = actorUtils.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
174 LOG.debug("Registering tree listener: {} for tree: {} shard: {}", listener, treeId, shardName);
176 final DataTreeChangeListenerProxy<L> listenerRegistrationProxy =
177 new DataTreeChangeListenerProxy<>(actorUtils, listener, treeId);
178 listenerRegistrationProxy.init(shardName);
180 return listenerRegistrationProxy;
185 public <C extends DOMDataTreeCommitCohort> DOMDataTreeCommitCohortRegistration<C> registerCommitCohort(
186 final DOMDataTreeIdentifier subtree, final C cohort) {
187 YangInstanceIdentifier treeId = requireNonNull(subtree, "subtree should not be null").getRootIdentifier();
188 requireNonNull(cohort, "listener should not be null");
191 final String shardName = actorUtils.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
192 LOG.debug("Registering cohort: {} for tree: {} shard: {}", cohort, treeId, shardName);
194 DataTreeCohortRegistrationProxy<C> cohortProxy =
195 new DataTreeCohortRegistrationProxy<>(actorUtils, subtree, cohort);
196 cohortProxy.init(shardName);
201 public void onGlobalContextUpdated(final SchemaContext schemaContext) {
202 actorUtils.setSchemaContext(schemaContext);
206 public void onDatastoreContextUpdated(final DatastoreContextFactory contextFactory) {
207 LOG.info("DatastoreContext updated for data store {}", actorUtils.getDataStoreName());
209 actorUtils.setDatastoreContext(contextFactory);
210 datastoreConfigMXBean.setContext(contextFactory.getBaseDatastoreContext());
214 @SuppressWarnings("checkstyle:IllegalCatch")
215 public void close() {
216 LOG.info("Closing data store {}", identifier);
218 if (datastoreConfigMXBean != null) {
219 datastoreConfigMXBean.unregisterMBean();
221 if (datastoreInfoMXBean != null) {
222 datastoreInfoMXBean.unregisterMBean();
225 if (closeable != null) {
228 } catch (Exception e) {
229 LOG.debug("Error closing instance", e);
233 actorUtils.shutdown();
235 if (client != null) {
241 public ActorUtils getActorUtils() {
245 public void waitTillReady() {
246 LOG.info("Beginning to wait for data store to become ready : {}", identifier);
249 if (waitTillReadyCountDownLatch.await(waitTillReadyTimeInMillis, TimeUnit.MILLISECONDS)) {
250 LOG.debug("Data store {} is now ready", identifier);
252 LOG.error("Shard leaders failed to settle in {} seconds, giving up",
253 TimeUnit.MILLISECONDS.toSeconds(waitTillReadyTimeInMillis));
255 } catch (InterruptedException e) {
256 LOG.error("Interrupted while waiting for shards to settle", e);
260 @SuppressWarnings("checkstyle:IllegalCatch")
261 private static ActorRef createShardManager(final ActorSystem actorSystem,
262 final AbstractShardManagerCreator<?> creator, final String shardDispatcher,
263 final String shardManagerId) {
264 Exception lastException = null;
266 for (int i = 0; i < 100; i++) {
268 return actorSystem.actorOf(creator.props().withDispatcher(shardDispatcher), shardManagerId);
269 } catch (Exception e) {
271 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
272 LOG.debug("Could not create actor {} because of {} - waiting for sometime before retrying "
273 + "(retry count = {})", shardManagerId, e.getMessage(), i);
277 throw new IllegalStateException("Failed to create Shard Manager", lastException);
281 public CountDownLatch getWaitTillReadyCountDownLatch() {
282 return waitTillReadyCountDownLatch;
285 @SuppressWarnings("unchecked")
286 public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerProxyListener(
287 final YangInstanceIdentifier shardLookup,
288 final YangInstanceIdentifier insideShard,
289 final org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener delegate) {
291 requireNonNull(shardLookup, "shardLookup should not be null");
292 requireNonNull(insideShard, "insideShard should not be null");
293 requireNonNull(delegate, "delegate should not be null");
295 final String shardName = actorUtils.getShardStrategyFactory().getStrategy(shardLookup).findShard(shardLookup);
296 LOG.debug("Registering tree listener: {} for tree: {} shard: {}, path inside shard: {}",
297 delegate,shardLookup, shardName, insideShard);
299 final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> listenerRegistrationProxy =
300 new DataTreeChangeListenerProxy<>(actorUtils,
301 // wrap this in the ClusteredDOMDataTreeChangeLister interface
302 // since we always want clustered registration
303 (ClusteredDOMDataTreeChangeListener) delegate::onDataTreeChanged, insideShard);
304 listenerRegistrationProxy.init(shardName);
306 return (ListenerRegistration<L>) listenerRegistrationProxy;
309 @SuppressWarnings("unchecked")
310 public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerShardConfigListener(
311 final YangInstanceIdentifier internalPath,
312 final DOMDataTreeChangeListener delegate) {
313 requireNonNull(delegate, "delegate should not be null");
315 LOG.debug("Registering a listener for the configuration shard: {}", internalPath);
317 final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy =
318 new DataTreeChangeListenerProxy<>(actorUtils, delegate, internalPath);
319 proxy.init(ClusterUtils.PREFIX_CONFIG_SHARD_ID);
321 return (ListenerRegistration<L>) proxy;