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

©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.