Convert sal-distributed-datastore to OSGi DS
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / AbstractDataStore.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.cluster.datastore;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
13 import akka.actor.ActorRef;
14 import akka.actor.ActorSystem;
15 import akka.actor.PoisonPill;
16 import akka.actor.Props;
17 import com.google.common.annotations.Beta;
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.common.base.Throwables;
20 import com.google.common.util.concurrent.Uninterruptibles;
21 import java.util.Set;
22 import java.util.concurrent.CountDownLatch;
23 import java.util.concurrent.TimeUnit;
24 import java.util.concurrent.TimeoutException;
25 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
26 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
27 import org.opendaylight.controller.cluster.databroker.actors.dds.DataStoreClient;
28 import org.opendaylight.controller.cluster.databroker.actors.dds.DistributedDataStoreClientActor;
29 import org.opendaylight.controller.cluster.datastore.config.Configuration;
30 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
31 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.DatastoreConfigurationMXBeanImpl;
32 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.DatastoreInfoMXBeanImpl;
33 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
34 import org.opendaylight.controller.cluster.datastore.shardmanager.AbstractShardManagerCreator;
35 import org.opendaylight.controller.cluster.datastore.shardmanager.ShardManagerCreator;
36 import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
37 import org.opendaylight.controller.cluster.datastore.utils.ClusterUtils;
38 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
39 import org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener;
40 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
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.mdsal.dom.spi.store.DOMStoreTreeChangePublisher;
46 import org.opendaylight.yangtools.concepts.ListenerRegistration;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
48 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
49 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextListener;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import scala.concurrent.duration.Duration;
53
54 /**
55  * Base implementation of a distributed DOMStore.
56  */
57 public abstract class AbstractDataStore implements DistributedDataStoreInterface, EffectiveModelContextListener,
58         DatastoreContextPropertiesUpdater.Listener, DOMStoreTreeChangePublisher,
59         DOMDataTreeCommitCohortRegistry, AutoCloseable {
60
61     private static final Logger LOG = LoggerFactory.getLogger(AbstractDataStore.class);
62
63     private final CountDownLatch waitTillReadyCountDownLatch = new CountDownLatch(1);
64     private final ClientIdentifier identifier;
65     private final DataStoreClient client;
66     private final ActorUtils actorUtils;
67
68     private AutoCloseable closeable;
69     private DatastoreConfigurationMXBeanImpl datastoreConfigMXBean;
70     private DatastoreInfoMXBeanImpl datastoreInfoMXBean;
71
72     @SuppressWarnings("checkstyle:IllegalCatch")
73     protected AbstractDataStore(final ActorSystem actorSystem, final ClusterWrapper cluster,
74             final Configuration configuration, final DatastoreContextFactory datastoreContextFactory,
75             final DatastoreSnapshot restoreFromSnapshot) {
76         requireNonNull(actorSystem, "actorSystem should not be null");
77         requireNonNull(cluster, "cluster should not be null");
78         requireNonNull(configuration, "configuration should not be null");
79         requireNonNull(datastoreContextFactory, "datastoreContextFactory should not be null");
80
81         String shardManagerId = ShardManagerIdentifier.builder()
82                 .type(datastoreContextFactory.getBaseDatastoreContext().getDataStoreName()).build().toString();
83
84         LOG.info("Creating ShardManager : {}", shardManagerId);
85
86         String shardDispatcher =
87                 new Dispatchers(actorSystem.dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
88
89         PrimaryShardInfoFutureCache primaryShardInfoCache = new PrimaryShardInfoFutureCache();
90
91         AbstractShardManagerCreator<?> creator = getShardManagerCreator().cluster(cluster).configuration(configuration)
92                 .datastoreContextFactory(datastoreContextFactory)
93                 .waitTillReadyCountDownLatch(waitTillReadyCountDownLatch)
94                 .primaryShardInfoCache(primaryShardInfoCache)
95                 .restoreFromSnapshot(restoreFromSnapshot)
96                 .distributedDataStore(this);
97
98         actorUtils = new ActorUtils(actorSystem, createShardManager(actorSystem, creator, shardDispatcher,
99                 shardManagerId), cluster, configuration, datastoreContextFactory.getBaseDatastoreContext(),
100                 primaryShardInfoCache);
101
102         final Props clientProps = DistributedDataStoreClientActor.props(cluster.getCurrentMemberName(),
103             datastoreContextFactory.getBaseDatastoreContext().getDataStoreName(), actorUtils);
104         final ActorRef clientActor = actorSystem.actorOf(clientProps);
105         try {
106             client = DistributedDataStoreClientActor.getDistributedDataStoreClient(clientActor, 30, TimeUnit.SECONDS);
107         } catch (Exception e) {
108             LOG.error("Failed to get actor for {}", clientProps, e);
109             clientActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
110             Throwables.throwIfUnchecked(e);
111             throw new RuntimeException(e);
112         }
113
114         identifier = client.getIdentifier();
115         LOG.debug("Distributed data store client {} started", identifier);
116
117         datastoreConfigMXBean = new DatastoreConfigurationMXBeanImpl(
118                 datastoreContextFactory.getBaseDatastoreContext().getDataStoreMXBeanType());
119         datastoreConfigMXBean.setContext(datastoreContextFactory.getBaseDatastoreContext());
120         datastoreConfigMXBean.registerMBean();
121
122         datastoreInfoMXBean = new DatastoreInfoMXBeanImpl(datastoreContextFactory.getBaseDatastoreContext()
123                 .getDataStoreMXBeanType(), actorUtils);
124         datastoreInfoMXBean.registerMBean();
125     }
126
127     @VisibleForTesting
128     protected AbstractDataStore(final ActorUtils actorUtils, final ClientIdentifier identifier) {
129         this.actorUtils = requireNonNull(actorUtils, "actorContext should not be null");
130         this.client = null;
131         this.identifier = requireNonNull(identifier);
132     }
133
134     @VisibleForTesting
135     protected AbstractDataStore(final ActorUtils actorUtils, final ClientIdentifier identifier,
136                                 final DataStoreClient clientActor) {
137         this.actorUtils = requireNonNull(actorUtils, "actorContext should not be null");
138         this.client = clientActor;
139         this.identifier = requireNonNull(identifier);
140     }
141
142     protected AbstractShardManagerCreator<?> getShardManagerCreator() {
143         return new ShardManagerCreator();
144     }
145
146     protected final DataStoreClient getClient() {
147         return client;
148     }
149
150     final ClientIdentifier getIdentifier() {
151         return identifier;
152     }
153
154     public void setCloseable(final AutoCloseable closeable) {
155         this.closeable = closeable;
156     }
157
158     @Override
159     public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerTreeChangeListener(
160             final YangInstanceIdentifier treeId, final L listener) {
161         requireNonNull(treeId, "treeId should not be null");
162         requireNonNull(listener, "listener should not be null");
163
164         /*
165          * We need to potentially deal with multi-shard composition for registration targeting the root of the data
166          * store. If that is the case, we delegate to a more complicated setup invol
167          */
168         if (treeId.isEmpty()) {
169             // User is targeting root of the datastore. If there is more than one shard, we have to register with them
170             // all and perform data composition.
171             final Set<String> shardNames = actorUtils.getConfiguration().getAllShardNames();
172             if (shardNames.size() > 1) {
173                 checkArgument(listener instanceof ClusteredDOMDataTreeChangeListener,
174                     "Cannot listen on root without non-clustered listener %s", listener);
175                 return new RootDataTreeChangeListenerProxy<>(actorUtils, listener, shardNames);
176             }
177         }
178
179         final String shardName = actorUtils.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
180         LOG.debug("Registering tree listener: {} for tree: {} shard: {}", listener, treeId, shardName);
181
182         final DataTreeChangeListenerProxy<L> listenerRegistrationProxy =
183                 new DataTreeChangeListenerProxy<>(actorUtils, listener, treeId);
184         listenerRegistrationProxy.init(shardName);
185
186         return listenerRegistrationProxy;
187     }
188
189     @Override
190     public <C extends DOMDataTreeCommitCohort> DOMDataTreeCommitCohortRegistration<C> registerCommitCohort(
191             final DOMDataTreeIdentifier subtree, final C cohort) {
192         YangInstanceIdentifier treeId = requireNonNull(subtree, "subtree should not be null").getRootIdentifier();
193         requireNonNull(cohort, "listener should not be null");
194
195
196         final String shardName = actorUtils.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
197         LOG.debug("Registering cohort: {} for tree: {} shard: {}", cohort, treeId, shardName);
198
199         DataTreeCohortRegistrationProxy<C> cohortProxy =
200                 new DataTreeCohortRegistrationProxy<>(actorUtils, subtree, cohort);
201         cohortProxy.init(shardName);
202         return cohortProxy;
203     }
204
205     @Override
206     public void onModelContextUpdated(final EffectiveModelContext newModelContext) {
207         actorUtils.setSchemaContext(newModelContext);
208     }
209
210     @Override
211     public void onDatastoreContextUpdated(final DatastoreContextFactory contextFactory) {
212         LOG.info("DatastoreContext updated for data store {}", actorUtils.getDataStoreName());
213
214         actorUtils.setDatastoreContext(contextFactory);
215         datastoreConfigMXBean.setContext(contextFactory.getBaseDatastoreContext());
216     }
217
218     @Override
219     @SuppressWarnings("checkstyle:IllegalCatch")
220     public void close() {
221         LOG.info("Closing data store {}", identifier);
222
223         if (datastoreConfigMXBean != null) {
224             datastoreConfigMXBean.unregisterMBean();
225         }
226         if (datastoreInfoMXBean != null) {
227             datastoreInfoMXBean.unregisterMBean();
228         }
229
230         if (closeable != null) {
231             try {
232                 closeable.close();
233             } catch (Exception e) {
234                 LOG.debug("Error closing instance", e);
235             }
236         }
237
238         actorUtils.shutdown();
239
240         if (client != null) {
241             client.close();
242         }
243     }
244
245     @Override
246     public ActorUtils getActorUtils() {
247         return actorUtils;
248     }
249
250     // TODO: consider removing this in favor of awaitReadiness()
251     public void waitTillReady() {
252         LOG.info("Beginning to wait for data store to become ready : {}", identifier);
253
254         final Duration toWait = initialSettleTime();
255         try {
256             if (!awaitReadiness(toWait)) {
257                 LOG.error("Shard leaders failed to settle in {}, giving up", toWait);
258                 return;
259             }
260         } catch (InterruptedException e) {
261             LOG.error("Interrupted while waiting for shards to settle", e);
262             return;
263         }
264
265         LOG.debug("Data store {} is now ready", identifier);
266     }
267
268     @Beta
269     public boolean awaitReadiness() throws InterruptedException {
270         return awaitReadiness(initialSettleTime());
271     }
272
273     @Beta
274     public boolean awaitReadiness(final Duration toWait) throws InterruptedException {
275         if (toWait.isFinite()) {
276             return waitTillReadyCountDownLatch.await(toWait.toNanos(), TimeUnit.NANOSECONDS);
277         }
278
279         waitTillReadyCountDownLatch.await();
280         return true;
281     }
282
283     @Beta
284     public void awaitReadiness(final long timeout, final TimeUnit unit) throws InterruptedException, TimeoutException {
285         if (!waitTillReadyCountDownLatch.await(timeout, unit)) {
286             throw new TimeoutException("Shard leaders failed to settle");
287         }
288     }
289
290     @SuppressWarnings("checkstyle:IllegalCatch")
291     private static ActorRef createShardManager(final ActorSystem actorSystem,
292             final AbstractShardManagerCreator<?> creator, final String shardDispatcher,
293             final String shardManagerId) {
294         Exception lastException = null;
295
296         for (int i = 0; i < 100; i++) {
297             try {
298                 return actorSystem.actorOf(creator.props().withDispatcher(shardDispatcher), shardManagerId);
299             } catch (Exception e) {
300                 lastException = 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);
304             }
305         }
306
307         throw new IllegalStateException("Failed to create Shard Manager", lastException);
308     }
309
310     @VisibleForTesting
311     public CountDownLatch getWaitTillReadyCountDownLatch() {
312         return waitTillReadyCountDownLatch;
313     }
314
315     @Override
316     @SuppressWarnings("unchecked")
317     public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerProxyListener(
318             final YangInstanceIdentifier shardLookup, final YangInstanceIdentifier insideShard,
319             final DOMDataTreeChangeListener delegate) {
320
321         requireNonNull(shardLookup, "shardLookup should not be null");
322         requireNonNull(insideShard, "insideShard should not be null");
323         requireNonNull(delegate, "delegate should not be null");
324
325         final String shardName = actorUtils.getShardStrategyFactory().getStrategy(shardLookup).findShard(shardLookup);
326         LOG.debug("Registering tree listener: {} for tree: {} shard: {}, path inside shard: {}",
327                 delegate,shardLookup, shardName, insideShard);
328
329         final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> listenerRegistrationProxy =
330                 new DataTreeChangeListenerProxy<>(actorUtils,
331                         // wrap this in the ClusteredDOMDataTreeChangeLister interface
332                         // since we always want clustered registration
333                         (ClusteredDOMDataTreeChangeListener) delegate::onDataTreeChanged, insideShard);
334         listenerRegistrationProxy.init(shardName);
335
336         return (ListenerRegistration<L>) listenerRegistrationProxy;
337     }
338
339     @Override
340     @SuppressWarnings("unchecked")
341     public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerShardConfigListener(
342             final YangInstanceIdentifier internalPath, final DOMDataTreeChangeListener delegate) {
343         requireNonNull(delegate, "delegate should not be null");
344
345         LOG.debug("Registering a listener for the configuration shard: {}", internalPath);
346
347         final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy =
348                 new DataTreeChangeListenerProxy<>(actorUtils, delegate, internalPath);
349         proxy.init(ClusterUtils.PREFIX_CONFIG_SHARD_ID);
350
351         return (ListenerRegistration<L>) proxy;
352     }
353
354     private Duration initialSettleTime() {
355         final DatastoreContext context = actorUtils.getDatastoreContext();
356         final int multiplier = context.getInitialSettleTimeoutMultiplier();
357         return multiplier == 0 ? Duration.Inf() : context.getShardLeaderElectionTimeout().duration().$times(multiplier);
358     }
359 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.