BUG-5280: switch tests to 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.AskTimeoutException;
27 import akka.pattern.Patterns;
28 import akka.testkit.JavaTestKit;
29 import com.google.common.base.Optional;
30 import com.google.common.base.Supplier;
31 import com.google.common.base.Throwables;
32 import com.google.common.collect.ImmutableMap;
33 import com.google.common.util.concurrent.ListenableFuture;
34 import com.google.common.util.concurrent.MoreExecutors;
35 import com.google.common.util.concurrent.Uninterruptibles;
36 import com.typesafe.config.ConfigFactory;
37 import java.math.BigInteger;
38 import java.util.Arrays;
39 import java.util.Collection;
40 import java.util.Collections;
41 import java.util.LinkedList;
42 import java.util.concurrent.ExecutionException;
43 import java.util.concurrent.TimeUnit;
44 import org.junit.After;
45 import org.junit.Assume;
46 import org.junit.Before;
47 import org.junit.Test;
48 import org.junit.runner.RunWith;
49 import org.junit.runners.Parameterized;
50 import org.junit.runners.Parameterized.Parameter;
51 import org.junit.runners.Parameterized.Parameters;
52 import org.mockito.Mockito;
53 import org.mockito.stubbing.Answer;
54 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
55 import org.opendaylight.controller.cluster.databroker.ClientBackedDataStore;
56 import org.opendaylight.controller.cluster.databroker.ConcurrentDOMDataBroker;
57 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
58 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
59 import org.opendaylight.controller.cluster.datastore.exceptions.ShardLeaderNotRespondingException;
60 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
61 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
62 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
63 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
64 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
65 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
66 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
67 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
68 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
69 import org.opendaylight.controller.cluster.raft.client.messages.Shutdown;
70 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
71 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
72 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
73 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
74 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
75 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
76 import org.opendaylight.controller.md.cluster.datastore.model.PeopleModel;
77 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
78 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
79 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
80 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
81 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
82 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
83 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
84 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
85 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
86 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
87 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
88 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
89 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
90 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
91 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
92 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
93 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
94 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
95 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
96 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
97 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
98 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
99 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
100 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
101 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
102 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
103 import scala.concurrent.Await;
104 import scala.concurrent.Future;
105 import scala.concurrent.duration.FiniteDuration;
106
107 /**
108  * End-to-end distributed data store tests that exercise remote shards and transactions.
109  *
110  * @author Thomas Pantelis
111  */
112 @RunWith(Parameterized.class)
113 public class DistributedDataStoreRemotingIntegrationTest extends AbstractTest {
114
115     @Parameters(name = "{0}")
116     public static Collection<Object[]> data() {
117         return Arrays.asList(new Object[][] {
118                 { DistributedDataStore.class }, { ClientBackedDataStore.class }
119         });
120     }
121
122     @Parameter
123     public Class<? extends AbstractDataStore> testParameter;
124
125     private static final String[] CARS_AND_PEOPLE = {"cars", "people"};
126     private static final String[] CARS = {"cars"};
127
128     private static final Address MEMBER_1_ADDRESS = AddressFromURIString.parse(
129             "akka://cluster-test@127.0.0.1:2558");
130     private static final Address MEMBER_2_ADDRESS = AddressFromURIString.parse(
131             "akka://cluster-test@127.0.0.1:2559");
132
133     private static final String MODULE_SHARDS_CARS_ONLY_1_2 = "module-shards-cars-member-1-and-2.conf";
134     private static final String MODULE_SHARDS_CARS_PEOPLE_1_2 = "module-shards-member1-and-2.conf";
135     private static final String MODULE_SHARDS_CARS_PEOPLE_1_2_3 = "module-shards-member1-and-2-and-3.conf";
136
137     private ActorSystem leaderSystem;
138     private ActorSystem followerSystem;
139     private ActorSystem follower2System;
140
141     private final DatastoreContext.Builder leaderDatastoreContextBuilder =
142             DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2);
143
144     private final DatastoreContext.Builder followerDatastoreContextBuilder =
145             DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5)
146                 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
147     private final TransactionIdentifier tx1 = nextTransactionId();
148     private final TransactionIdentifier tx2 = nextTransactionId();
149
150     private AbstractDataStore followerDistributedDataStore;
151     private AbstractDataStore leaderDistributedDataStore;
152     private IntegrationTestKit followerTestKit;
153     private IntegrationTestKit leaderTestKit;
154
155     @Before
156     public void setUp() {
157         InMemoryJournal.clear();
158         InMemorySnapshotStore.clear();
159
160         leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
161         Cluster.get(leaderSystem).join(MEMBER_1_ADDRESS);
162
163         followerSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member2"));
164         Cluster.get(followerSystem).join(MEMBER_1_ADDRESS);
165
166         follower2System = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member3"));
167         Cluster.get(follower2System).join(MEMBER_1_ADDRESS);
168     }
169
170     @After
171     public void tearDown() {
172         if (followerDistributedDataStore != null) {
173             leaderDistributedDataStore.close();
174         }
175         if (leaderDistributedDataStore != null) {
176             leaderDistributedDataStore.close();
177         }
178
179         JavaTestKit.shutdownActorSystem(leaderSystem);
180         JavaTestKit.shutdownActorSystem(followerSystem);
181         JavaTestKit.shutdownActorSystem(follower2System);
182
183         InMemoryJournal.clear();
184         InMemorySnapshotStore.clear();
185     }
186
187     private void initDatastoresWithCars(final String type) throws Exception {
188         initDatastores(type, MODULE_SHARDS_CARS_ONLY_1_2, CARS);
189     }
190
191     private void initDatastoresWithCarsAndPeople(final String type) throws Exception {
192         initDatastores(type, MODULE_SHARDS_CARS_PEOPLE_1_2, CARS_AND_PEOPLE);
193     }
194
195     private void initDatastores(final String type, final String moduleShardsConfig, final String[] shards)
196             throws Exception {
197         leaderTestKit = new IntegrationTestKit(leaderSystem, leaderDatastoreContextBuilder);
198
199         leaderDistributedDataStore = leaderTestKit.setupAbstractDataStore(
200                 testParameter, type, moduleShardsConfig, false, shards);
201
202         followerTestKit = new IntegrationTestKit(followerSystem, followerDatastoreContextBuilder);
203         followerDistributedDataStore = followerTestKit.setupAbstractDataStore(
204                 testParameter, type, moduleShardsConfig, false, shards);
205
206         leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorContext(), shards);
207     }
208
209     private static void verifyCars(final DOMStoreReadTransaction readTx, final MapEntryNode... entries)
210             throws Exception {
211         final Optional<NormalizedNode<?, ?>> optional = readTx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
212         assertEquals("isPresent", true, optional.isPresent());
213
214         final CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = ImmutableNodes.mapNodeBuilder(
215                 CarsModel.CAR_QNAME);
216         for (final NormalizedNode<?, ?> entry: entries) {
217             listBuilder.withChild((MapEntryNode) entry);
218         }
219
220         assertEquals("Car list node", listBuilder.build(), optional.get());
221     }
222
223     private static void verifyNode(final DOMStoreReadTransaction readTx, final YangInstanceIdentifier path,
224             final NormalizedNode<?, ?> expNode) throws Exception {
225         final Optional<NormalizedNode<?, ?>> optional = readTx.read(path).get(5, TimeUnit.SECONDS);
226         assertEquals("isPresent", true, optional.isPresent());
227         assertEquals("Data node", expNode, optional.get());
228     }
229
230     private static void verifyExists(final DOMStoreReadTransaction readTx, final YangInstanceIdentifier path)
231             throws Exception {
232         final Boolean exists = readTx.exists(path).get(5, TimeUnit.SECONDS);
233         assertEquals("exists", true, exists);
234     }
235
236     @Test
237     public void testWriteTransactionWithSingleShard() throws Exception {
238         final String testName = "testWriteTransactionWithSingleShard";
239         initDatastoresWithCars(testName);
240
241         final String followerCarShardName = "member-2-shard-cars-" + testName;
242         InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 2, ApplyJournalEntries.class);
243
244         DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
245         assertNotNull("newWriteOnlyTransaction returned null", writeTx);
246
247         writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
248         writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
249
250         final MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
251         final YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
252         writeTx.merge(car1Path, car1);
253
254         final MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
255         final YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
256         writeTx.merge(car2Path, car2);
257
258         followerTestKit.doCommit(writeTx.ready());
259
260         verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
261
262         verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
263
264         // Test delete
265
266         writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
267
268         writeTx.delete(car1Path);
269
270         followerTestKit.doCommit(writeTx.ready());
271
272         verifyExists(followerDistributedDataStore.newReadOnlyTransaction(), car2Path);
273
274         verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
275
276         verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car2);
277
278         // Re-instate the follower member 2 as a single-node to verify replication and recovery.
279
280         InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
281
282         JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
283         JavaTestKit.shutdownActorSystem(followerSystem, null, true);
284
285         final ActorSystem newSystem = ActorSystem.create("reinstated-member2", ConfigFactory.load()
286                 .getConfig("Member2"));
287
288         try (final AbstractDataStore member2Datastore = new IntegrationTestKit(newSystem, leaderDatastoreContextBuilder)
289                 .setupAbstractDataStore(testParameter, testName, "module-shards-member2", true, CARS_AND_PEOPLE)) {
290             verifyCars(member2Datastore.newReadOnlyTransaction(), car2);
291         }
292
293         JavaTestKit.shutdownActorSystem(newSystem);
294     }
295
296     @Test
297     public void testReadWriteTransactionWithSingleShard() throws Exception {
298         initDatastoresWithCars("testReadWriteTransactionWithSingleShard");
299
300         final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
301         assertNotNull("newReadWriteTransaction returned null", rwTx);
302
303         rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
304         rwTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
305
306         final MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
307         rwTx.merge(CarsModel.newCarPath("optima"), car1);
308
309         verifyCars(rwTx, car1);
310
311         final MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
312         final YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
313         rwTx.merge(car2Path, car2);
314
315         verifyExists(rwTx, car2Path);
316
317         followerTestKit.doCommit(rwTx.ready());
318
319         verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
320     }
321
322     @Test
323     public void testWriteTransactionWithMultipleShards() throws Exception {
324         initDatastoresWithCarsAndPeople("testWriteTransactionWithMultipleShards");
325
326         final DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
327         assertNotNull("newWriteOnlyTransaction returned null", writeTx);
328
329         final YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
330         final NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
331         writeTx.write(carsPath, carsNode);
332
333         final YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
334         final NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
335         writeTx.write(peoplePath, peopleNode);
336
337         followerTestKit.doCommit(writeTx.ready());
338
339         final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
340
341         verifyNode(readTx, carsPath, carsNode);
342         verifyNode(readTx, peoplePath, peopleNode);
343     }
344
345     @Test
346     public void testReadWriteTransactionWithMultipleShards() throws Exception {
347         initDatastoresWithCarsAndPeople("testReadWriteTransactionWithMultipleShards");
348
349         final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
350         assertNotNull("newReadWriteTransaction returned null", rwTx);
351
352         final YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
353         final NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
354         rwTx.write(carsPath, carsNode);
355
356         final YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
357         final NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
358         rwTx.write(peoplePath, peopleNode);
359
360         followerTestKit.doCommit(rwTx.ready());
361
362         final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
363
364         verifyNode(readTx, carsPath, carsNode);
365         verifyNode(readTx, peoplePath, peopleNode);
366     }
367
368     @Test
369     public void testTransactionChainWithSingleShard() throws Exception {
370         initDatastoresWithCars("testTransactionChainWithSingleShard");
371
372         final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
373
374         // Add the top-level cars container with write-only.
375
376         final DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
377         assertNotNull("newWriteOnlyTransaction returned null", writeTx);
378
379         writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
380
381         final DOMStoreThreePhaseCommitCohort writeTxReady = writeTx.ready();
382
383         // Verify the top-level cars container with read-only.
384
385         verifyNode(txChain.newReadOnlyTransaction(), CarsModel.BASE_PATH, CarsModel.emptyContainer());
386
387         // Perform car operations with read-write.
388
389         final DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
390
391         verifyNode(rwTx, CarsModel.BASE_PATH, CarsModel.emptyContainer());
392
393         rwTx.merge(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
394
395         final MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
396         final YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
397         rwTx.write(car1Path, car1);
398
399         verifyExists(rwTx, car1Path);
400
401         verifyCars(rwTx, car1);
402
403         final MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
404         rwTx.merge(CarsModel.newCarPath("sportage"), car2);
405
406         rwTx.delete(car1Path);
407
408         followerTestKit.doCommit(writeTxReady);
409
410         followerTestKit.doCommit(rwTx.ready());
411
412         txChain.close();
413
414         verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
415     }
416
417     @Test
418     public void testTransactionChainWithMultipleShards() throws Exception {
419         initDatastoresWithCarsAndPeople("testTransactionChainWithMultipleShards");
420
421         final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
422
423         DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
424         assertNotNull("newWriteOnlyTransaction returned null", writeTx);
425
426         writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
427         writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
428
429         writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
430         writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
431
432         followerTestKit.doCommit(writeTx.ready());
433
434         final DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
435
436         final MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
437         final YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
438         readWriteTx.write(carPath, car);
439
440         final MapEntryNode person = PeopleModel.newPersonEntry("jack");
441         final YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
442         readWriteTx.merge(personPath, person);
443
444         Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
445         assertEquals("isPresent", true, optional.isPresent());
446         assertEquals("Data node", car, optional.get());
447
448         optional = readWriteTx.read(personPath).get(5, TimeUnit.SECONDS);
449         assertEquals("isPresent", true, optional.isPresent());
450         assertEquals("Data node", person, optional.get());
451
452         final DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
453
454         writeTx = txChain.newWriteOnlyTransaction();
455
456         writeTx.delete(personPath);
457
458         final DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
459
460         followerTestKit.doCommit(cohort2);
461         followerTestKit.doCommit(cohort3);
462
463         txChain.close();
464
465         final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
466         verifyCars(readTx, car);
467
468         optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
469         assertEquals("isPresent", false, optional.isPresent());
470     }
471
472     @Test
473     public void testChainedTransactionFailureWithSingleShard() throws Exception {
474         initDatastoresWithCars("testChainedTransactionFailureWithSingleShard");
475
476         final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
477                 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
478                         LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
479                         MoreExecutors.directExecutor());
480
481         final TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
482         final DOMTransactionChain txChain = broker.createTransactionChain(listener);
483
484         final DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
485
486         final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
487                 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
488                     .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
489
490         writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
491
492         try {
493             writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
494             fail("Expected TransactionCommitFailedException");
495         } catch (final TransactionCommitFailedException e) {
496             // Expected
497         }
498
499         verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
500
501         txChain.close();
502         broker.close();
503     }
504
505     @Test
506     public void testChainedTransactionFailureWithMultipleShards() throws Exception {
507         initDatastoresWithCarsAndPeople("testChainedTransactionFailureWithMultipleShards");
508
509         final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
510                 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
511                         LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
512                         MoreExecutors.directExecutor());
513
514         final TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
515         final DOMTransactionChain txChain = broker.createTransactionChain(listener);
516
517         final DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
518
519         writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
520
521         final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
522                 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
523                     .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
524
525         // Note that merge will validate the data and fail but put succeeds b/c deep validation is not
526         // done for put for performance reasons.
527         writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
528
529         try {
530             writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
531             fail("Expected TransactionCommitFailedException");
532         } catch (final TransactionCommitFailedException e) {
533             // Expected
534         }
535
536         verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
537
538         txChain.close();
539         broker.close();
540     }
541
542     @Test
543     public void testSingleShardTransactionsWithLeaderChanges() throws Exception {
544         //TODO remove when test passes also for ClientBackedDataStore
545         Assume.assumeTrue(testParameter.equals(DistributedDataStore.class));
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);
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         try (final AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupAbstractDataStore(
856                 testParameter, testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, false)) {
857
858             // Create and submit a couple tx's so they're pending.
859
860             DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
861             writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
862             writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
863             writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
864             final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
865
866             IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
867                 stats -> assertEquals("getTxCohortCacheSize", 1, stats.getTxCohortCacheSize()));
868
869             writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
870             final MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
871             writeTx.write(CarsModel.newCarPath("optima"), car);
872             final DOMStoreThreePhaseCommitCohort cohort2 = writeTx.ready();
873
874             IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
875                 stats -> assertEquals("getTxCohortCacheSize", 2, stats.getTxCohortCacheSize()));
876
877             // Gracefully stop the leader via a Shutdown message.
878
879             sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
880                 .shardElectionTimeoutFactor(100));
881
882             final FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
883             final Future<ActorRef> future = leaderDistributedDataStore.getActorContext().findLocalShardAsync("cars");
884             final ActorRef leaderActor = Await.result(future, duration);
885
886             final Future<Boolean> stopFuture = Patterns.gracefulStop(leaderActor, duration, Shutdown.INSTANCE);
887
888             // Commit the 2 transactions. They should finish and succeed.
889
890             followerTestKit.doCommit(cohort1);
891             followerTestKit.doCommit(cohort2);
892
893             // Wait for the leader actor stopped.
894
895             final Boolean stopped = Await.result(stopFuture, duration);
896             assertEquals("Stopped", Boolean.TRUE, stopped);
897
898             // Verify leadership was transferred by reading the committed data from the other nodes.
899
900             verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car);
901             verifyCars(follower2DistributedDataStore.newReadOnlyTransaction(), car);
902         }
903     }
904
905     @Test
906     public void testTransactionWithIsolatedLeader() throws Exception {
907         //TODO remove when test passes also for ClientBackedDataStore
908         Assume.assumeTrue(testParameter.equals(DistributedDataStore.class));
909         // Set the isolated leader check interval high so we can control the switch to IsolatedLeader.
910         leaderDatastoreContextBuilder.shardIsolatedLeaderCheckIntervalInMillis(10000000);
911         final String testName = "testTransactionWithIsolatedLeader";
912         initDatastoresWithCars(testName);
913
914         // Tx that is submitted after the follower is stopped but before the leader transitions to IsolatedLeader.
915         final DOMStoreWriteTransaction preIsolatedLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
916         preIsolatedLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
917
918         // Tx that is submitted after the leader transitions to IsolatedLeader.
919         final DOMStoreWriteTransaction noShardLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
920         noShardLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
921
922         // Tx that is submitted after the follower is reinstated.
923         final DOMStoreWriteTransaction successWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
924         successWriteTx.merge(CarsModel.BASE_PATH, CarsModel.emptyContainer());
925
926         // Stop the follower
927         followerTestKit.watch(followerDistributedDataStore.getActorContext().getShardManager());
928         followerDistributedDataStore.close();
929         followerTestKit.expectTerminated(followerDistributedDataStore.getActorContext().getShardManager());
930
931         // Submit the preIsolatedLeaderWriteTx so it's pending
932         final DOMStoreThreePhaseCommitCohort preIsolatedLeaderTxCohort = preIsolatedLeaderWriteTx.ready();
933
934         // Change the isolated leader check interval low so it changes to IsolatedLeader.
935         sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
936                 .shardIsolatedLeaderCheckIntervalInMillis(200));
937
938         MemberNode.verifyRaftState(leaderDistributedDataStore, "cars",
939             raftState -> assertEquals("getRaftState", "IsolatedLeader", raftState.getRaftState()));
940
941         try {
942             leaderTestKit.doCommit(noShardLeaderWriteTx.ready());
943             fail("Expected NoShardLeaderException");
944         } catch (final ExecutionException e) {
945             assertEquals("getCause", NoShardLeaderException.class, Throwables.getRootCause(e).getClass());
946         }
947
948         sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
949                 .shardElectionTimeoutFactor(100));
950
951         final DOMStoreThreePhaseCommitCohort successTxCohort = successWriteTx.ready();
952
953         followerDistributedDataStore = followerTestKit.setupAbstractDataStore(
954                 testParameter, testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS);
955
956         leaderTestKit.doCommit(preIsolatedLeaderTxCohort);
957         leaderTestKit.doCommit(successTxCohort);
958     }
959
960     @Test(expected = AskTimeoutException.class)
961     public void testTransactionWithShardLeaderNotResponding() throws Exception {
962         //TODO remove when test passes also for ClientBackedDataStore
963         Assume.assumeTrue(testParameter.equals(DistributedDataStore.class));
964         followerDatastoreContextBuilder.shardElectionTimeoutFactor(50);
965         initDatastoresWithCars("testTransactionWithShardLeaderNotResponding");
966
967         // Do an initial read to get the primary shard info cached.
968
969         final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
970         readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
971
972         // Shutdown the leader and try to create a new tx.
973
974         JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
975
976         followerDatastoreContextBuilder.operationTimeoutInMillis(50).shardElectionTimeoutFactor(1);
977         sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder);
978
979         final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
980
981         rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
982
983         try {
984             followerTestKit.doCommit(rwTx.ready());
985         } catch (final ExecutionException e) {
986             assertTrue("Expected ShardLeaderNotRespondingException cause. Actual: " + e.getCause(),
987                     e.getCause() instanceof ShardLeaderNotRespondingException);
988             assertNotNull("Expected a nested cause", e.getCause().getCause());
989             Throwables.propagateIfInstanceOf(e.getCause().getCause(), Exception.class);
990             Throwables.propagate(e.getCause().getCause());
991         }
992     }
993
994     @Test(expected = NoShardLeaderException.class)
995     public void testTransactionWithCreateTxFailureDueToNoLeader() throws Exception {
996         //TODO remove when test passes also for ClientBackedDataStore
997         Assume.assumeTrue(testParameter.equals(DistributedDataStore.class));
998         initDatastoresWithCars("testTransactionWithCreateTxFailureDueToNoLeader");
999
1000         // Do an initial read to get the primary shard info cached.
1001
1002         final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1003         readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
1004
1005         // Shutdown the leader and try to create a new tx.
1006
1007         JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
1008
1009         Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
1010
1011         Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
1012
1013         sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1014                 .operationTimeoutInMillis(10).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
1015
1016         final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1017
1018         rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1019
1020         try {
1021             followerTestKit.doCommit(rwTx.ready());
1022         } catch (final ExecutionException e) {
1023             Throwables.propagateIfInstanceOf(e.getCause(), Exception.class);
1024             Throwables.propagate(e.getCause());
1025         }
1026     }
1027
1028     @Test
1029     public void testTransactionRetryWithInitialAskTimeoutExOnCreateTx() throws Exception {
1030         //TODO remove when test passes also for ClientBackedDataStore
1031         Assume.assumeTrue(testParameter.equals(DistributedDataStore.class));
1032         String testName = "testTransactionRetryWithInitialAskTimeoutExOnCreateTx";
1033         initDatastores(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, CARS);
1034
1035         final DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder()
1036                 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
1037         final IntegrationTestKit follower2TestKit = new IntegrationTestKit(
1038                 follower2System, follower2DatastoreContextBuilder);
1039
1040         try (final AbstractDataStore ds =
1041                 follower2TestKit.setupAbstractDataStore(
1042                         testParameter, testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, false, CARS)) {
1043
1044             followerTestKit.waitForMembersUp("member-1", "member-3");
1045             follower2TestKit.waitForMembersUp("member-1", "member-2");
1046
1047             // Do an initial read to get the primary shard info cached.
1048
1049             final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1050             readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
1051
1052             // Shutdown the leader and try to create a new tx.
1053
1054             JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
1055
1056             Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
1057
1058             sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1059                 .operationTimeoutInMillis(500).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
1060
1061             final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1062
1063             rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1064
1065             followerTestKit.doCommit(rwTx.ready());
1066         }
1067     }
1068
1069     @Test
1070     public void testInstallSnapshot() throws Exception {
1071         final String testName = "testInstallSnapshot";
1072         final String leaderCarShardName = "member-1-shard-cars-" + testName;
1073         final String followerCarShardName = "member-2-shard-cars-" + testName;
1074
1075         // Setup a saved snapshot on the leader. The follower will startup with no data and the leader should
1076         // install a snapshot to sync the follower.
1077
1078         TipProducingDataTree tree = InMemoryDataTreeFactory.getInstance().create(TreeType.CONFIGURATION);
1079         tree.setSchemaContext(SchemaContextHelper.full());
1080
1081         final ContainerNode carsNode = CarsModel.newCarsNode(
1082                 CarsModel.newCarsMapNode(CarsModel.newCarEntry("optima", BigInteger.valueOf(20000))));
1083         AbstractShardTest.writeToStore(tree, CarsModel.BASE_PATH, carsNode);
1084
1085         final NormalizedNode<?, ?> snapshotRoot = AbstractShardTest.readStore(tree, YangInstanceIdentifier.EMPTY);
1086         final Snapshot initialSnapshot = Snapshot.create(
1087                 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(snapshotRoot)),
1088                 Collections.emptyList(), 5, 1, 5, 1, 1, null, null);
1089         InMemorySnapshotStore.addSnapshot(leaderCarShardName, initialSnapshot);
1090
1091         InMemorySnapshotStore.addSnapshotSavedLatch(leaderCarShardName);
1092         InMemorySnapshotStore.addSnapshotSavedLatch(followerCarShardName);
1093
1094         initDatastoresWithCars(testName);
1095
1096         final Optional<NormalizedNode<?, ?>> readOptional = leaderDistributedDataStore.newReadOnlyTransaction().read(
1097                 CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
1098         assertEquals("isPresent", true, readOptional.isPresent());
1099         assertEquals("Node", carsNode, readOptional.get());
1100
1101         verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(leaderCarShardName, Snapshot.class),
1102                 initialSnapshot, snapshotRoot);
1103
1104         verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(followerCarShardName, Snapshot.class),
1105                 initialSnapshot, snapshotRoot);
1106     }
1107
1108     private static void verifySnapshot(final Snapshot actual, final Snapshot expected,
1109                                        final NormalizedNode<?, ?> expRoot) {
1110         assertEquals("Snapshot getLastAppliedTerm", expected.getLastAppliedTerm(), actual.getLastAppliedTerm());
1111         assertEquals("Snapshot getLastAppliedIndex", expected.getLastAppliedIndex(), actual.getLastAppliedIndex());
1112         assertEquals("Snapshot getLastTerm", expected.getLastTerm(), actual.getLastTerm());
1113         assertEquals("Snapshot getLastIndex", expected.getLastIndex(), actual.getLastIndex());
1114         assertEquals("Snapshot state type", ShardSnapshotState.class, actual.getState().getClass());
1115         MetadataShardDataTreeSnapshot shardSnapshot =
1116                 (MetadataShardDataTreeSnapshot) ((ShardSnapshotState)actual.getState()).getSnapshot();
1117         assertEquals("Snapshot root node", expRoot, shardSnapshot.getRootNode().get());
1118     }
1119
1120     private static void sendDatastoreContextUpdate(final AbstractDataStore dataStore, final Builder builder) {
1121         final Builder newBuilder = DatastoreContext.newBuilderFrom(builder.build());
1122         final DatastoreContextFactory mockContextFactory = Mockito.mock(DatastoreContextFactory.class);
1123         final Answer<DatastoreContext> answer = invocation -> newBuilder.build();
1124         Mockito.doAnswer(answer).when(mockContextFactory).getBaseDatastoreContext();
1125         Mockito.doAnswer(answer).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
1126         dataStore.onDatastoreContextUpdated(mockContextFactory);
1127     }
1128 }