CDS: Retry remote front-end transactions on AskTimeoutException
[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.ActorSystem;
20 import akka.actor.Address;
21 import akka.actor.AddressFromURIString;
22 import akka.cluster.Cluster;
23 import akka.pattern.AskTimeoutException;
24 import akka.testkit.JavaTestKit;
25 import com.google.common.base.Optional;
26 import com.google.common.collect.ImmutableMap;
27 import com.google.common.util.concurrent.MoreExecutors;
28 import com.google.common.util.concurrent.Uninterruptibles;
29 import com.typesafe.config.ConfigFactory;
30 import java.math.BigInteger;
31 import java.util.concurrent.ExecutionException;
32 import java.util.concurrent.TimeUnit;
33 import org.junit.After;
34 import org.junit.Before;
35 import org.junit.Test;
36 import org.mockito.Mockito;
37 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
38 import org.opendaylight.controller.cluster.datastore.exceptions.ShardLeaderNotRespondingException;
39 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
40 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
41 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
42 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
43 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
44 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
45 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
46 import org.opendaylight.controller.md.cluster.datastore.model.PeopleModel;
47 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
48 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
49 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
50 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
51 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
52 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
53 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
54 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
55 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
56 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
57 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
58 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
59 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
61 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
62 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
63 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
64 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
66 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
67 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
68 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
69 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
70 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
71
72 /**
73  * End-to-end distributed data store tests that exercise remote shards and transactions.
74  *
75  * @author Thomas Pantelis
76  */
77 public class DistributedDataStoreRemotingIntegrationTest {
78
79     private static final String[] SHARD_NAMES = {"cars", "people"};
80
81     private static final Address MEMBER_1_ADDRESS = AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2558");
82     private static final Address MEMBER_2_ADDRESS = AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2559");
83
84     private static final String MODULE_SHARDS_CONFIG_2 = "module-shards-member1-and-2.conf";
85     private static final String MODULE_SHARDS_CONFIG_3 = "module-shards-member1-and-2-and-3.conf";
86
87     private ActorSystem leaderSystem;
88     private ActorSystem followerSystem;
89     private ActorSystem follower2System;
90
91     private final DatastoreContext.Builder leaderDatastoreContextBuilder =
92             DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(1);
93
94     private final DatastoreContext.Builder followerDatastoreContextBuilder =
95             DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
96
97     private DistributedDataStore followerDistributedDataStore;
98     private DistributedDataStore leaderDistributedDataStore;
99     private IntegrationTestKit followerTestKit;
100     private IntegrationTestKit leaderTestKit;
101
102     @Before
103     public void setUp() {
104         leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
105         Cluster.get(leaderSystem).join(MEMBER_1_ADDRESS);
106
107         followerSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member2"));
108         Cluster.get(followerSystem).join(MEMBER_1_ADDRESS);
109
110         follower2System = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member3"));
111         Cluster.get(follower2System).join(MEMBER_1_ADDRESS);
112     }
113
114     @After
115     public void tearDown() {
116         JavaTestKit.shutdownActorSystem(leaderSystem);
117         JavaTestKit.shutdownActorSystem(followerSystem);
118         JavaTestKit.shutdownActorSystem(follower2System);
119     }
120
121     private void initDatastores(String type) {
122         initDatastores(type, MODULE_SHARDS_CONFIG_2);
123     }
124
125     private void initDatastores(String type, String moduleShardsConfig) {
126         leaderTestKit = new IntegrationTestKit(leaderSystem, leaderDatastoreContextBuilder);
127
128         leaderDistributedDataStore = leaderTestKit.setupDistributedDataStore(type, moduleShardsConfig, false, SHARD_NAMES);
129
130         followerTestKit = new IntegrationTestKit(followerSystem, followerDatastoreContextBuilder);
131         followerDistributedDataStore = followerTestKit.setupDistributedDataStore(type, moduleShardsConfig, false, SHARD_NAMES);
132
133         leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorContext(), SHARD_NAMES);
134     }
135
136     private void verifyCars(DOMStoreReadTransaction readTx, MapEntryNode... entries) throws Exception {
137         Optional<NormalizedNode<?, ?>> optional = readTx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
138         assertEquals("isPresent", true, optional.isPresent());
139
140         CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = ImmutableNodes.mapNodeBuilder(CarsModel.CAR_QNAME);
141         for(NormalizedNode<?, ?> entry: entries) {
142             listBuilder.withChild((MapEntryNode) entry);
143         }
144
145         assertEquals("Car list node", listBuilder.build(), optional.get());
146     }
147
148     private void verifyNode(DOMStoreReadTransaction readTx, YangInstanceIdentifier path, NormalizedNode<?, ?> expNode)
149             throws Exception {
150         Optional<NormalizedNode<?, ?>> optional = readTx.read(path).get(5, TimeUnit.SECONDS);
151         assertEquals("isPresent", true, optional.isPresent());
152         assertEquals("Data node", expNode, optional.get());
153     }
154
155     private void verifyExists(DOMStoreReadTransaction readTx, YangInstanceIdentifier path) throws Exception {
156         Boolean exists = readTx.exists(path).get(5, TimeUnit.SECONDS);
157         assertEquals("exists", true, exists);
158     }
159
160     @Test
161     public void testWriteTransactionWithSingleShard() throws Exception {
162         String testName = "testWriteTransactionWithSingleShard";
163         initDatastores(testName);
164
165         String followerCarShardName = "member-2-shard-cars-" + testName;
166         InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 2, ApplyJournalEntries.class );
167
168         DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
169         assertNotNull("newWriteOnlyTransaction returned null", writeTx);
170
171         writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
172         writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
173
174         MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
175         YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
176         writeTx.merge(car1Path, car1);
177
178         MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
179         YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
180         writeTx.merge(car2Path, car2);
181
182         followerTestKit.doCommit(writeTx.ready());
183
184         verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
185
186         verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
187
188         // Test delete
189
190         writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
191
192         writeTx.delete(car1Path);
193
194         followerTestKit.doCommit(writeTx.ready());
195
196         verifyExists(followerDistributedDataStore.newReadOnlyTransaction(), car2Path);
197
198         verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
199
200         verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car2);
201
202         // Re-instate the follower member 2 as a single-node to verify replication and recovery.
203
204         InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
205
206         JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
207         JavaTestKit.shutdownActorSystem(followerSystem, null, true);
208
209         ActorSystem newSystem = ActorSystem.create("reinstated-member2", ConfigFactory.load().getConfig("Member2"));
210
211         DistributedDataStore member2Datastore = new IntegrationTestKit(newSystem, leaderDatastoreContextBuilder).
212                 setupDistributedDataStore(testName, "module-shards-member2", true, SHARD_NAMES);
213
214         verifyCars(member2Datastore.newReadOnlyTransaction(), car2);
215
216         JavaTestKit.shutdownActorSystem(newSystem);
217     }
218
219     @Test
220     public void testReadWriteTransactionWithSingleShard() throws Exception {
221         initDatastores("testReadWriteTransactionWithSingleShard");
222
223         DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
224         assertNotNull("newReadWriteTransaction returned null", rwTx);
225
226         rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
227         rwTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
228
229         MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
230         rwTx.merge(CarsModel.newCarPath("optima"), car1);
231
232         verifyCars(rwTx, car1);
233
234         MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
235         YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
236         rwTx.merge(car2Path, car2);
237
238         verifyExists(rwTx, car2Path);
239
240         followerTestKit.doCommit(rwTx.ready());
241
242         verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
243     }
244
245     @Test
246     public void testWriteTransactionWithMultipleShards() throws Exception {
247         initDatastores("testWriteTransactionWithMultipleShards");
248
249         DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
250         assertNotNull("newWriteOnlyTransaction returned null", writeTx);
251
252         YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
253         NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
254         writeTx.write(carsPath, carsNode);
255
256         YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
257         NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
258         writeTx.write(peoplePath, peopleNode);
259
260         followerTestKit.doCommit(writeTx.ready());
261
262         DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
263
264         verifyNode(readTx, carsPath, carsNode);
265         verifyNode(readTx, peoplePath, peopleNode);
266     }
267
268     @Test
269     public void testReadWriteTransactionWithMultipleShards() throws Exception {
270         initDatastores("testReadWriteTransactionWithMultipleShards");
271
272         DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
273         assertNotNull("newReadWriteTransaction returned null", rwTx);
274
275         YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
276         NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
277         rwTx.write(carsPath, carsNode);
278
279         YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
280         NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
281         rwTx.write(peoplePath, peopleNode);
282
283         followerTestKit.doCommit(rwTx.ready());
284
285         DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
286
287         verifyNode(readTx, carsPath, carsNode);
288         verifyNode(readTx, peoplePath, peopleNode);
289     }
290
291     @Test
292     public void testTransactionChainWithSingleShard() throws Exception {
293         initDatastores("testTransactionChainWithSingleShard");
294
295         DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
296
297         // Add the top-level cars container with write-only.
298
299         DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
300         assertNotNull("newWriteOnlyTransaction returned null", writeTx);
301
302         writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
303
304         writeTx.ready();
305
306         // Verify the top-level cars container with read-only.
307
308         verifyNode(txChain.newReadOnlyTransaction(), CarsModel.BASE_PATH, CarsModel.emptyContainer());
309
310         // Perform car operations with read-write.
311
312         DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
313
314         verifyNode(rwTx, CarsModel.BASE_PATH, CarsModel.emptyContainer());
315
316         rwTx.merge(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
317
318         MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
319         YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
320         rwTx.write(car1Path, car1);
321
322         verifyExists(rwTx, car1Path);
323
324         verifyCars(rwTx, car1);
325
326         MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
327         rwTx.merge(CarsModel.newCarPath("sportage"), car2);
328
329         rwTx.delete(car1Path);
330
331         followerTestKit.doCommit(rwTx.ready());
332
333         txChain.close();
334
335         verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
336     }
337
338     @Test
339     public void testTransactionChainWithMultipleShards() throws Exception{
340         initDatastores("testTransactionChainWithMultipleShards");
341
342         DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
343
344         DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
345         assertNotNull("newWriteOnlyTransaction returned null", writeTx);
346
347         writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
348         writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
349
350         writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
351         writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
352
353         followerTestKit.doCommit(writeTx.ready());
354
355         DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
356
357         MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
358         YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
359         readWriteTx.write(carPath, car);
360
361         MapEntryNode person = PeopleModel.newPersonEntry("jack");
362         YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
363         readWriteTx.merge(personPath, person);
364
365         Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
366         assertEquals("isPresent", true, optional.isPresent());
367         assertEquals("Data node", car, optional.get());
368
369         optional = readWriteTx.read(personPath).get(5, TimeUnit.SECONDS);
370         assertEquals("isPresent", true, optional.isPresent());
371         assertEquals("Data node", person, optional.get());
372
373         DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
374
375         writeTx = txChain.newWriteOnlyTransaction();
376
377         writeTx.delete(personPath);
378
379         DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
380
381         followerTestKit.doCommit(cohort2);
382         followerTestKit.doCommit(cohort3);
383
384         txChain.close();
385
386         DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
387         verifyCars(readTx, car);
388
389         optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
390         assertEquals("isPresent", false, optional.isPresent());
391     }
392
393     @Test
394     public void testChainedTransactionFailureWithSingleShard() throws Exception {
395         initDatastores("testChainedTransactionFailureWithSingleShard");
396
397         ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
398                 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
399                         LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
400                         MoreExecutors.directExecutor());
401
402         TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
403         DOMTransactionChain txChain = broker.createTransactionChain(listener);
404
405         DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
406
407         ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
408                 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME)).
409                     withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
410
411         writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
412
413         try {
414             writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
415             fail("Expected TransactionCommitFailedException");
416         } catch (TransactionCommitFailedException e) {
417             // Expected
418         }
419
420         verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
421
422         txChain.close();
423         broker.close();
424     }
425
426     @Test
427     public void testChainedTransactionFailureWithMultipleShards() throws Exception {
428         initDatastores("testChainedTransactionFailureWithMultipleShards");
429
430         ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
431                 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
432                         LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
433                         MoreExecutors.directExecutor());
434
435         TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
436         DOMTransactionChain txChain = broker.createTransactionChain(listener);
437
438         DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
439
440         writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
441
442         ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
443                 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME)).
444                     withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
445
446         // Note that merge will validate the data and fail but put succeeds b/c deep validation is not
447         // done for put for performance reasons.
448         writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
449
450         try {
451             writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
452             fail("Expected TransactionCommitFailedException");
453         } catch (TransactionCommitFailedException e) {
454             // Expected
455         }
456
457         verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
458
459         txChain.close();
460         broker.close();
461     }
462
463     @Test
464     public void testSingleShardTransactionsWithLeaderChanges() throws Exception {
465         String testName = "testSingleShardTransactionsWithLeaderChanges";
466         initDatastores(testName);
467
468         String followerCarShardName = "member-2-shard-cars-" + testName;
469         InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 1, ApplyJournalEntries.class );
470
471         // Write top-level car container from the follower so it uses a remote Tx.
472
473         DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
474
475         writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
476         writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
477
478         followerTestKit.doCommit(writeTx.ready());
479
480         InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
481
482         // Switch the leader to the follower
483
484         followerDatastoreContextBuilder.shardElectionTimeoutFactor(1);
485         followerDistributedDataStore.onDatastoreContextUpdated(followerDatastoreContextBuilder.build());
486
487         JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
488
489         followerTestKit.waitUntilNoLeader(followerDistributedDataStore.getActorContext(), SHARD_NAMES);
490
491         leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
492         Cluster.get(leaderSystem).join(MEMBER_2_ADDRESS);
493
494         DatastoreContext.Builder newMember1Builder = DatastoreContext.newBuilder().
495                 shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
496         IntegrationTestKit newMember1TestKit = new IntegrationTestKit(leaderSystem, newMember1Builder);
497         newMember1TestKit.setupDistributedDataStore(testName, MODULE_SHARDS_CONFIG_2, false, SHARD_NAMES);
498
499         followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorContext(), SHARD_NAMES);
500
501         // Write a car entry to the new leader - should switch to local Tx
502
503         writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
504
505         MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
506         YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
507         writeTx.merge(car1Path, car1);
508
509         followerTestKit.doCommit(writeTx.ready());
510
511         verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1);
512     }
513
514     @Test
515     public void testReadyLocalTransactionForwardedToLeader() throws Exception {
516         initDatastores("testReadyLocalTransactionForwardedToLeader");
517
518         Optional<ActorRef> carsFollowerShard = followerDistributedDataStore.getActorContext().findLocalShard("cars");
519         assertEquals("Cars follower shard found", true, carsFollowerShard.isPresent());
520
521         TipProducingDataTree dataTree = InMemoryDataTreeFactory.getInstance().create();
522         dataTree.setSchemaContext(SchemaContextHelper.full());
523         DataTreeModification modification = dataTree.takeSnapshot().newModification();
524
525         new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
526         new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
527
528         MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
529         new WriteModification(CarsModel.newCarPath("optima"), car).apply(modification);
530
531         String transactionID = "tx-1";
532         ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(transactionID , modification, true);
533
534         carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
535         followerTestKit.expectMsgClass(CommitTransactionReply.SERIALIZABLE_CLASS);
536
537         verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car);
538     }
539
540     @Test(expected=NoShardLeaderException.class)
541     public void testTransactionWithIsolatedLeader() throws Throwable {
542         leaderDatastoreContextBuilder.shardIsolatedLeaderCheckIntervalInMillis(300);
543         String testName = "testTransactionWithIsolatedLeader";
544         initDatastores(testName);
545
546         JavaTestKit.shutdownActorSystem(followerSystem, null, true);
547
548         Uninterruptibles.sleepUninterruptibly(leaderDistributedDataStore.getActorContext().getDatastoreContext()
549                 .getShardRaftConfig().getElectionTimeOutInterval().toMillis() * 3, TimeUnit.MILLISECONDS);
550
551         DOMStoreWriteTransaction writeTx = leaderDistributedDataStore.newWriteOnlyTransaction();
552         writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
553
554         try {
555             followerTestKit.doCommit(writeTx.ready());
556         } catch (ExecutionException e) {
557             throw e.getCause();
558         }
559     }
560
561     @Test(expected=AskTimeoutException.class)
562     public void testTransactionWithShardLeaderNotResponding() throws Throwable {
563         followerDatastoreContextBuilder.shardElectionTimeoutFactor(30);
564         initDatastores("testTransactionWithShardLeaderNotResponding");
565
566         // Do an initial read to get the primary shard info cached.
567
568         DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
569         readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
570
571         // Shutdown the leader and try to create a new tx.
572
573         JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
574
575         followerDatastoreContextBuilder.operationTimeoutInMillis(50).shardElectionTimeoutFactor(1);
576         followerDistributedDataStore.onDatastoreContextUpdated(followerDatastoreContextBuilder.build());
577
578         DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
579
580         rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
581
582         try {
583             followerTestKit.doCommit(rwTx.ready());
584         } catch (ExecutionException e) {
585             assertTrue("Expected ShardLeaderNotRespondingException cause. Actual: " + e.getCause(),
586                     e.getCause() instanceof ShardLeaderNotRespondingException);
587             assertNotNull("Expected a nested cause", e.getCause().getCause());
588             throw e.getCause().getCause();
589         }
590     }
591
592     @Test(expected=NoShardLeaderException.class)
593     public void testTransactionWithCreateTxFailureDueToNoLeader() throws Throwable {
594         initDatastores("testTransactionWithCreateTxFailureDueToNoLeader");
595
596         // Do an initial read to get the primary shard info cached.
597
598         DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
599         readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
600
601         // Shutdown the leader and try to create a new tx.
602
603         JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
604
605         Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
606
607         followerDatastoreContextBuilder.operationTimeoutInMillis(10).shardElectionTimeoutFactor(1);
608         followerDistributedDataStore.onDatastoreContextUpdated(followerDatastoreContextBuilder.build());
609
610         DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
611
612         rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
613
614         try {
615             followerTestKit.doCommit(rwTx.ready());
616         } catch (ExecutionException e) {
617             throw e.getCause();
618         }
619     }
620
621     @Test
622     public void testTransactionRetryWithInitialAskTimeoutExOnCreateTx() throws Exception {
623         followerDatastoreContextBuilder.shardElectionTimeoutFactor(30);
624         String testName = "testTransactionRetryWithInitialAskTimeoutExOnCreateTx";
625         initDatastores(testName, MODULE_SHARDS_CONFIG_3);
626
627         DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder().
628                 shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
629         IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System, follower2DatastoreContextBuilder);
630         follower2TestKit.setupDistributedDataStore(testName, MODULE_SHARDS_CONFIG_3, false, SHARD_NAMES);
631
632         // Do an initial read to get the primary shard info cached.
633
634         DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
635         readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
636
637         // Shutdown the leader and try to create a new tx.
638
639         JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
640
641         followerDatastoreContextBuilder.operationTimeoutInMillis(500);
642         followerDistributedDataStore.onDatastoreContextUpdated(followerDatastoreContextBuilder.build());
643
644         DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
645
646         rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
647
648         followerTestKit.doCommit(rwTx.ready());
649     }
650 }