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