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