2 * Copyright (c) 2015 Brocade Communications 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 org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNotNull;
12 import static org.junit.Assert.fail;
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;
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;
55 public class IntegrationTestKit extends ShardTestKit {
57 private static final Logger LOG = LoggerFactory.getLogger(IntegrationTestKit.class);
59 protected DatastoreContext.Builder datastoreContextBuilder;
60 protected DatastoreSnapshot restoreFromSnapshot;
61 private final int commitTimeout;
63 public IntegrationTestKit(final ActorSystem actorSystem, final Builder datastoreContextBuilder) {
64 this(actorSystem, datastoreContextBuilder, 7);
67 public IntegrationTestKit(final ActorSystem actorSystem, final Builder datastoreContextBuilder, int commitTimeout) {
69 this.datastoreContextBuilder = datastoreContextBuilder;
70 this.commitTimeout = commitTimeout;
73 public DatastoreContext.Builder getDatastoreContextBuilder() {
74 return datastoreContextBuilder;
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);
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);
92 public AbstractDataStore setupAbstractDataStore(final Class<? extends AbstractDataStore> implementation,
93 final String typeName, final String... shardNames)
95 return setupAbstractDataStore(implementation, typeName, "module-shards.conf", true,
96 SchemaContextHelper.full(), shardNames);
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);
106 public AbstractDataStore setupAbstractDataStore(final Class<? extends AbstractDataStore> implementation,
107 final String typeName, final String moduleShardsConfig,
108 final boolean waitUntilLeader, final String... shardNames)
110 return setupAbstractDataStore(implementation, typeName, moduleShardsConfig, waitUntilLeader,
111 SchemaContextHelper.full(), shardNames);
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);
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)
128 final ClusterWrapper cluster = new ClusterWrapperImpl(getSystem());
129 final Configuration config = new ConfigurationImpl(moduleShardsConfig, modulesConfig);
131 datastoreContextBuilder.dataStoreName(typeName);
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());
138 final Constructor constructor = implementation.getDeclaredConstructor(
139 ActorSystem.class, ClusterWrapper.class, Configuration.class,
140 DatastoreContextFactory.class, DatastoreSnapshot.class);
142 final AbstractDataStore dataStore = (AbstractDataStore) constructor.newInstance(
143 getSystem(), cluster, config, mockContextFactory, restoreFromSnapshot);
145 dataStore.onGlobalContextUpdated(schemaContext);
147 if (waitUntilLeader) {
148 waitUntilLeader(dataStore.getActorContext(), shardNames);
151 datastoreContextBuilder = DatastoreContext.newBuilderFrom(datastoreContext);
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());
160 getDatastoreContextBuilder().dataStoreName(typeName);
162 final DatastoreContext datastoreContext = getDatastoreContextBuilder().build();
164 final DatastoreContextFactory mockContextFactory = Mockito.mock(DatastoreContextFactory.class);
165 Mockito.doReturn(datastoreContext).when(mockContextFactory).getBaseDatastoreContext();
166 Mockito.doReturn(datastoreContext).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
168 final DistributedDataStore dataStore = new DistributedDataStore(getSystem(), cluster,
169 configuration, mockContextFactory, restoreFromSnapshot);
171 dataStore.onGlobalContextUpdated(schemaContext);
173 datastoreContextBuilder = DatastoreContext.newBuilderFrom(datastoreContext);
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());
183 getDatastoreContextBuilder().dataStoreName(typeName);
185 final DatastoreContext datastoreContext =
186 getDatastoreContextBuilder().logicalStoreType(storeType).build();
188 final DatastoreContextFactory mockContextFactory = Mockito.mock(DatastoreContextFactory.class);
189 Mockito.doReturn(datastoreContext).when(mockContextFactory).getBaseDatastoreContext();
190 Mockito.doReturn(datastoreContext).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
192 final DistributedDataStore dataStore = new DistributedDataStore(getSystem(), cluster,
193 configuration, mockContextFactory, restoreFromSnapshot);
195 dataStore.onGlobalContextUpdated(schemaContext);
197 datastoreContextBuilder = DatastoreContext.newBuilderFrom(datastoreContext);
201 public void waitUntilLeader(final ActorContext actorContext, final String... shardNames) {
202 for (String shardName: shardNames) {
203 ActorRef shard = findLocalShard(actorContext, shardName);
205 assertNotNull("Shard was not created for " + shardName, shard);
207 waitUntilLeader(shard);
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);
216 waitUntilNoLeader(shard);
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()) {
232 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
235 fail("Member(s) " + otherMembersSet + " are not Up");
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();
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()) {
260 throw new IllegalStateException("Shard[" + shardName + " did not shutdown in time");
263 public static void verifyShardStats(final AbstractDataStore datastore, final String shardName,
264 final ShardStatsVerifier verifier) throws Exception {
265 ActorContext actorContext = datastore.getActorContext();
267 Future<ActorRef> future = actorContext.findLocalShardAsync(shardName);
268 ActorRef shardActor = Await.result(future, Duration.create(10, TimeUnit.SECONDS));
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);
277 verifier.verify(shardStats);
279 } catch (AssertionError e) {
281 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
288 public static void verifyShardState(final AbstractDataStore datastore, final String shardName,
289 final Consumer<OnDemandShardState> verifier) throws Exception {
290 ActorContext actorContext = datastore.getActorContext();
292 Future<ActorRef> future = actorContext.findLocalShardAsync(shardName);
293 ActorRef shardActor = Await.result(future, Duration.create(10, TimeUnit.SECONDS));
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);
302 verifier.accept(shardState);
304 } catch (AssertionError e) {
306 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
313 void testWriteTransaction(final AbstractDataStore dataStore, final YangInstanceIdentifier nodePath,
314 final NormalizedNode<?, ?> nodeToWrite) throws Exception {
316 // 1. Create a write-only Tx
318 DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
319 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
321 // 2. Write some data
323 writeTx.write(nodePath, nodeToWrite);
325 // 3. Ready the Tx for commit
327 DOMStoreThreePhaseCommitCohort cohort = writeTx.ready();
333 // 5. Verify the data in the store
335 DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
337 Optional<NormalizedNode<?, ?>> optional = readTx.read(nodePath).get(5, TimeUnit.SECONDS);
338 assertEquals("isPresent", true, optional.isPresent());
339 assertEquals("Data node", nodeToWrite, optional.get());
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);
349 void doCommit(final ListenableFuture<Boolean> canCommitFuture, final DOMStoreThreePhaseCommitCohort cohort)
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);
357 @SuppressWarnings("checkstyle:IllegalCatch")
358 void assertExceptionOnCall(final Callable<Void> callable, final Class<? extends Exception> expType)
362 fail("Expected " + expType.getSimpleName());
363 } catch (Exception e) {
364 assertEquals("Exception type", expType, e.getClass());
368 void assertExceptionOnTxChainCreates(final DOMStoreTransactionChain txChain,
369 final Class<? extends Exception> expType) throws Exception {
370 assertExceptionOnCall(() -> {
371 txChain.newWriteOnlyTransaction();
375 assertExceptionOnCall(() -> {
376 txChain.newReadWriteTransaction();
380 assertExceptionOnCall(() -> {
381 txChain.newReadOnlyTransaction();
386 public interface ShardStatsVerifier {
387 void verify(ShardStats stats);