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