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