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

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