d6bb8182a747b0c16700cb52acf280efc551aae3
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / test / java / org / opendaylight / controller / cluster / datastore / IntegrationTestKit.java
1 /*
2  * Copyright (c) 2015 Brocade Communications 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 org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNotNull;
12 import static org.junit.Assert.fail;
13
14 import akka.actor.ActorRef;
15 import akka.actor.ActorSystem;
16 import akka.cluster.Cluster;
17 import akka.cluster.ClusterEvent.CurrentClusterState;
18 import akka.cluster.Member;
19 import akka.cluster.MemberStatus;
20 import com.google.common.base.Optional;
21 import com.google.common.base.Stopwatch;
22 import com.google.common.collect.Sets;
23 import com.google.common.util.concurrent.ListenableFuture;
24 import com.google.common.util.concurrent.Uninterruptibles;
25 import java.lang.reflect.Constructor;
26 import java.util.Set;
27 import java.util.concurrent.Callable;
28 import java.util.concurrent.TimeUnit;
29 import java.util.function.Consumer;
30 import org.mockito.Mockito;
31 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
32 import org.opendaylight.controller.cluster.datastore.config.Configuration;
33 import org.opendaylight.controller.cluster.datastore.config.ConfigurationImpl;
34 import org.opendaylight.controller.cluster.datastore.config.EmptyModuleShardConfigProvider;
35 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
36 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
37 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
38 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
39 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
40 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
41 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
42 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
43 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
44 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
45 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
48 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51 import scala.concurrent.Await;
52 import scala.concurrent.Future;
53 import scala.concurrent.duration.Duration;
54
55 public class IntegrationTestKit extends ShardTestKit {
56
57     private static final Logger LOG = LoggerFactory.getLogger(IntegrationTestKit.class);
58
59     protected DatastoreContext.Builder datastoreContextBuilder;
60     protected DatastoreSnapshot restoreFromSnapshot;
61     private final int commitTimeout;
62
63     public IntegrationTestKit(final ActorSystem actorSystem, final Builder datastoreContextBuilder) {
64         this(actorSystem, datastoreContextBuilder, 7);
65     }
66
67     public IntegrationTestKit(final ActorSystem actorSystem, final Builder datastoreContextBuilder, int commitTimeout) {
68         super(actorSystem);
69         this.datastoreContextBuilder = datastoreContextBuilder;
70         this.commitTimeout = commitTimeout;
71     }
72
73     public DatastoreContext.Builder getDatastoreContextBuilder() {
74         return datastoreContextBuilder;
75     }
76
77     public DistributedDataStore setupDistributedDataStore(final String typeName, final String moduleShardsConfig,
78                                                           final boolean waitUntilLeader,
79                                                           final SchemaContext schemaContext) throws Exception {
80         return setupDistributedDataStore(typeName, moduleShardsConfig, "modules.conf", waitUntilLeader, schemaContext);
81     }
82
83     public DistributedDataStore setupDistributedDataStore(final String typeName, final String moduleShardsConfig,
84                                                           final String modulesConfig,
85                                                           final boolean waitUntilLeader,
86                                                           final SchemaContext schemaContext,
87                                                           final String... shardNames) throws Exception {
88         return (DistributedDataStore) setupAbstractDataStore(DistributedDataStore.class, typeName, moduleShardsConfig,
89                 modulesConfig, waitUntilLeader, schemaContext, shardNames);
90     }
91
92     public AbstractDataStore setupAbstractDataStore(final Class<? extends AbstractDataStore> implementation,
93                                                     final String typeName, final String... shardNames)
94             throws Exception {
95         return setupAbstractDataStore(implementation, typeName, "module-shards.conf", true,
96                 SchemaContextHelper.full(), shardNames);
97     }
98
99     public AbstractDataStore setupAbstractDataStore(final Class<? extends AbstractDataStore> implementation,
100                                                     final String typeName, final boolean waitUntilLeader,
101                                                     final String... shardNames) throws Exception {
102         return setupAbstractDataStore(implementation, typeName, "module-shards.conf", waitUntilLeader,
103                 SchemaContextHelper.full(), shardNames);
104     }
105
106     public AbstractDataStore setupAbstractDataStore(final Class<? extends AbstractDataStore> implementation,
107                                                     final String typeName, final String moduleShardsConfig,
108                                                     final boolean waitUntilLeader, final String... shardNames)
109             throws Exception {
110         return setupAbstractDataStore(implementation, typeName, moduleShardsConfig, waitUntilLeader,
111                 SchemaContextHelper.full(), shardNames);
112     }
113
114     public AbstractDataStore setupAbstractDataStore(final Class<? extends AbstractDataStore> implementation,
115                                                     final String typeName, final String moduleShardsConfig,
116                                                     final boolean waitUntilLeader,
117                                                     final SchemaContext schemaContext,
118                                                     final String... shardNames) throws Exception {
119         return setupAbstractDataStore(implementation, typeName, moduleShardsConfig, "modules.conf", waitUntilLeader,
120                 schemaContext, shardNames);
121     }
122
123     private AbstractDataStore setupAbstractDataStore(final Class<? extends AbstractDataStore> implementation,
124                                                      final String typeName, final String moduleShardsConfig,
125                                                      final String modulesConfig, final boolean waitUntilLeader,
126                                                      final SchemaContext schemaContext, final String... shardNames)
127             throws Exception {
128         final ClusterWrapper cluster = new ClusterWrapperImpl(getSystem());
129         final Configuration config = new ConfigurationImpl(moduleShardsConfig, modulesConfig);
130
131         datastoreContextBuilder.dataStoreName(typeName);
132
133         final DatastoreContext datastoreContext = datastoreContextBuilder.build();
134         final DatastoreContextFactory mockContextFactory = Mockito.mock(DatastoreContextFactory.class);
135         Mockito.doReturn(datastoreContext).when(mockContextFactory).getBaseDatastoreContext();
136         Mockito.doReturn(datastoreContext).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
137
138         final Constructor constructor = implementation.getDeclaredConstructor(
139                 ActorSystem.class, ClusterWrapper.class, Configuration.class,
140                 DatastoreContextFactory.class, DatastoreSnapshot.class);
141
142         final AbstractDataStore dataStore = (AbstractDataStore) constructor.newInstance(
143                 getSystem(), cluster, config, mockContextFactory, restoreFromSnapshot);
144
145         dataStore.onGlobalContextUpdated(schemaContext);
146
147         if (waitUntilLeader) {
148             waitUntilLeader(dataStore.getActorContext(), shardNames);
149         }
150
151         datastoreContextBuilder = DatastoreContext.newBuilderFrom(datastoreContext);
152         return dataStore;
153     }
154
155     public DistributedDataStore setupDistributedDataStoreWithoutConfig(final String typeName,
156                                                                        final SchemaContext schemaContext) {
157         final ClusterWrapper cluster = new ClusterWrapperImpl(getSystem());
158         final ConfigurationImpl configuration = new ConfigurationImpl(new EmptyModuleShardConfigProvider());
159
160         getDatastoreContextBuilder().dataStoreName(typeName);
161
162         final DatastoreContext datastoreContext = getDatastoreContextBuilder().build();
163
164         final DatastoreContextFactory mockContextFactory = Mockito.mock(DatastoreContextFactory.class);
165         Mockito.doReturn(datastoreContext).when(mockContextFactory).getBaseDatastoreContext();
166         Mockito.doReturn(datastoreContext).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
167
168         final DistributedDataStore dataStore = new DistributedDataStore(getSystem(), cluster,
169                 configuration, mockContextFactory, restoreFromSnapshot);
170
171         dataStore.onGlobalContextUpdated(schemaContext);
172
173         datastoreContextBuilder = DatastoreContext.newBuilderFrom(datastoreContext);
174         return dataStore;
175     }
176
177     public DistributedDataStore setupDistributedDataStoreWithoutConfig(final String typeName,
178                                                                        final SchemaContext schemaContext,
179                                                                        final LogicalDatastoreType storeType) {
180         final ClusterWrapper cluster = new ClusterWrapperImpl(getSystem());
181         final ConfigurationImpl configuration = new ConfigurationImpl(new EmptyModuleShardConfigProvider());
182
183         getDatastoreContextBuilder().dataStoreName(typeName);
184
185         final DatastoreContext datastoreContext =
186                 getDatastoreContextBuilder().logicalStoreType(storeType).build();
187
188         final DatastoreContextFactory mockContextFactory = Mockito.mock(DatastoreContextFactory.class);
189         Mockito.doReturn(datastoreContext).when(mockContextFactory).getBaseDatastoreContext();
190         Mockito.doReturn(datastoreContext).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
191
192         final DistributedDataStore dataStore = new DistributedDataStore(getSystem(), cluster,
193                 configuration, mockContextFactory, restoreFromSnapshot);
194
195         dataStore.onGlobalContextUpdated(schemaContext);
196
197         datastoreContextBuilder = DatastoreContext.newBuilderFrom(datastoreContext);
198         return dataStore;
199     }
200
201     public void waitUntilLeader(final ActorContext actorContext, final String... shardNames) {
202         for (String shardName: shardNames) {
203             ActorRef shard = findLocalShard(actorContext, shardName);
204
205             assertNotNull("Shard was not created for " + shardName, shard);
206
207             waitUntilLeader(shard);
208         }
209     }
210
211     public void waitUntilNoLeader(final ActorContext actorContext, final String... shardNames) {
212         for (String shardName: shardNames) {
213             ActorRef shard = findLocalShard(actorContext, shardName);
214             assertNotNull("No local shard found for " + shardName, shard);
215
216             waitUntilNoLeader(shard);
217         }
218     }
219
220     public void waitForMembersUp(final String... otherMembers) {
221         Set<String> otherMembersSet = Sets.newHashSet(otherMembers);
222         Stopwatch sw = Stopwatch.createStarted();
223         while (sw.elapsed(TimeUnit.SECONDS) <= 10) {
224             CurrentClusterState state = Cluster.get(getSystem()).state();
225             for (Member m: state.getMembers()) {
226                 if (m.status() == MemberStatus.up() && otherMembersSet.remove(m.getRoles().iterator().next())
227                         && otherMembersSet.isEmpty()) {
228                     return;
229                 }
230             }
231
232             Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
233         }
234
235         fail("Member(s) " + otherMembersSet + " are not Up");
236     }
237
238     public static ActorRef findLocalShard(final ActorContext actorContext, final String shardName) {
239         ActorRef shard = null;
240         for (int i = 0; i < 20 * 5 && shard == null; i++) {
241             Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
242             Optional<ActorRef> shardReply = actorContext.findLocalShard(shardName);
243             if (shardReply.isPresent()) {
244                 shard = shardReply.get();
245             }
246         }
247         return shard;
248     }
249
250     public static void waitUntilShardIsDown(final ActorContext actorContext, final String shardName) {
251         for (int i = 0; i < 20 * 5 ; i++) {
252             LOG.debug("Waiting for shard down {}", shardName);
253             Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
254             Optional<ActorRef> shardReply = actorContext.findLocalShard(shardName);
255             if (!shardReply.isPresent()) {
256                 return;
257             }
258         }
259
260         throw new IllegalStateException("Shard[" + shardName + " did not shutdown in time");
261     }
262
263     public static void verifyShardStats(final AbstractDataStore datastore, final String shardName,
264             final ShardStatsVerifier verifier) throws Exception {
265         ActorContext actorContext = datastore.getActorContext();
266
267         Future<ActorRef> future = actorContext.findLocalShardAsync(shardName);
268         ActorRef shardActor = Await.result(future, Duration.create(10, TimeUnit.SECONDS));
269
270         AssertionError lastError = null;
271         Stopwatch sw = Stopwatch.createStarted();
272         while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
273             ShardStats shardStats = (ShardStats)actorContext
274                     .executeOperation(shardActor, Shard.GET_SHARD_MBEAN_MESSAGE);
275
276             try {
277                 verifier.verify(shardStats);
278                 return;
279             } catch (AssertionError e) {
280                 lastError = e;
281                 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
282             }
283         }
284
285         throw lastError;
286     }
287
288     public static void verifyShardState(final AbstractDataStore datastore, final String shardName,
289             final Consumer<OnDemandShardState> verifier) throws Exception {
290         ActorContext actorContext = datastore.getActorContext();
291
292         Future<ActorRef> future = actorContext.findLocalShardAsync(shardName);
293         ActorRef shardActor = Await.result(future, Duration.create(10, TimeUnit.SECONDS));
294
295         AssertionError lastError = null;
296         Stopwatch sw = Stopwatch.createStarted();
297         while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
298             OnDemandShardState shardState = (OnDemandShardState)actorContext
299                     .executeOperation(shardActor, GetOnDemandRaftState.INSTANCE);
300
301             try {
302                 verifier.accept(shardState);
303                 return;
304             } catch (AssertionError e) {
305                 lastError = e;
306                 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
307             }
308         }
309
310         throw lastError;
311     }
312
313     void testWriteTransaction(final AbstractDataStore dataStore, final YangInstanceIdentifier nodePath,
314             final NormalizedNode<?, ?> nodeToWrite) throws Exception {
315
316         // 1. Create a write-only Tx
317
318         DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
319         assertNotNull("newWriteOnlyTransaction returned null", writeTx);
320
321         // 2. Write some data
322
323         writeTx.write(nodePath, nodeToWrite);
324
325         // 3. Ready the Tx for commit
326
327         DOMStoreThreePhaseCommitCohort cohort = writeTx.ready();
328
329         // 4. Commit the Tx
330
331         doCommit(cohort);
332
333         // 5. Verify the data in the store
334
335         DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
336
337         Optional<NormalizedNode<?, ?>> optional = readTx.read(nodePath).get(5, TimeUnit.SECONDS);
338         assertEquals("isPresent", true, optional.isPresent());
339         assertEquals("Data node", nodeToWrite, optional.get());
340     }
341
342     public void doCommit(final DOMStoreThreePhaseCommitCohort cohort) throws Exception {
343         Boolean canCommit = cohort.canCommit().get(commitTimeout, TimeUnit.SECONDS);
344         assertEquals("canCommit", true, canCommit);
345         cohort.preCommit().get(5, TimeUnit.SECONDS);
346         cohort.commit().get(5, TimeUnit.SECONDS);
347     }
348
349     void doCommit(final ListenableFuture<Boolean> canCommitFuture, final DOMStoreThreePhaseCommitCohort cohort)
350             throws Exception {
351         Boolean canCommit = canCommitFuture.get(commitTimeout, TimeUnit.SECONDS);
352         assertEquals("canCommit", true, canCommit);
353         cohort.preCommit().get(5, TimeUnit.SECONDS);
354         cohort.commit().get(5, TimeUnit.SECONDS);
355     }
356
357     @SuppressWarnings("checkstyle:IllegalCatch")
358     void assertExceptionOnCall(final Callable<Void> callable, final Class<? extends Exception> expType)
359             throws Exception {
360         try {
361             callable.call();
362             fail("Expected " + expType.getSimpleName());
363         } catch (Exception e) {
364             assertEquals("Exception type", expType, e.getClass());
365         }
366     }
367
368     void assertExceptionOnTxChainCreates(final DOMStoreTransactionChain txChain,
369             final Class<? extends Exception> expType) throws Exception {
370         assertExceptionOnCall(() -> {
371             txChain.newWriteOnlyTransaction();
372             return null;
373         }, expType);
374
375         assertExceptionOnCall(() -> {
376             txChain.newReadWriteTransaction();
377             return null;
378         }, expType);
379
380         assertExceptionOnCall(() -> {
381             txChain.newReadOnlyTransaction();
382             return null;
383         }, expType);
384     }
385
386     public interface ShardStatsVerifier {
387         void verify(ShardStats stats);
388     }
389 }