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.assertTrue;
13 import static org.junit.Assert.fail;
15 import akka.actor.ActorRef;
16 import akka.actor.ActorSystem;
17 import akka.cluster.Cluster;
18 import akka.cluster.ClusterEvent.CurrentClusterState;
19 import akka.cluster.Member;
20 import akka.cluster.MemberStatus;
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.Optional;
28 import java.util.concurrent.Callable;
29 import java.util.concurrent.TimeUnit;
30 import java.util.function.Consumer;
31 import org.mockito.Mockito;
32 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
33 import org.opendaylight.controller.cluster.datastore.config.Configuration;
34 import org.opendaylight.controller.cluster.datastore.config.ConfigurationImpl;
35 import org.opendaylight.controller.cluster.datastore.config.EmptyModuleShardConfigProvider;
36 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
37 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
38 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
39 import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
40 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
41 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
42 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
43 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
44 import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
45 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionChain;
46 import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
49 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import scala.concurrent.Await;
53 import scala.concurrent.Future;
54 import scala.concurrent.duration.FiniteDuration;
56 public class IntegrationTestKit extends ShardTestKit {
58 private static final Logger LOG = LoggerFactory.getLogger(IntegrationTestKit.class);
60 protected DatastoreContext.Builder datastoreContextBuilder;
61 protected DatastoreSnapshot restoreFromSnapshot;
62 private final int commitTimeout;
64 public IntegrationTestKit(final ActorSystem actorSystem, final Builder datastoreContextBuilder) {
65 this(actorSystem, datastoreContextBuilder, 7);
68 public IntegrationTestKit(final ActorSystem actorSystem, final Builder datastoreContextBuilder,
69 final int commitTimeout) {
71 this.datastoreContextBuilder = datastoreContextBuilder;
72 this.commitTimeout = commitTimeout;
75 public DatastoreContext.Builder getDatastoreContextBuilder() {
76 return datastoreContextBuilder;
79 public DistributedDataStore setupDistributedDataStore(final String typeName, final String moduleShardsConfig,
80 final boolean waitUntilLeader,
81 final SchemaContext schemaContext) throws Exception {
82 return setupDistributedDataStore(typeName, moduleShardsConfig, "modules.conf", waitUntilLeader, schemaContext);
85 public DistributedDataStore setupDistributedDataStore(final String typeName, final String moduleShardsConfig,
86 final String modulesConfig,
87 final boolean waitUntilLeader,
88 final SchemaContext schemaContext,
89 final String... shardNames) throws Exception {
90 return (DistributedDataStore) setupAbstractDataStore(DistributedDataStore.class, typeName, moduleShardsConfig,
91 modulesConfig, waitUntilLeader, schemaContext, shardNames);
94 public AbstractDataStore setupAbstractDataStore(final Class<? extends AbstractDataStore> implementation,
95 final String typeName, final String... shardNames)
97 return setupAbstractDataStore(implementation, typeName, "module-shards.conf", true,
98 SchemaContextHelper.full(), shardNames);
101 public AbstractDataStore setupAbstractDataStore(final Class<? extends AbstractDataStore> implementation,
102 final String typeName, final boolean waitUntilLeader,
103 final String... shardNames) throws Exception {
104 return setupAbstractDataStore(implementation, typeName, "module-shards.conf", waitUntilLeader,
105 SchemaContextHelper.full(), shardNames);
108 public AbstractDataStore setupAbstractDataStore(final Class<? extends AbstractDataStore> implementation,
109 final String typeName, final String moduleShardsConfig,
110 final boolean waitUntilLeader, final String... shardNames)
112 return setupAbstractDataStore(implementation, typeName, moduleShardsConfig, waitUntilLeader,
113 SchemaContextHelper.full(), shardNames);
116 public AbstractDataStore setupAbstractDataStore(final Class<? extends AbstractDataStore> implementation,
117 final String typeName, final String moduleShardsConfig,
118 final boolean waitUntilLeader,
119 final SchemaContext schemaContext,
120 final String... shardNames) throws Exception {
121 return setupAbstractDataStore(implementation, typeName, moduleShardsConfig, "modules.conf", waitUntilLeader,
122 schemaContext, shardNames);
125 private AbstractDataStore setupAbstractDataStore(final Class<? extends AbstractDataStore> implementation,
126 final String typeName, final String moduleShardsConfig,
127 final String modulesConfig, final boolean waitUntilLeader,
128 final SchemaContext schemaContext, final String... shardNames)
130 final ClusterWrapper cluster = new ClusterWrapperImpl(getSystem());
131 final Configuration config = new ConfigurationImpl(moduleShardsConfig, modulesConfig);
133 setDataStoreName(typeName);
135 final DatastoreContext datastoreContext = datastoreContextBuilder.build();
136 final DatastoreContextFactory mockContextFactory = Mockito.mock(DatastoreContextFactory.class);
137 Mockito.doReturn(datastoreContext).when(mockContextFactory).getBaseDatastoreContext();
138 Mockito.doReturn(datastoreContext).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
140 final Constructor<? extends AbstractDataStore> constructor = implementation.getDeclaredConstructor(
141 ActorSystem.class, ClusterWrapper.class, Configuration.class,
142 DatastoreContextFactory.class, DatastoreSnapshot.class);
144 final AbstractDataStore dataStore = constructor.newInstance(getSystem(), cluster, config, mockContextFactory,
145 restoreFromSnapshot);
147 dataStore.onGlobalContextUpdated(schemaContext);
149 if (waitUntilLeader) {
150 waitUntilLeader(dataStore.getActorUtils(), shardNames);
153 datastoreContextBuilder = DatastoreContext.newBuilderFrom(datastoreContext);
157 private void setDataStoreName(final String typeName) {
158 if ("config".equals(typeName)) {
159 datastoreContextBuilder.logicalStoreType(LogicalDatastoreType.CONFIGURATION);
160 } else if ("operational".equals(typeName)) {
161 datastoreContextBuilder.logicalStoreType(LogicalDatastoreType.OPERATIONAL);
163 datastoreContextBuilder.dataStoreName(typeName);
167 public DistributedDataStore setupDistributedDataStoreWithoutConfig(final String typeName,
168 final SchemaContext schemaContext) {
169 final ClusterWrapper cluster = new ClusterWrapperImpl(getSystem());
170 final ConfigurationImpl configuration = new ConfigurationImpl(new EmptyModuleShardConfigProvider());
172 setDataStoreName(typeName);
174 final DatastoreContext datastoreContext = getDatastoreContextBuilder().build();
176 final DatastoreContextFactory mockContextFactory = Mockito.mock(DatastoreContextFactory.class);
177 Mockito.doReturn(datastoreContext).when(mockContextFactory).getBaseDatastoreContext();
178 Mockito.doReturn(datastoreContext).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
180 final DistributedDataStore dataStore = new DistributedDataStore(getSystem(), cluster,
181 configuration, mockContextFactory, restoreFromSnapshot);
183 dataStore.onGlobalContextUpdated(schemaContext);
185 datastoreContextBuilder = DatastoreContext.newBuilderFrom(datastoreContext);
189 public DistributedDataStore setupDistributedDataStoreWithoutConfig(final String typeName,
190 final SchemaContext schemaContext,
191 final LogicalDatastoreType storeType) {
192 final ClusterWrapper cluster = new ClusterWrapperImpl(getSystem());
193 final ConfigurationImpl configuration = new ConfigurationImpl(new EmptyModuleShardConfigProvider());
195 setDataStoreName(typeName);
197 final DatastoreContext datastoreContext =
198 getDatastoreContextBuilder().logicalStoreType(storeType).build();
200 final DatastoreContextFactory mockContextFactory = Mockito.mock(DatastoreContextFactory.class);
201 Mockito.doReturn(datastoreContext).when(mockContextFactory).getBaseDatastoreContext();
202 Mockito.doReturn(datastoreContext).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
204 final DistributedDataStore dataStore = new DistributedDataStore(getSystem(), cluster,
205 configuration, mockContextFactory, restoreFromSnapshot);
207 dataStore.onGlobalContextUpdated(schemaContext);
209 datastoreContextBuilder = DatastoreContext.newBuilderFrom(datastoreContext);
213 public void waitUntilLeader(final ActorUtils actorUtils, final String... shardNames) {
214 for (String shardName: shardNames) {
215 ActorRef shard = findLocalShard(actorUtils, shardName);
217 assertNotNull("Shard was not created for " + shardName, shard);
219 waitUntilLeader(shard);
223 public void waitUntilNoLeader(final ActorUtils actorUtils, final String... shardNames) {
224 for (String shardName: shardNames) {
225 ActorRef shard = findLocalShard(actorUtils, shardName);
226 assertNotNull("No local shard found for " + shardName, shard);
228 waitUntilNoLeader(shard);
232 public void waitForMembersUp(final String... otherMembers) {
233 Set<String> otherMembersSet = Sets.newHashSet(otherMembers);
234 Stopwatch sw = Stopwatch.createStarted();
235 while (sw.elapsed(TimeUnit.SECONDS) <= 10) {
236 CurrentClusterState state = Cluster.get(getSystem()).state();
237 for (Member m: state.getMembers()) {
238 if (m.status() == MemberStatus.up() && otherMembersSet.remove(m.getRoles().iterator().next())
239 && otherMembersSet.isEmpty()) {
244 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
247 fail("Member(s) " + otherMembersSet + " are not Up");
250 public static ActorRef findLocalShard(final ActorUtils actorUtils, final String shardName) {
251 ActorRef shard = null;
252 for (int i = 0; i < 20 * 5 && shard == null; i++) {
253 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
254 com.google.common.base.Optional<ActorRef> shardReply = actorUtils.findLocalShard(shardName);
255 if (shardReply.isPresent()) {
256 shard = shardReply.get();
262 public static void waitUntilShardIsDown(final ActorUtils actorUtils, final String shardName) {
263 for (int i = 0; i < 20 * 5 ; i++) {
264 LOG.debug("Waiting for shard down {}", shardName);
265 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
266 com.google.common.base.Optional<ActorRef> shardReply = actorUtils.findLocalShard(shardName);
267 if (!shardReply.isPresent()) {
272 throw new IllegalStateException("Shard[" + shardName + " did not shutdown in time");
275 public static void verifyShardStats(final AbstractDataStore datastore, final String shardName,
276 final ShardStatsVerifier verifier) throws Exception {
277 ActorUtils actorUtils = datastore.getActorUtils();
279 Future<ActorRef> future = actorUtils.findLocalShardAsync(shardName);
280 ActorRef shardActor = Await.result(future, FiniteDuration.create(10, TimeUnit.SECONDS));
282 AssertionError lastError = null;
283 Stopwatch sw = Stopwatch.createStarted();
284 while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
285 ShardStats shardStats = (ShardStats)actorUtils
286 .executeOperation(shardActor, Shard.GET_SHARD_MBEAN_MESSAGE);
289 verifier.verify(shardStats);
291 } catch (AssertionError e) {
293 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
300 public static void verifyShardState(final AbstractDataStore datastore, final String shardName,
301 final Consumer<OnDemandShardState> verifier) throws Exception {
302 ActorUtils actorUtils = datastore.getActorUtils();
304 Future<ActorRef> future = actorUtils.findLocalShardAsync(shardName);
305 ActorRef shardActor = Await.result(future, FiniteDuration.create(10, TimeUnit.SECONDS));
307 AssertionError lastError = null;
308 Stopwatch sw = Stopwatch.createStarted();
309 while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
310 OnDemandShardState shardState = (OnDemandShardState)actorUtils
311 .executeOperation(shardActor, GetOnDemandRaftState.INSTANCE);
314 verifier.accept(shardState);
316 } catch (AssertionError e) {
318 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
325 void testWriteTransaction(final AbstractDataStore dataStore, final YangInstanceIdentifier nodePath,
326 final NormalizedNode<?, ?> nodeToWrite) throws Exception {
328 // 1. Create a write-only Tx
330 DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
331 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
333 // 2. Write some data
335 writeTx.write(nodePath, nodeToWrite);
337 // 3. Ready the Tx for commit
339 DOMStoreThreePhaseCommitCohort cohort = writeTx.ready();
345 // 5. Verify the data in the store
347 DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
349 Optional<NormalizedNode<?, ?>> optional = readTx.read(nodePath).get(5, TimeUnit.SECONDS);
350 assertTrue("isPresent", optional.isPresent());
351 assertEquals("Data node", nodeToWrite, optional.get());
354 public void doCommit(final DOMStoreThreePhaseCommitCohort cohort) throws Exception {
355 Boolean canCommit = cohort.canCommit().get(commitTimeout, TimeUnit.SECONDS);
356 assertEquals("canCommit", Boolean.TRUE, canCommit);
357 cohort.preCommit().get(5, TimeUnit.SECONDS);
358 cohort.commit().get(5, TimeUnit.SECONDS);
361 void doCommit(final ListenableFuture<Boolean> canCommitFuture, final DOMStoreThreePhaseCommitCohort cohort)
363 Boolean canCommit = canCommitFuture.get(commitTimeout, TimeUnit.SECONDS);
364 assertEquals("canCommit", Boolean.TRUE, canCommit);
365 cohort.preCommit().get(5, TimeUnit.SECONDS);
366 cohort.commit().get(5, TimeUnit.SECONDS);
369 @SuppressWarnings("checkstyle:IllegalCatch")
370 void assertExceptionOnCall(final Callable<Void> callable, final Class<? extends Exception> expType) {
373 fail("Expected " + expType.getSimpleName());
374 } catch (Exception e) {
375 assertEquals("Exception type", expType, e.getClass());
379 void assertExceptionOnTxChainCreates(final DOMStoreTransactionChain txChain,
380 final Class<? extends Exception> expType) {
381 assertExceptionOnCall(() -> {
382 txChain.newWriteOnlyTransaction();
386 assertExceptionOnCall(() -> {
387 txChain.newReadWriteTransaction();
391 assertExceptionOnCall(() -> {
392 txChain.newReadOnlyTransaction();
397 public interface ShardStatsVerifier {
398 void verify(ShardStats stats);