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;
26 import java.util.concurrent.Callable;
27 import java.util.concurrent.TimeUnit;
28 import org.mockito.Mockito;
29 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
30 import org.opendaylight.controller.cluster.datastore.config.Configuration;
31 import org.opendaylight.controller.cluster.datastore.config.ConfigurationImpl;
32 import org.opendaylight.controller.cluster.datastore.config.EmptyModuleShardConfigProvider;
33 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
34 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
35 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
36 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
37 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
38 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
39 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
40 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
43 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import scala.concurrent.Await;
47 import scala.concurrent.Future;
48 import scala.concurrent.duration.Duration;
50 public class IntegrationTestKit extends ShardTestKit {
52 private static final Logger LOG = LoggerFactory.getLogger(IntegrationTestKit.class);
54 protected DatastoreContext.Builder datastoreContextBuilder;
55 protected DatastoreSnapshot restoreFromSnapshot;
57 public IntegrationTestKit(final ActorSystem actorSystem, final Builder datastoreContextBuilder) {
59 this.datastoreContextBuilder = datastoreContextBuilder;
62 public DatastoreContext.Builder getDatastoreContextBuilder() {
63 return datastoreContextBuilder;
66 public AbstractDataStore setupDistributedDataStore(final String typeName, final String... shardNames) {
67 return setupDistributedDataStore(typeName, "module-shards.conf", true, SchemaContextHelper.full(), shardNames);
70 public AbstractDataStore setupDistributedDataStore(final String typeName, final boolean waitUntilLeader,
71 final String... shardNames) {
72 return setupDistributedDataStore(typeName, "module-shards.conf", waitUntilLeader,
73 SchemaContextHelper.full(), shardNames);
76 public AbstractDataStore setupDistributedDataStore(final String typeName, final String moduleShardsConfig,
77 final boolean waitUntilLeader, final String... shardNames) {
78 return setupDistributedDataStore(typeName, moduleShardsConfig, waitUntilLeader,
79 SchemaContextHelper.full(), shardNames);
82 public AbstractDataStore setupDistributedDataStore(final String typeName, final String moduleShardsConfig,
83 final boolean waitUntilLeader, final SchemaContext schemaContext, final String... shardNames) {
84 final ClusterWrapper cluster = new ClusterWrapperImpl(getSystem());
85 final Configuration config = new ConfigurationImpl(moduleShardsConfig, "modules.conf");
87 datastoreContextBuilder.dataStoreName(typeName);
89 DatastoreContext datastoreContext = datastoreContextBuilder.build();
90 DatastoreContextFactory mockContextFactory = Mockito.mock(DatastoreContextFactory.class);
91 Mockito.doReturn(datastoreContext).when(mockContextFactory).getBaseDatastoreContext();
92 Mockito.doReturn(datastoreContext).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
94 AbstractDataStore dataStore = new DistributedDataStore(getSystem(), cluster, config, mockContextFactory,
97 dataStore.onGlobalContextUpdated(schemaContext);
99 if (waitUntilLeader) {
100 waitUntilLeader(dataStore.getActorContext(), shardNames);
103 datastoreContextBuilder = DatastoreContext.newBuilderFrom(datastoreContext);
107 public DistributedDataStore setupDistributedDataStoreWithoutConfig(final String typeName,
108 final SchemaContext schemaContext) {
109 final ClusterWrapper cluster = new ClusterWrapperImpl(getSystem());
110 final ConfigurationImpl configuration = new ConfigurationImpl(new EmptyModuleShardConfigProvider());
112 getDatastoreContextBuilder().dataStoreName(typeName);
114 final DatastoreContext datastoreContext = getDatastoreContextBuilder().build();
116 final DatastoreContextFactory mockContextFactory = Mockito.mock(DatastoreContextFactory.class);
117 Mockito.doReturn(datastoreContext).when(mockContextFactory).getBaseDatastoreContext();
118 Mockito.doReturn(datastoreContext).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
120 final DistributedDataStore dataStore = new DistributedDataStore(getSystem(), cluster,
121 configuration, mockContextFactory, restoreFromSnapshot);
123 dataStore.onGlobalContextUpdated(schemaContext);
125 datastoreContextBuilder = DatastoreContext.newBuilderFrom(datastoreContext);
129 public void waitUntilLeader(final ActorContext actorContext, final String... shardNames) {
130 for (String shardName: shardNames) {
131 ActorRef shard = findLocalShard(actorContext, shardName);
133 assertNotNull("Shard was not created for " + shardName, shard);
135 waitUntilLeader(shard);
139 public void waitUntilNoLeader(final ActorContext actorContext, final String... shardNames) {
140 for (String shardName: shardNames) {
141 ActorRef shard = findLocalShard(actorContext, shardName);
142 assertNotNull("No local shard found for " + shardName, shard);
144 waitUntilNoLeader(shard);
148 public void waitForMembersUp(final String... otherMembers) {
149 Set<String> otherMembersSet = Sets.newHashSet(otherMembers);
150 Stopwatch sw = Stopwatch.createStarted();
151 while (sw.elapsed(TimeUnit.SECONDS) <= 10) {
152 CurrentClusterState state = Cluster.get(getSystem()).state();
153 for (Member m: state.getMembers()) {
154 if (m.status() == MemberStatus.up() && otherMembersSet.remove(m.getRoles().iterator().next())
155 && otherMembersSet.isEmpty()) {
160 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
163 fail("Member(s) " + otherMembersSet + " are not Up");
166 public static ActorRef findLocalShard(final ActorContext actorContext, final String shardName) {
167 ActorRef shard = null;
168 for (int i = 0; i < 20 * 5 && shard == null; i++) {
169 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
170 Optional<ActorRef> shardReply = actorContext.findLocalShard(shardName);
171 if (shardReply.isPresent()) {
172 shard = shardReply.get();
178 public static void waitUntilShardIsDown(ActorContext actorContext, String shardName) {
179 for (int i = 0; i < 20 * 5 ; i++) {
180 LOG.debug("Waiting for shard down {}", shardName);
181 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
182 Optional<ActorRef> shardReply = actorContext.findLocalShard(shardName);
183 if (!shardReply.isPresent()) {
188 throw new IllegalStateException("Shard[" + shardName + " did not shutdown in time");
191 public static void verifyShardStats(final AbstractDataStore datastore, final String shardName,
192 final ShardStatsVerifier verifier) throws Exception {
193 ActorContext actorContext = datastore.getActorContext();
195 Future<ActorRef> future = actorContext.findLocalShardAsync(shardName);
196 ActorRef shardActor = Await.result(future, Duration.create(10, TimeUnit.SECONDS));
198 AssertionError lastError = null;
199 Stopwatch sw = Stopwatch.createStarted();
200 while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
201 ShardStats shardStats = (ShardStats)actorContext
202 .executeOperation(shardActor, Shard.GET_SHARD_MBEAN_MESSAGE);
205 verifier.verify(shardStats);
207 } catch (AssertionError e) {
209 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
216 void testWriteTransaction(final AbstractDataStore dataStore, final YangInstanceIdentifier nodePath,
217 final NormalizedNode<?, ?> nodeToWrite) throws Exception {
219 // 1. Create a write-only Tx
221 DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
222 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
224 // 2. Write some data
226 writeTx.write(nodePath, nodeToWrite);
228 // 3. Ready the Tx for commit
230 DOMStoreThreePhaseCommitCohort cohort = writeTx.ready();
236 // 5. Verify the data in the store
238 DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
240 Optional<NormalizedNode<?, ?>> optional = readTx.read(nodePath).get(5, TimeUnit.SECONDS);
241 assertEquals("isPresent", true, optional.isPresent());
242 assertEquals("Data node", nodeToWrite, optional.get());
245 public void doCommit(final DOMStoreThreePhaseCommitCohort cohort) throws Exception {
246 Boolean canCommit = cohort.canCommit().get(7, TimeUnit.SECONDS);
247 assertEquals("canCommit", true, canCommit);
248 cohort.preCommit().get(5, TimeUnit.SECONDS);
249 cohort.commit().get(5, TimeUnit.SECONDS);
252 void doCommit(final ListenableFuture<Boolean> canCommitFuture, final DOMStoreThreePhaseCommitCohort cohort)
254 Boolean canCommit = canCommitFuture.get(7, TimeUnit.SECONDS);
255 assertEquals("canCommit", true, canCommit);
256 cohort.preCommit().get(5, TimeUnit.SECONDS);
257 cohort.commit().get(5, TimeUnit.SECONDS);
260 @SuppressWarnings("checkstyle:IllegalCatch")
261 void assertExceptionOnCall(final Callable<Void> callable, final Class<? extends Exception> expType)
265 fail("Expected " + expType.getSimpleName());
266 } catch (Exception e) {
267 assertEquals("Exception type", expType, e.getClass());
271 void assertExceptionOnTxChainCreates(final DOMStoreTransactionChain txChain,
272 final Class<? extends Exception> expType) throws Exception {
273 assertExceptionOnCall(() -> {
274 txChain.newWriteOnlyTransaction();
278 assertExceptionOnCall(() -> {
279 txChain.newReadWriteTransaction();
283 assertExceptionOnCall(() -> {
284 txChain.newReadOnlyTransaction();
289 public interface ShardStatsVerifier {
290 void verify(ShardStats stats);