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

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.