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