2ca128271e0497d17446e742d6b847af905d598f
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / test / java / org / opendaylight / controller / cluster / datastore / entityownership / DistributedEntityOwnershipIntegrationTest.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.entityownership;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertFalse;
12 import static org.junit.Assert.assertTrue;
13 import static org.mockito.AdditionalMatchers.or;
14 import static org.mockito.Mockito.atMost;
15 import static org.mockito.Mockito.doNothing;
16 import static org.mockito.Mockito.reset;
17 import static org.mockito.Mockito.timeout;
18 import static org.mockito.Mockito.verify;
19 import static org.opendaylight.controller.cluster.datastore.entityownership.AbstractEntityOwnershipTest.ownershipChange;
20 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.CANDIDATE_NAME_NODE_ID;
21 import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityPath;
22 import akka.actor.ActorSystem;
23 import akka.actor.Address;
24 import akka.actor.AddressFromURIString;
25 import akka.cluster.Cluster;
26 import akka.testkit.JavaTestKit;
27 import com.google.common.base.Function;
28 import com.google.common.base.Optional;
29 import com.google.common.base.Stopwatch;
30 import com.google.common.util.concurrent.Uninterruptibles;
31 import com.typesafe.config.ConfigFactory;
32 import java.util.ArrayList;
33 import java.util.Arrays;
34 import java.util.Collection;
35 import java.util.concurrent.TimeUnit;
36 import org.junit.After;
37 import org.junit.Before;
38 import org.junit.Test;
39 import org.mockito.ArgumentCaptor;
40 import org.mockito.Mock;
41 import org.mockito.Mockito;
42 import org.mockito.MockitoAnnotations;
43 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
44 import org.opendaylight.controller.cluster.datastore.DistributedDataStore;
45 import org.opendaylight.controller.cluster.datastore.IntegrationTestKit;
46 import org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.EntityOwnerSelectionStrategyConfig;
47 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
48 import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
49 import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
50 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
51 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipChange;
52 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
53 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.clustering.entity.owners.rev150804.entity.owners.entity.type.entity.Candidate;
55 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
56 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
59 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
60
61 /**
62  * End-to-end integration tests for the entity ownership functionality.
63  *
64  * @author Thomas Pantelis
65  */
66 public class DistributedEntityOwnershipIntegrationTest {
67     private static final Address MEMBER_1_ADDRESS = AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2558");
68     private static final String MODULE_SHARDS_CONFIG = "module-shards-default.conf";
69     private static final String ENTITY_TYPE1 = "entityType1";
70     private static final String ENTITY_TYPE2 = "entityType2";
71     private static final Entity ENTITY1 = new Entity(ENTITY_TYPE1, "entity1");
72     private static final Entity ENTITY1_2 = new Entity(ENTITY_TYPE2, "entity1");
73     private static final Entity ENTITY2 = new Entity(ENTITY_TYPE1, "entity2");
74     private static final Entity ENTITY3 = new Entity(ENTITY_TYPE1, "entity3");
75     private static final Entity ENTITY4 = new Entity(ENTITY_TYPE1, "entity4");
76     private static final SchemaContext SCHEMA_CONTEXT = SchemaContextHelper.entityOwners();
77
78     private ActorSystem leaderSystem;
79     private ActorSystem follower1System;
80     private ActorSystem follower2System;
81
82     private final DatastoreContext.Builder leaderDatastoreContextBuilder =
83             DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
84
85     private final DatastoreContext.Builder followerDatastoreContextBuilder =
86             DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(10000);
87
88     private DistributedDataStore leaderDistributedDataStore;
89     private DistributedDataStore follower1DistributedDataStore;
90     private DistributedDataStore follower2DistributedDataStore;
91     private DistributedEntityOwnershipService leaderEntityOwnershipService;
92     private DistributedEntityOwnershipService follower1EntityOwnershipService;
93     private DistributedEntityOwnershipService follower2EntityOwnershipService;
94     private IntegrationTestKit leaderTestKit;
95     private IntegrationTestKit follower1TestKit;
96     private IntegrationTestKit follower2TestKit;
97
98     @Mock
99     private EntityOwnershipListener leaderMockListener;
100
101     @Mock
102     private EntityOwnershipListener leaderMockListener2;
103
104     @Mock
105     private EntityOwnershipListener follower1MockListener;
106
107     @Mock
108     private EntityOwnershipListener follower2MockListener;
109
110     @Before
111     public void setUp() {
112         MockitoAnnotations.initMocks(this);
113
114         leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
115         Cluster.get(leaderSystem).join(MEMBER_1_ADDRESS);
116
117         follower1System = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member2"));
118         Cluster.get(follower1System).join(MEMBER_1_ADDRESS);
119
120         follower2System = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member3"));
121         Cluster.get(follower2System).join(MEMBER_1_ADDRESS);
122     }
123
124     @After
125     public void tearDown() {
126         JavaTestKit.shutdownActorSystem(leaderSystem);
127         JavaTestKit.shutdownActorSystem(follower1System);
128         JavaTestKit.shutdownActorSystem(follower2System);
129     }
130
131     private void initDatastores(String type) {
132         leaderTestKit = new IntegrationTestKit(leaderSystem, leaderDatastoreContextBuilder);
133         leaderDistributedDataStore = leaderTestKit.setupDistributedDataStore(
134                 type, MODULE_SHARDS_CONFIG, false, SCHEMA_CONTEXT);
135
136         follower1TestKit = new IntegrationTestKit(follower1System, followerDatastoreContextBuilder);
137         follower1DistributedDataStore = follower1TestKit.setupDistributedDataStore(
138                 type, MODULE_SHARDS_CONFIG, false, SCHEMA_CONTEXT);
139
140         follower2TestKit = new IntegrationTestKit(follower2System, followerDatastoreContextBuilder);
141         follower2DistributedDataStore = follower2TestKit.setupDistributedDataStore(
142                 type, MODULE_SHARDS_CONFIG, false, SCHEMA_CONTEXT);
143
144         leaderDistributedDataStore.waitTillReady();
145         follower1DistributedDataStore.waitTillReady();
146         follower2DistributedDataStore.waitTillReady();
147
148         leaderEntityOwnershipService = new DistributedEntityOwnershipService(leaderDistributedDataStore, EntityOwnerSelectionStrategyConfig.newBuilder().build());
149         leaderEntityOwnershipService.start();
150
151         follower1EntityOwnershipService = new DistributedEntityOwnershipService(follower1DistributedDataStore, EntityOwnerSelectionStrategyConfig.newBuilder().build());
152         follower1EntityOwnershipService.start();
153
154         follower2EntityOwnershipService = new DistributedEntityOwnershipService(follower2DistributedDataStore, EntityOwnerSelectionStrategyConfig.newBuilder().build());
155         follower2EntityOwnershipService.start();
156
157         leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorContext(),
158                 DistributedEntityOwnershipService.ENTITY_OWNERSHIP_SHARD_NAME);
159     }
160
161     @Test
162     public void test() throws Exception {
163         initDatastores("test");
164
165         leaderEntityOwnershipService.registerListener(ENTITY_TYPE1, leaderMockListener);
166         leaderEntityOwnershipService.registerListener(ENTITY_TYPE2, leaderMockListener2);
167         follower1EntityOwnershipService.registerListener(ENTITY_TYPE1, follower1MockListener);
168
169         // Register leader candidate for entity1 and verify it becomes owner
170
171         leaderEntityOwnershipService.registerCandidate(ENTITY1);
172         verify(leaderMockListener, timeout(5000)).ownershipChanged(ownershipChange(ENTITY1, false, true, true));
173         verify(follower1MockListener, timeout(5000)).ownershipChanged(ownershipChange(ENTITY1, false, false, true));
174         reset(leaderMockListener, follower1MockListener);
175
176         verifyGetOwnershipState(leaderEntityOwnershipService, ENTITY1, true, true);
177         verifyGetOwnershipState(follower1EntityOwnershipService, ENTITY1, false, true);
178
179         // Register leader candidate for entity1_2 (same id, different type) and verify it becomes owner
180
181         leaderEntityOwnershipService.registerCandidate(ENTITY1_2);
182         verify(leaderMockListener2, timeout(5000)).ownershipChanged(ownershipChange(ENTITY1_2, false, true, true));
183         verify(leaderMockListener, timeout(300).never()).ownershipChanged(ownershipChange(ENTITY1_2));
184         reset(leaderMockListener2);
185
186         // Register follower1 candidate for entity1 and verify it gets added but doesn't become owner
187
188         follower1EntityOwnershipService.registerCandidate(ENTITY1);
189         verifyCandidates(leaderDistributedDataStore, ENTITY1, "member-1", "member-2");
190         verifyOwner(leaderDistributedDataStore, ENTITY1, "member-1");
191         verify(leaderMockListener, timeout(300).never()).ownershipChanged(ownershipChange(ENTITY1));
192         verify(follower1MockListener, timeout(300).never()).ownershipChanged(ownershipChange(ENTITY1));
193
194         // Register follower1 candidate for entity2 and verify it becomes owner
195
196         follower1EntityOwnershipService.registerCandidate(ENTITY2);
197         verify(follower1MockListener, timeout(5000)).ownershipChanged(ownershipChange(ENTITY2, false, true, true));
198         verify(leaderMockListener, timeout(5000)).ownershipChanged(ownershipChange(ENTITY2, false, false, true));
199         reset(leaderMockListener, follower1MockListener);
200
201         // Register follower2 candidate for entity2 and verify it gets added but doesn't become owner
202
203         follower2EntityOwnershipService.registerListener(ENTITY_TYPE1, follower2MockListener);
204         follower2EntityOwnershipService.registerCandidate(ENTITY2);
205         verifyCandidates(leaderDistributedDataStore, ENTITY2, "member-2", "member-3");
206         verifyOwner(leaderDistributedDataStore, ENTITY2, "member-2");
207
208         // Unregister follower1 candidate for entity2 and verify follower2 becomes owner
209
210         follower1EntityOwnershipService.unregisterCandidate(ENTITY2);
211         verifyCandidates(leaderDistributedDataStore, ENTITY2, "member-3");
212         verifyOwner(leaderDistributedDataStore, ENTITY2, "member-3");
213         verify(follower1MockListener, timeout(5000)).ownershipChanged(ownershipChange(ENTITY2, true, false, true));
214         verify(leaderMockListener, timeout(5000)).ownershipChanged(ownershipChange(ENTITY2, false, false, true));
215
216         // Depending on timing, follower2MockListener could get ownershipChanged with "false, false, true" if
217         // if the original ownership change with "member-2 is replicated to follower2 after the listener is
218         // registered.
219         Uninterruptibles.sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
220         verify(follower2MockListener, atMost(1)).ownershipChanged(ownershipChange(ENTITY2, false, false, true));
221         verify(follower2MockListener, timeout(5000)).ownershipChanged(ownershipChange(ENTITY2, false, true, true));
222
223         // Register follower1 candidate for entity3 and verify it becomes owner
224
225         follower1EntityOwnershipService.registerCandidate(ENTITY3);
226         verifyOwner(leaderDistributedDataStore, ENTITY3, "member-2");
227         verify(follower1MockListener, timeout(5000)).ownershipChanged(ownershipChange(ENTITY3, false, true, true));
228         verify(follower2MockListener, timeout(5000)).ownershipChanged(ownershipChange(ENTITY3, false, false, true));
229         verify(leaderMockListener, timeout(5000)).ownershipChanged(ownershipChange(ENTITY3, false, false, true));
230
231         // Register follower2 candidate for entity4 and verify it becomes owner
232
233         follower2EntityOwnershipService.registerCandidate(ENTITY4);
234         verifyOwner(leaderDistributedDataStore, ENTITY4, "member-3");
235         verify(follower2MockListener, timeout(5000)).ownershipChanged(ownershipChange(ENTITY4, false, true, true));
236         verify(follower1MockListener, timeout(5000)).ownershipChanged(ownershipChange(ENTITY4, false, false, true));
237         verify(leaderMockListener, timeout(5000)).ownershipChanged(ownershipChange(ENTITY4, false, false, true));
238         reset(follower1MockListener, follower2MockListener);
239
240         // Register follower1 candidate for entity4 and verify it gets added but doesn't become owner
241
242         follower1EntityOwnershipService.registerCandidate(ENTITY4);
243         verifyCandidates(leaderDistributedDataStore, ENTITY4, "member-3", "member-2");
244         verifyOwner(leaderDistributedDataStore, ENTITY4, "member-3");
245
246         // Shutdown follower2 and verify it's owned entities (entity 2 & 4) get re-assigned
247
248         reset(leaderMockListener, follower1MockListener);
249         JavaTestKit.shutdownActorSystem(follower2System);
250
251         verify(follower1MockListener, timeout(15000).times(2)).ownershipChanged(or(ownershipChange(ENTITY4, false, true, true),
252                 ownershipChange(ENTITY2, false, false, false)));
253         verify(leaderMockListener, timeout(15000).times(2)).ownershipChanged(or(ownershipChange(ENTITY4, false, false, true),
254                 ownershipChange(ENTITY2, false, false, false)));
255         verifyOwner(leaderDistributedDataStore, ENTITY2, ""); // no other candidate
256
257         // Register leader candidate for entity2 and verify it becomes owner
258
259         leaderEntityOwnershipService.registerCandidate(ENTITY2);
260         verify(leaderMockListener, timeout(5000)).ownershipChanged(ownershipChange(ENTITY2, false, true, true));
261         verifyOwner(leaderDistributedDataStore, ENTITY2, "member-1");
262
263         // Unregister leader candidate for entity2 and verify the owner is cleared
264
265         leaderEntityOwnershipService.unregisterCandidate(ENTITY2);
266         verifyOwner(leaderDistributedDataStore, ENTITY2, "");
267         verify(leaderMockListener, timeout(5000)).ownershipChanged(ownershipChange(ENTITY2, true, false, false));
268         verify(follower1MockListener, timeout(5000)).ownershipChanged(ownershipChange(ENTITY2, false, false, false));
269     }
270
271     /**
272      * Reproduces bug <a href="https://bugs.opendaylight.org/show_bug.cgi?id=4554">4554</a>
273      *
274      * @throws CandidateAlreadyRegisteredException
275      */
276     @Test
277     public void testCloseCandidateRegistrationInQuickSuccession() throws CandidateAlreadyRegisteredException {
278         initDatastores("testCloseCandidateRegistrationInQuickSuccession");
279
280         leaderEntityOwnershipService.registerListener(ENTITY_TYPE1, leaderMockListener);
281         follower1EntityOwnershipService.registerListener(ENTITY_TYPE1, follower1MockListener);
282         follower2EntityOwnershipService.registerListener(ENTITY_TYPE1, follower2MockListener);
283
284         final EntityOwnershipCandidateRegistration candidate1 = leaderEntityOwnershipService.registerCandidate(ENTITY1);
285         final EntityOwnershipCandidateRegistration candidate2 = follower1EntityOwnershipService.registerCandidate(ENTITY1);
286         final EntityOwnershipCandidateRegistration candidate3 = follower2EntityOwnershipService.registerCandidate(ENTITY1);
287
288         verify(leaderMockListener, timeout(5000)).ownershipChanged(ownershipChange(ENTITY1, false, true, true));
289
290         Mockito.reset(leaderMockListener);
291
292         candidate1.close();
293         candidate2.close();
294         candidate3.close();
295
296         ArgumentCaptor<EntityOwnershipChange> leaderChangeCaptor = ArgumentCaptor.forClass(EntityOwnershipChange.class);
297         ArgumentCaptor<EntityOwnershipChange> follower1ChangeCaptor = ArgumentCaptor.forClass(EntityOwnershipChange.class);
298         ArgumentCaptor<EntityOwnershipChange> follower2ChangeCaptor = ArgumentCaptor.forClass(EntityOwnershipChange.class);
299         doNothing().when(leaderMockListener).ownershipChanged(leaderChangeCaptor.capture());
300         doNothing().when(follower1MockListener).ownershipChanged(follower1ChangeCaptor.capture());
301         doNothing().when(follower2MockListener).ownershipChanged(follower2ChangeCaptor.capture());
302
303         boolean passed = false;
304         for(int i=0;i<100;i++) {
305             Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
306             if(!leaderEntityOwnershipService.getOwnershipState(ENTITY1).get().hasOwner() &&
307                     !follower1EntityOwnershipService.getOwnershipState(ENTITY1).get().hasOwner() &&
308                     !follower2EntityOwnershipService.getOwnershipState(ENTITY1).get().hasOwner()) {
309                 passed = true;
310                 break;
311             }
312         }
313
314         assertTrue("No ownership change message was sent with hasOwner=false", passed);
315
316         assertFalse(leaderChangeCaptor.getAllValues().get(leaderChangeCaptor.getAllValues().size()-1).hasOwner());
317         assertFalse(follower1ChangeCaptor.getAllValues().get(follower1ChangeCaptor.getAllValues().size()-1).hasOwner());
318         assertFalse(follower2ChangeCaptor.getAllValues().get(follower2ChangeCaptor.getAllValues().size()-1).hasOwner());
319     }
320
321     private static void verifyGetOwnershipState(DistributedEntityOwnershipService service, Entity entity,
322             boolean isOwner, boolean hasOwner) {
323         Optional<EntityOwnershipState> state = service.getOwnershipState(entity);
324         assertEquals("getOwnershipState present", true, state.isPresent());
325         assertEquals("isOwner", isOwner, state.get().isOwner());
326         assertEquals("hasOwner", hasOwner, state.get().hasOwner());
327     }
328
329     private static void verifyCandidates(DistributedDataStore dataStore, Entity entity, String... expCandidates) throws Exception {
330         AssertionError lastError = null;
331         Stopwatch sw = Stopwatch.createStarted();
332         while(sw.elapsed(TimeUnit.MILLISECONDS) <= 5000) {
333             Optional<NormalizedNode<?, ?>> possible = dataStore.newReadOnlyTransaction().read(
334                     entityPath(entity.getType(), entity.getId()).node(Candidate.QNAME)).get(5, TimeUnit.SECONDS);
335             try {
336                 assertEquals("Candidates not found for " + entity, true, possible.isPresent());
337                 Collection<String> actual = new ArrayList<>();
338                 for(MapEntryNode candidate: ((MapNode)possible.get()).getValue()) {
339                     actual.add(candidate.getChild(CANDIDATE_NAME_NODE_ID).get().getValue().toString());
340                 }
341
342                 assertEquals("Candidates for " + entity, Arrays.asList(expCandidates), actual);
343                 return;
344             } catch (AssertionError e) {
345                 lastError = e;
346                 Uninterruptibles.sleepUninterruptibly(300, TimeUnit.MILLISECONDS);
347             }
348         }
349
350         throw lastError;
351     }
352
353     private static void verifyOwner(final DistributedDataStore dataStore, Entity entity, String expOwner) {
354         AbstractEntityOwnershipTest.verifyOwner(expOwner, entity.getType(), entity.getId(),
355                 new Function<YangInstanceIdentifier, NormalizedNode<?,?>>() {
356                     @Override
357                     public NormalizedNode<?, ?> apply(YangInstanceIdentifier path) {
358                         try {
359                             return dataStore.newReadOnlyTransaction().read(path).get(5, TimeUnit.SECONDS).get();
360                         } catch (Exception e) {
361                             return null;
362                         }
363                     }
364                 });
365     }
366 }

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