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