132ac47e7da77de739c6fb1b50fb7d201ce81259
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / test / java / org / opendaylight / controller / cluster / datastore / DistributedDataStoreRemotingIntegrationTest.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.assertTrue;
13 import static org.junit.Assert.fail;
14 import static org.mockito.Matchers.any;
15 import static org.mockito.Matchers.eq;
16 import static org.mockito.Mockito.timeout;
17 import static org.mockito.Mockito.verify;
18 import akka.actor.ActorRef;
19 import akka.actor.ActorSelection;
20 import akka.actor.ActorSystem;
21 import akka.actor.Address;
22 import akka.actor.AddressFromURIString;
23 import akka.cluster.Cluster;
24 import akka.dispatch.Futures;
25 import akka.pattern.AskTimeoutException;
26 import akka.pattern.Patterns;
27 import akka.testkit.JavaTestKit;
28 import com.google.common.base.Optional;
29 import com.google.common.base.Supplier;
30 import com.google.common.collect.ImmutableMap;
31 import com.google.common.util.concurrent.ListenableFuture;
32 import com.google.common.util.concurrent.MoreExecutors;
33 import com.google.common.util.concurrent.Uninterruptibles;
34 import com.typesafe.config.ConfigFactory;
35 import java.math.BigInteger;
36 import java.util.Arrays;
37 import java.util.LinkedList;
38 import java.util.concurrent.ExecutionException;
39 import java.util.concurrent.TimeUnit;
40 import org.junit.After;
41 import org.junit.Before;
42 import org.junit.Test;
43 import org.mockito.Mockito;
44 import org.mockito.invocation.InvocationOnMock;
45 import org.mockito.stubbing.Answer;
46 import org.opendaylight.controller.cluster.databroker.ConcurrentDOMDataBroker;
47 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
48 import org.opendaylight.controller.cluster.datastore.IntegrationTestKit.ShardStatsVerifier;
49 import org.opendaylight.controller.cluster.datastore.MemberNode.RaftStateVerifier;
50 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
51 import org.opendaylight.controller.cluster.datastore.exceptions.ShardLeaderNotRespondingException;
52 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
53 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
54 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
55 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
56 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
57 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
58 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
59 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
60 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
61 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
62 import org.opendaylight.controller.cluster.raft.client.messages.Shutdown;
63 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
64 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
65 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
66 import org.opendaylight.controller.md.cluster.datastore.model.PeopleModel;
67 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
68 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
69 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
70 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
71 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
72 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
73 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
74 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
75 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
76 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
77 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
78 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
79 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
80 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
81 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
82 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
83 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
84 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
85 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
86 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
87 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
88 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
89 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
90 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
91 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
92 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
93 import scala.concurrent.Await;
94 import scala.concurrent.Future;
95 import scala.concurrent.duration.FiniteDuration;
96
97 /**
98  * End-to-end distributed data store tests that exercise remote shards and transactions.
99  *
100  * @author Thomas Pantelis
101  */
102 public class DistributedDataStoreRemotingIntegrationTest {
103
104     private static final String[] CARS_AND_PEOPLE = {"cars", "people"};
105     private static final String[] CARS = {"cars"};
106
107     private static final Address MEMBER_1_ADDRESS = AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2558");
108     private static final Address MEMBER_2_ADDRESS = AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2559");
109
110     private static final String MODULE_SHARDS_CARS_ONLY_1_2 = "module-shards-cars-member-1-and-2.conf";
111     private static final String MODULE_SHARDS_CARS_PEOPLE_1_2 = "module-shards-member1-and-2.conf";
112     private static final String MODULE_SHARDS_CARS_PEOPLE_1_2_3 = "module-shards-member1-and-2-and-3.conf";
113
114     private ActorSystem leaderSystem;
115     private ActorSystem followerSystem;
116     private ActorSystem follower2System;
117
118     private final DatastoreContext.Builder leaderDatastoreContextBuilder =
119             DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2);
120
121     private final DatastoreContext.Builder followerDatastoreContextBuilder =
122             DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5).
123                 customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
124
125     private DistributedDataStore followerDistributedDataStore;
126     private DistributedDataStore leaderDistributedDataStore;
127     private IntegrationTestKit followerTestKit;
128     private IntegrationTestKit leaderTestKit;
129
130     @Before
131     public void setUp() {
132         leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
133         Cluster.get(leaderSystem).join(MEMBER_1_ADDRESS);
134
135         followerSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member2"));
136         Cluster.get(followerSystem).join(MEMBER_1_ADDRESS);
137
138         follower2System = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member3"));
139         Cluster.get(follower2System).join(MEMBER_1_ADDRESS);
140     }
141
142     @After
143     public void tearDown() {
144         JavaTestKit.shutdownActorSystem(leaderSystem);
145         JavaTestKit.shutdownActorSystem(followerSystem);
146         JavaTestKit.shutdownActorSystem(follower2System);
147     }
148
149     private void initDatastoresWithCars(String type) {
150         initDatastores(type, MODULE_SHARDS_CARS_ONLY_1_2, CARS);
151     }
152
153     private void initDatastoresWithCarsAndPeople(String type) {
154         initDatastores(type, MODULE_SHARDS_CARS_PEOPLE_1_2, CARS_AND_PEOPLE);
155     }
156
157     private void initDatastores(String type, String moduleShardsConfig, String[] shards) {
158         leaderTestKit = new IntegrationTestKit(leaderSystem, leaderDatastoreContextBuilder);
159
160         leaderDistributedDataStore = leaderTestKit.setupDistributedDataStore(type, moduleShardsConfig, false, shards);
161
162         followerTestKit = new IntegrationTestKit(followerSystem, followerDatastoreContextBuilder);
163         followerDistributedDataStore = followerTestKit.setupDistributedDataStore(type, moduleShardsConfig, false, shards);
164
165         leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorContext(), shards);
166     }
167
168     private static void verifyCars(DOMStoreReadTransaction readTx, MapEntryNode... entries) throws Exception {
169         Optional<NormalizedNode<?, ?>> optional = readTx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
170         assertEquals("isPresent", true, optional.isPresent());
171
172         CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = ImmutableNodes.mapNodeBuilder(CarsModel.CAR_QNAME);
173         for(NormalizedNode<?, ?> entry: entries) {
174             listBuilder.withChild((MapEntryNode) entry);
175         }
176
177         assertEquals("Car list node", listBuilder.build(), optional.get());
178     }
179
180     private static void verifyNode(DOMStoreReadTransaction readTx, YangInstanceIdentifier path, NormalizedNode<?, ?> expNode)
181             throws Exception {
182         Optional<NormalizedNode<?, ?>> optional = readTx.read(path).get(5, TimeUnit.SECONDS);
183         assertEquals("isPresent", true, optional.isPresent());
184         assertEquals("Data node", expNode, optional.get());
185     }
186
187     private static void verifyExists(DOMStoreReadTransaction readTx, YangInstanceIdentifier path) throws Exception {
188         Boolean exists = readTx.exists(path).get(5, TimeUnit.SECONDS);
189         assertEquals("exists", true, exists);
190     }
191
192     @Test
193     public void testWriteTransactionWithSingleShard() throws Exception {
194         String testName = "testWriteTransactionWithSingleShard";
195         initDatastoresWithCars(testName);
196
197         String followerCarShardName = "member-2-shard-cars-" + testName;
198         InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 2, ApplyJournalEntries.class );
199
200         DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
201         assertNotNull("newWriteOnlyTransaction returned null", writeTx);
202
203         writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
204         writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
205
206         MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
207         YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
208         writeTx.merge(car1Path, car1);
209
210         MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
211         YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
212         writeTx.merge(car2Path, car2);
213
214         followerTestKit.doCommit(writeTx.ready());
215
216         verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
217
218         verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
219
220         // Test delete
221
222         writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
223
224         writeTx.delete(car1Path);
225
226         followerTestKit.doCommit(writeTx.ready());
227
228         verifyExists(followerDistributedDataStore.newReadOnlyTransaction(), car2Path);
229
230         verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
231
232         verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car2);
233
234         // Re-instate the follower member 2 as a single-node to verify replication and recovery.
235
236         InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
237
238         JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
239         JavaTestKit.shutdownActorSystem(followerSystem, null, true);
240
241         ActorSystem newSystem = ActorSystem.create("reinstated-member2", ConfigFactory.load().getConfig("Member2"));
242
243         DistributedDataStore member2Datastore = new IntegrationTestKit(newSystem, leaderDatastoreContextBuilder).
244                 setupDistributedDataStore(testName, "module-shards-member2", true, CARS_AND_PEOPLE);
245
246         verifyCars(member2Datastore.newReadOnlyTransaction(), car2);
247
248         JavaTestKit.shutdownActorSystem(newSystem);
249     }
250
251     @Test
252     public void testReadWriteTransactionWithSingleShard() throws Exception {
253         initDatastoresWithCars("testReadWriteTransactionWithSingleShard");
254
255         DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
256         assertNotNull("newReadWriteTransaction returned null", rwTx);
257
258         rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
259         rwTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
260
261         MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
262         rwTx.merge(CarsModel.newCarPath("optima"), car1);
263
264         verifyCars(rwTx, car1);
265
266         MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
267         YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
268         rwTx.merge(car2Path, car2);
269
270         verifyExists(rwTx, car2Path);
271
272         followerTestKit.doCommit(rwTx.ready());
273
274         verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
275     }
276
277     @Test
278     public void testWriteTransactionWithMultipleShards() throws Exception {
279         initDatastoresWithCarsAndPeople("testWriteTransactionWithMultipleShards");
280
281         DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
282         assertNotNull("newWriteOnlyTransaction returned null", writeTx);
283
284         YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
285         NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
286         writeTx.write(carsPath, carsNode);
287
288         YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
289         NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
290         writeTx.write(peoplePath, peopleNode);
291
292         followerTestKit.doCommit(writeTx.ready());
293
294         DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
295
296         verifyNode(readTx, carsPath, carsNode);
297         verifyNode(readTx, peoplePath, peopleNode);
298     }
299
300     @Test
301     public void testReadWriteTransactionWithMultipleShards() throws Exception {
302         initDatastoresWithCarsAndPeople("testReadWriteTransactionWithMultipleShards");
303
304         DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
305         assertNotNull("newReadWriteTransaction returned null", rwTx);
306
307         YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
308         NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
309         rwTx.write(carsPath, carsNode);
310
311         YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
312         NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
313         rwTx.write(peoplePath, peopleNode);
314
315         followerTestKit.doCommit(rwTx.ready());
316
317         DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
318
319         verifyNode(readTx, carsPath, carsNode);
320         verifyNode(readTx, peoplePath, peopleNode);
321     }
322
323     @Test
324     public void testTransactionChainWithSingleShard() throws Exception {
325         initDatastoresWithCars("testTransactionChainWithSingleShard");
326
327         DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
328
329         // Add the top-level cars container with write-only.
330
331         DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
332         assertNotNull("newWriteOnlyTransaction returned null", writeTx);
333
334         writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
335
336         writeTx.ready();
337
338         // Verify the top-level cars container with read-only.
339
340         verifyNode(txChain.newReadOnlyTransaction(), CarsModel.BASE_PATH, CarsModel.emptyContainer());
341
342         // Perform car operations with read-write.
343
344         DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
345
346         verifyNode(rwTx, CarsModel.BASE_PATH, CarsModel.emptyContainer());
347
348         rwTx.merge(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
349
350         MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
351         YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
352         rwTx.write(car1Path, car1);
353
354         verifyExists(rwTx, car1Path);
355
356         verifyCars(rwTx, car1);
357
358         MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
359         rwTx.merge(CarsModel.newCarPath("sportage"), car2);
360
361         rwTx.delete(car1Path);
362
363         followerTestKit.doCommit(rwTx.ready());
364
365         txChain.close();
366
367         verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
368     }
369
370     @Test
371     public void testTransactionChainWithMultipleShards() throws Exception{
372         initDatastoresWithCarsAndPeople("testTransactionChainWithMultipleShards");
373
374         DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
375
376         DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
377         assertNotNull("newWriteOnlyTransaction returned null", writeTx);
378
379         writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
380         writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
381
382         writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
383         writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
384
385         followerTestKit.doCommit(writeTx.ready());
386
387         DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
388
389         MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
390         YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
391         readWriteTx.write(carPath, car);
392
393         MapEntryNode person = PeopleModel.newPersonEntry("jack");
394         YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
395         readWriteTx.merge(personPath, person);
396
397         Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
398         assertEquals("isPresent", true, optional.isPresent());
399         assertEquals("Data node", car, optional.get());
400
401         optional = readWriteTx.read(personPath).get(5, TimeUnit.SECONDS);
402         assertEquals("isPresent", true, optional.isPresent());
403         assertEquals("Data node", person, optional.get());
404
405         DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
406
407         writeTx = txChain.newWriteOnlyTransaction();
408
409         writeTx.delete(personPath);
410
411         DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
412
413         followerTestKit.doCommit(cohort2);
414         followerTestKit.doCommit(cohort3);
415
416         txChain.close();
417
418         DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
419         verifyCars(readTx, car);
420
421         optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
422         assertEquals("isPresent", false, optional.isPresent());
423     }
424
425     @Test
426     public void testChainedTransactionFailureWithSingleShard() throws Exception {
427         initDatastoresWithCars("testChainedTransactionFailureWithSingleShard");
428
429         ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
430                 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
431                         LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
432                         MoreExecutors.directExecutor());
433
434         TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
435         DOMTransactionChain txChain = broker.createTransactionChain(listener);
436
437         DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
438
439         ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
440                 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME)).
441                     withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
442
443         writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
444
445         try {
446             writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
447             fail("Expected TransactionCommitFailedException");
448         } catch (TransactionCommitFailedException e) {
449             // Expected
450         }
451
452         verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
453
454         txChain.close();
455         broker.close();
456     }
457
458     @Test
459     public void testChainedTransactionFailureWithMultipleShards() throws Exception {
460         initDatastoresWithCarsAndPeople("testChainedTransactionFailureWithMultipleShards");
461
462         ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
463                 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
464                         LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
465                         MoreExecutors.directExecutor());
466
467         TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
468         DOMTransactionChain txChain = broker.createTransactionChain(listener);
469
470         DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
471
472         writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
473
474         ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
475                 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME)).
476                     withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
477
478         // Note that merge will validate the data and fail but put succeeds b/c deep validation is not
479         // done for put for performance reasons.
480         writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
481
482         try {
483             writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
484             fail("Expected TransactionCommitFailedException");
485         } catch (TransactionCommitFailedException e) {
486             // Expected
487         }
488
489         verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
490
491         txChain.close();
492         broker.close();
493     }
494
495     @Test
496     public void testSingleShardTransactionsWithLeaderChanges() throws Exception {
497         String testName = "testSingleShardTransactionsWithLeaderChanges";
498         initDatastoresWithCars(testName);
499
500         String followerCarShardName = "member-2-shard-cars-" + testName;
501         InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 1, ApplyJournalEntries.class );
502
503         // Write top-level car container from the follower so it uses a remote Tx.
504
505         DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
506
507         writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
508         writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
509
510         followerTestKit.doCommit(writeTx.ready());
511
512         InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
513
514         // Switch the leader to the follower
515
516         sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder.
517                 shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
518
519         JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
520
521         followerTestKit.waitUntilNoLeader(followerDistributedDataStore.getActorContext(), CARS);
522
523         leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
524         Cluster.get(leaderSystem).join(MEMBER_2_ADDRESS);
525
526         DatastoreContext.Builder newMember1Builder = DatastoreContext.newBuilder().
527                 shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
528         IntegrationTestKit newMember1TestKit = new IntegrationTestKit(leaderSystem, newMember1Builder);
529         newMember1TestKit.setupDistributedDataStore(testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS);
530
531         followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorContext(), CARS);
532
533         // Write a car entry to the new leader - should switch to local Tx
534
535         writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
536
537         MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
538         YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
539         writeTx.merge(car1Path, car1);
540
541         followerTestKit.doCommit(writeTx.ready());
542
543         verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1);
544     }
545
546     @SuppressWarnings("unchecked")
547     @Test
548     public void testReadyLocalTransactionForwardedToLeader() throws Exception {
549         initDatastoresWithCars("testReadyLocalTransactionForwardedToLeader");
550         followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorContext(), "cars");
551
552         Optional<ActorRef> carsFollowerShard = followerDistributedDataStore.getActorContext().findLocalShard("cars");
553         assertEquals("Cars follower shard found", true, carsFollowerShard.isPresent());
554
555         TipProducingDataTree dataTree = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
556         dataTree.setSchemaContext(SchemaContextHelper.full());
557
558         // Send a tx with immediate commit.
559
560         DataTreeModification modification = dataTree.takeSnapshot().newModification();
561         new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
562         new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
563
564         MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
565         new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
566         modification.ready();
567
568         ReadyLocalTransaction readyLocal = new ReadyLocalTransaction("tx-1" , modification, true);
569
570         carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
571         Object resp = followerTestKit.expectMsgClass(Object.class);
572         if(resp instanceof akka.actor.Status.Failure) {
573             throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
574         }
575
576         assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
577
578         verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
579
580         // Send another tx without immediate commit.
581
582         modification = dataTree.takeSnapshot().newModification();
583         MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(30000));
584         new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
585         modification.ready();
586
587         readyLocal = new ReadyLocalTransaction("tx-2" , modification, false);
588
589         carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
590         resp = followerTestKit.expectMsgClass(Object.class);
591         if(resp instanceof akka.actor.Status.Failure) {
592             throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
593         }
594
595         assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
596
597         ActorSelection txActor = leaderDistributedDataStore.getActorContext().actorSelection(
598                 ((ReadyTransactionReply)resp).getCohortPath());
599
600         Supplier<Short> versionSupplier = Mockito.mock(Supplier.class);
601         Mockito.doReturn(DataStoreVersions.CURRENT_VERSION).when(versionSupplier).get();
602         ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(
603                 leaderDistributedDataStore.getActorContext(), Arrays.asList(
604                         new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor), versionSupplier)), "tx-2");
605         cohort.canCommit().get(5, TimeUnit.SECONDS);
606         cohort.preCommit().get(5, TimeUnit.SECONDS);
607         cohort.commit().get(5, TimeUnit.SECONDS);
608
609         verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
610     }
611
612     @SuppressWarnings("unchecked")
613     @Test
614     public void testForwardedReadyTransactionForwardedToLeader() throws Exception {
615         initDatastoresWithCars("testForwardedReadyTransactionForwardedToLeader");
616         followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorContext(), "cars");
617
618         Optional<ActorRef> carsFollowerShard = followerDistributedDataStore.getActorContext().findLocalShard("cars");
619         assertEquals("Cars follower shard found", true, carsFollowerShard.isPresent());
620
621         carsFollowerShard.get().tell(GetShardDataTree.INSTANCE, followerTestKit.getRef());
622         DataTree dataTree = followerTestKit.expectMsgClass(DataTree.class);
623
624         // Send a tx with immediate commit.
625
626         DataTreeModification modification = dataTree.takeSnapshot().newModification();
627         new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
628         new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
629
630         MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
631         new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
632
633         ForwardedReadyTransaction forwardedReady = new ForwardedReadyTransaction("tx-1",
634                 DataStoreVersions.CURRENT_VERSION, new ReadWriteShardDataTreeTransaction(
635                         Mockito.mock(ShardDataTreeTransactionParent.class), "tx-1", modification), true);
636
637         carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
638         Object resp = followerTestKit.expectMsgClass(Object.class);
639         if(resp instanceof akka.actor.Status.Failure) {
640             throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
641         }
642
643         assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
644
645         verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
646
647         // Send another tx without immediate commit.
648
649         modification = dataTree.takeSnapshot().newModification();
650         MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(30000));
651         new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
652
653         forwardedReady = new ForwardedReadyTransaction("tx-2",
654                 DataStoreVersions.CURRENT_VERSION, new ReadWriteShardDataTreeTransaction(
655                         Mockito.mock(ShardDataTreeTransactionParent.class), "tx-2", modification), false);
656
657         carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
658         resp = followerTestKit.expectMsgClass(Object.class);
659         if(resp instanceof akka.actor.Status.Failure) {
660             throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
661         }
662
663         assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
664
665         ActorSelection txActor = leaderDistributedDataStore.getActorContext().actorSelection(
666                 ((ReadyTransactionReply)resp).getCohortPath());
667
668         Supplier<Short> versionSupplier = Mockito.mock(Supplier.class);
669         Mockito.doReturn(DataStoreVersions.CURRENT_VERSION).when(versionSupplier).get();
670         ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(
671                 leaderDistributedDataStore.getActorContext(), Arrays.asList(
672                         new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor), versionSupplier)), "tx-2");
673         cohort.canCommit().get(5, TimeUnit.SECONDS);
674         cohort.preCommit().get(5, TimeUnit.SECONDS);
675         cohort.commit().get(5, TimeUnit.SECONDS);
676
677         verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
678     }
679
680     @Test
681     public void testTransactionForwardedToLeaderAfterRetry() throws Exception {
682         followerDatastoreContextBuilder.shardBatchedModificationCount(2);
683         leaderDatastoreContextBuilder.shardBatchedModificationCount(2);
684         initDatastoresWithCarsAndPeople("testTransactionForwardedToLeaderAfterRetry");
685
686         // Do an initial write to get the primary shard info cached.
687
688         DOMStoreWriteTransaction initialWriteTx = followerDistributedDataStore.newWriteOnlyTransaction();
689         initialWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
690         initialWriteTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
691         followerTestKit.doCommit(initialWriteTx.ready());
692
693         // Wait for the commit to be replicated to the follower.
694
695         MemberNode.verifyRaftState(followerDistributedDataStore, "cars", new RaftStateVerifier() {
696             @Override
697             public void verify(OnDemandRaftState raftState) {
698                 assertEquals("getLastApplied", 0, raftState.getLastApplied());
699             }
700         });
701
702         // Prepare, ready and canCommit a WO tx that writes to 2 shards. This will become the current tx in
703         // the leader shard.
704
705         DOMStoreWriteTransaction writeTx1 = followerDistributedDataStore.newWriteOnlyTransaction();
706         writeTx1.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
707         writeTx1.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
708         DOMStoreThreePhaseCommitCohort writeTx1Cohort = writeTx1.ready();
709         ListenableFuture<Boolean> writeTx1CanCommit = writeTx1Cohort.canCommit();
710         writeTx1CanCommit.get(5, TimeUnit.SECONDS);
711
712         // Prepare and ready another WO tx that writes to 2 shards but don't canCommit yet. This will be queued
713         // in the leader shard.
714
715         DOMStoreWriteTransaction writeTx2 = followerDistributedDataStore.newWriteOnlyTransaction();
716         LinkedList<MapEntryNode> cars = new LinkedList<>();
717         int carIndex = 1;
718         cars.add(CarsModel.newCarEntry("car" + carIndex, BigInteger.valueOf(carIndex)));
719         writeTx2.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
720         carIndex++;
721         NormalizedNode<?, ?> people = PeopleModel.newPersonMapNode();
722         writeTx2.write(PeopleModel.PERSON_LIST_PATH, people);
723         DOMStoreThreePhaseCommitCohort writeTx2Cohort = writeTx2.ready();
724
725         // Prepare another WO that writes to a single shard and thus will be directly committed on ready. This
726         // tx writes 5 cars so 2 BatchedModidifications messages will be sent initially and cached in the
727         // leader shard (with shardBatchedModificationCount set to 2). The 3rd BatchedModidifications will be
728         // sent on ready.
729
730         DOMStoreWriteTransaction writeTx3 = followerDistributedDataStore.newWriteOnlyTransaction();
731         for(int i = 1; i <= 5; i++, carIndex++) {
732             cars.add(CarsModel.newCarEntry("car" + carIndex, BigInteger.valueOf(carIndex)));
733             writeTx3.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
734         }
735
736         // Prepare another WO that writes to a single shard. This will send a single BatchedModidifications
737         // message on ready.
738
739         DOMStoreWriteTransaction writeTx4 = followerDistributedDataStore.newWriteOnlyTransaction();
740         cars.add(CarsModel.newCarEntry("car" + carIndex, BigInteger.valueOf(carIndex)));
741         writeTx4.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
742         carIndex++;
743
744         // Prepare a RW tx that will create a tx actor and send a ForwardedReadyTransaciton message to the
745         // leader shard on ready.
746
747         DOMStoreReadWriteTransaction readWriteTx = followerDistributedDataStore.newReadWriteTransaction();
748         cars.add(CarsModel.newCarEntry("car" + carIndex, BigInteger.valueOf(carIndex)));
749         readWriteTx.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
750
751         IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars", new ShardStatsVerifier() {
752             @Override
753             public void verify(ShardStats stats) {
754                 assertEquals("getReadWriteTransactionCount", 1, stats.getReadWriteTransactionCount());
755             }
756         });
757
758         // Disable elections on the leader so it switches to follower.
759
760         sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder.
761                 customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).
762                 shardElectionTimeoutFactor(10));
763
764         leaderTestKit.waitUntilNoLeader(leaderDistributedDataStore.getActorContext(), "cars");
765
766         // Submit all tx's - the messages should get queued for retry.
767
768         ListenableFuture<Boolean> writeTx2CanCommit = writeTx2Cohort.canCommit();
769         DOMStoreThreePhaseCommitCohort writeTx3Cohort = writeTx3.ready();
770         DOMStoreThreePhaseCommitCohort writeTx4Cohort = writeTx4.ready();
771         DOMStoreThreePhaseCommitCohort rwTxCohort = readWriteTx.ready();
772
773         // Enable elections on the other follower so it becomes the leader, at which point the
774         // tx's should get forwarded from the previous leader to the new leader to complete the commits.
775
776         sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder.
777                 customRaftPolicyImplementation(null).shardElectionTimeoutFactor(1));
778
779         followerTestKit.doCommit(writeTx1CanCommit, writeTx1Cohort);
780         followerTestKit.doCommit(writeTx2CanCommit, writeTx2Cohort);
781         followerTestKit.doCommit(writeTx3Cohort);
782         followerTestKit.doCommit(writeTx4Cohort);
783         followerTestKit.doCommit(rwTxCohort);
784
785         DOMStoreReadTransaction readTx = leaderDistributedDataStore.newReadOnlyTransaction();
786         verifyCars(readTx, cars.toArray(new MapEntryNode[cars.size()]));
787         verifyNode(readTx, PeopleModel.PERSON_LIST_PATH, people);
788     }
789
790     @Test
791     public void testLeadershipTransferOnShutdown() throws Exception {
792         leaderDatastoreContextBuilder.shardBatchedModificationCount(1);
793         followerDatastoreContextBuilder.shardElectionTimeoutFactor(10).customRaftPolicyImplementation(null);
794         String testName = "testLeadershipTransferOnShutdown";
795         initDatastores(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, CARS_AND_PEOPLE);
796
797         IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System, followerDatastoreContextBuilder);
798         DistributedDataStore follower2DistributedDataStore = follower2TestKit.setupDistributedDataStore(testName,
799                 MODULE_SHARDS_CARS_PEOPLE_1_2_3, false);
800
801         // Create and submit a couple tx's so they're pending.
802
803         DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
804         writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
805         writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
806         writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
807         DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
808
809         IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars", new ShardStatsVerifier() {
810             @Override
811             public void verify(ShardStats stats) {
812                 assertEquals("getTxCohortCacheSize", 1, stats.getTxCohortCacheSize());
813             }
814         });
815
816         writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
817         MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
818         writeTx.write(CarsModel.newCarPath("optima"), car);
819         DOMStoreThreePhaseCommitCohort cohort2 = writeTx.ready();
820
821         IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars", new ShardStatsVerifier() {
822             @Override
823             public void verify(ShardStats stats) {
824                 assertEquals("getTxCohortCacheSize", 2, stats.getTxCohortCacheSize());
825             }
826         });
827
828         // Gracefully stop the leader via a Shutdown message.
829
830         sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder.
831                 shardElectionTimeoutFactor(100));
832
833         FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
834         Future<ActorRef> future = leaderDistributedDataStore.getActorContext().findLocalShardAsync("cars");
835         ActorRef leaderActor = Await.result(future, duration);
836
837         Future<Boolean> stopFuture = Patterns.gracefulStop(leaderActor, duration, Shutdown.INSTANCE);
838
839         // Commit the 2 transactions. They should finish and succeed.
840
841         followerTestKit.doCommit(cohort1);
842         followerTestKit.doCommit(cohort2);
843
844         // Wait for the leader actor stopped.
845
846         Boolean stopped = Await.result(stopFuture, duration);
847         assertEquals("Stopped", Boolean.TRUE, stopped);
848
849         // Verify leadership was transferred by reading the committed data from the other nodes.
850
851         verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car);
852         verifyCars(follower2DistributedDataStore.newReadOnlyTransaction(), car);
853     }
854
855     @Test
856     public void testTransactionWithIsolatedLeader() throws Throwable {
857         leaderDatastoreContextBuilder.shardIsolatedLeaderCheckIntervalInMillis(200);
858         String testName = "testTransactionWithIsolatedLeader";
859         initDatastoresWithCars(testName);
860
861         DOMStoreWriteTransaction failWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
862         failWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
863
864         DOMStoreWriteTransaction successWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
865         successWriteTx.merge(CarsModel.BASE_PATH, CarsModel.emptyContainer());
866
867         followerTestKit.watch(followerDistributedDataStore.getActorContext().getShardManager());
868         followerDistributedDataStore.close();
869         followerTestKit.expectTerminated(followerDistributedDataStore.getActorContext().getShardManager());
870
871         MemberNode.verifyRaftState(leaderDistributedDataStore, "cars", new RaftStateVerifier() {
872             @Override
873             public void verify(OnDemandRaftState raftState) {
874                 assertEquals("getRaftState", "IsolatedLeader", raftState.getRaftState());
875             }
876         });
877
878         try {
879             leaderTestKit.doCommit(failWriteTx.ready());
880             fail("Expected NoShardLeaderException");
881         } catch (ExecutionException e) {
882             assertEquals("getCause", NoShardLeaderException.class, e.getCause().getClass());
883         }
884
885         sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder.
886                 shardElectionTimeoutFactor(100));
887
888         DOMStoreThreePhaseCommitCohort writeTxCohort = successWriteTx.ready();
889
890         followerDistributedDataStore = followerTestKit.setupDistributedDataStore(testName,
891                 MODULE_SHARDS_CARS_ONLY_1_2, false, CARS);
892
893         leaderTestKit.doCommit(writeTxCohort);
894     }
895
896     @Test(expected=AskTimeoutException.class)
897     public void testTransactionWithShardLeaderNotResponding() throws Throwable {
898         initDatastoresWithCars("testTransactionWithShardLeaderNotResponding");
899
900         // Do an initial read to get the primary shard info cached.
901
902         DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
903         readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
904
905         // Shutdown the leader and try to create a new tx.
906
907         JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
908
909         followerDatastoreContextBuilder.operationTimeoutInMillis(50).shardElectionTimeoutFactor(1);
910         sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder);
911
912         DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
913
914         rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
915
916         try {
917             followerTestKit.doCommit(rwTx.ready());
918         } catch (ExecutionException e) {
919             assertTrue("Expected ShardLeaderNotRespondingException cause. Actual: " + e.getCause(),
920                     e.getCause() instanceof ShardLeaderNotRespondingException);
921             assertNotNull("Expected a nested cause", e.getCause().getCause());
922             throw e.getCause().getCause();
923         }
924     }
925
926     @Test(expected=NoShardLeaderException.class)
927     public void testTransactionWithCreateTxFailureDueToNoLeader() throws Throwable {
928         initDatastoresWithCars("testTransactionWithCreateTxFailureDueToNoLeader");
929
930         // Do an initial read to get the primary shard info cached.
931
932         DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
933         readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
934
935         // Shutdown the leader and try to create a new tx.
936
937         JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
938
939         Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
940
941         sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder.
942                 operationTimeoutInMillis(10).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
943
944         DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
945
946         rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
947
948         try {
949             followerTestKit.doCommit(rwTx.ready());
950         } catch (ExecutionException e) {
951             throw e.getCause();
952         }
953     }
954
955     @Test
956     public void testTransactionRetryWithInitialAskTimeoutExOnCreateTx() throws Exception {
957         String testName = "testTransactionRetryWithInitialAskTimeoutExOnCreateTx";
958         initDatastores(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, CARS);
959
960         DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder().
961                 shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
962         IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System, follower2DatastoreContextBuilder);
963         follower2TestKit.setupDistributedDataStore(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, false, CARS);
964
965         followerTestKit.waitForMembersUp("member-1", "member-3");
966         follower2TestKit.waitForMembersUp("member-1", "member-2");
967
968         // Do an initial read to get the primary shard info cached.
969
970         DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
971         readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
972
973         // Shutdown the leader and try to create a new tx.
974
975         JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
976
977         sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder.
978                 operationTimeoutInMillis(500).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
979
980         DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
981
982         rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
983
984         followerTestKit.doCommit(rwTx.ready());
985     }
986
987     private static void sendDatastoreContextUpdate(DistributedDataStore dataStore, final Builder builder) {
988         final Builder newBuilder = DatastoreContext.newBuilderFrom(builder.build());
989         DatastoreContextFactory mockContextFactory = Mockito.mock(DatastoreContextFactory.class);
990         Answer<DatastoreContext> answer = new Answer<DatastoreContext>() {
991             @Override
992             public DatastoreContext answer(InvocationOnMock invocation) {
993                 return newBuilder.build();
994             }
995         };
996         Mockito.doAnswer(answer).when(mockContextFactory).getBaseDatastoreContext();
997         Mockito.doAnswer(answer).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
998         dataStore.onDatastoreContextUpdated(mockContextFactory);
999     }
1000 }