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