Teach sal-remoterpc-connector to route actions
[controller.git] / opendaylight / md-sal / sal-remoterpc-connector / src / test / java / org / opendaylight / controller / remote / rpc / registry / RpcRegistryTest.java
1 /*
2  * Copyright (c) 2014, 2015 Cisco 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.remote.rpc.registry;
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.opendaylight.controller.remote.rpc.registry.gossip.BucketStoreAccess.Singletons.GET_ALL_BUCKETS;
15 import static org.opendaylight.controller.remote.rpc.registry.gossip.BucketStoreAccess.Singletons.GET_BUCKET_VERSIONS;
16
17 import akka.actor.ActorRef;
18 import akka.actor.ActorSystem;
19 import akka.actor.Address;
20 import akka.cluster.Cluster;
21 import akka.cluster.ClusterEvent.CurrentClusterState;
22 import akka.cluster.Member;
23 import akka.cluster.MemberStatus;
24 import akka.cluster.UniqueAddress;
25 import akka.testkit.javadsl.TestKit;
26 import com.google.common.base.Stopwatch;
27 import com.google.common.collect.Sets;
28 import com.google.common.util.concurrent.Uninterruptibles;
29 import com.typesafe.config.ConfigFactory;
30 import java.net.URI;
31 import java.time.Duration;
32 import java.util.ArrayList;
33 import java.util.Arrays;
34 import java.util.Collection;
35 import java.util.Collections;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.Optional;
39 import java.util.Set;
40 import java.util.concurrent.TimeUnit;
41 import org.junit.After;
42 import org.junit.AfterClass;
43 import org.junit.Before;
44 import org.junit.BeforeClass;
45 import org.junit.Test;
46 import org.opendaylight.controller.cluster.common.actor.AkkaConfigurationReader;
47 import org.opendaylight.controller.remote.rpc.RemoteOpsProviderConfig;
48 import org.opendaylight.controller.remote.rpc.registry.RpcRegistry.Messages.AddOrUpdateRoutes;
49 import org.opendaylight.controller.remote.rpc.registry.RpcRegistry.Messages.RemoveRoutes;
50 import org.opendaylight.controller.remote.rpc.registry.RpcRegistry.Messages.UpdateRemoteEndpoints;
51 import org.opendaylight.controller.remote.rpc.registry.RpcRegistry.RemoteRpcEndpoint;
52 import org.opendaylight.controller.remote.rpc.registry.gossip.Bucket;
53 import org.opendaylight.mdsal.dom.api.DOMRpcIdentifier;
54 import org.opendaylight.yangtools.yang.common.QName;
55 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 public class RpcRegistryTest {
60     private static final Logger LOG = LoggerFactory.getLogger(RpcRegistryTest.class);
61
62     private static ActorSystem node1;
63     private static ActorSystem node2;
64     private static ActorSystem node3;
65
66     private TestKit invoker1;
67     private TestKit invoker2;
68     private TestKit invoker3;
69     private TestKit registrar1;
70     private TestKit registrar2;
71     private TestKit registrar3;
72     private ActorRef registry1;
73     private ActorRef registry2;
74     private ActorRef registry3;
75
76     private int routeIdCounter = 1;
77
78     @BeforeClass
79     public static void staticSetup() {
80         AkkaConfigurationReader reader = ConfigFactory::load;
81
82         RemoteOpsProviderConfig config1 = new RemoteOpsProviderConfig.Builder("memberA").gossipTickInterval("200ms")
83                 .withConfigReader(reader).build();
84         RemoteOpsProviderConfig config2 = new RemoteOpsProviderConfig.Builder("memberB").gossipTickInterval("200ms")
85                 .withConfigReader(reader).build();
86         RemoteOpsProviderConfig config3 = new RemoteOpsProviderConfig.Builder("memberC").gossipTickInterval("200ms")
87                 .withConfigReader(reader).build();
88         node1 = ActorSystem.create("opendaylight-rpc", config1.get());
89         node2 = ActorSystem.create("opendaylight-rpc", config2.get());
90         node3 = ActorSystem.create("opendaylight-rpc", config3.get());
91
92         waitForMembersUp(node1, Cluster.get(node2).selfUniqueAddress(), Cluster.get(node3).selfUniqueAddress());
93         waitForMembersUp(node2, Cluster.get(node1).selfUniqueAddress(), Cluster.get(node3).selfUniqueAddress());
94     }
95
96     static void waitForMembersUp(final ActorSystem node, final UniqueAddress... addresses) {
97         Set<UniqueAddress> otherMembersSet = Sets.newHashSet(addresses);
98         Stopwatch sw = Stopwatch.createStarted();
99         while (sw.elapsed(TimeUnit.SECONDS) <= 10) {
100             CurrentClusterState state = Cluster.get(node).state();
101             for (Member m : state.getMembers()) {
102                 if (m.status() == MemberStatus.up() && otherMembersSet.remove(m.uniqueAddress())
103                         && otherMembersSet.isEmpty()) {
104                     return;
105                 }
106             }
107
108             Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
109         }
110
111         fail("Member(s) " + otherMembersSet + " are not Up");
112     }
113
114     @AfterClass
115     public static void staticTeardown() {
116         TestKit.shutdownActorSystem(node1);
117         TestKit.shutdownActorSystem(node2);
118         TestKit.shutdownActorSystem(node3);
119     }
120
121     @Before
122     public void setup() {
123         invoker1 = new TestKit(node1);
124         registrar1 = new TestKit(node1);
125         registry1 = node1.actorOf(RpcRegistry.props(config(node1), invoker1.getRef(), registrar1.getRef()));
126         invoker2 = new TestKit(node2);
127         registrar2 = new TestKit(node2);
128         registry2 = node2.actorOf(RpcRegistry.props(config(node2), invoker2.getRef(), registrar2.getRef()));
129         invoker3 = new TestKit(node3);
130         registrar3 = new TestKit(node3);
131         registry3 = node3.actorOf(RpcRegistry.props(config(node3), invoker3.getRef(), registrar3.getRef()));
132     }
133
134     private static RemoteOpsProviderConfig config(final ActorSystem node) {
135         return new RemoteOpsProviderConfig(node.settings().config());
136     }
137
138     @After
139     public void teardown() {
140         if (registry1 != null) {
141             node1.stop(registry1);
142         }
143         if (registry2 != null) {
144             node2.stop(registry2);
145         }
146         if (registry3 != null) {
147             node3.stop(registry3);
148         }
149
150         if (invoker1 != null) {
151             node1.stop(invoker1.getRef());
152         }
153         if (invoker2 != null) {
154             node2.stop(invoker2.getRef());
155         }
156         if (invoker3 != null) {
157             node3.stop(invoker3.getRef());
158         }
159
160         if (registrar1 != null) {
161             node1.stop(registrar1.getRef());
162         }
163         if (registrar2 != null) {
164             node2.stop(registrar2.getRef());
165         }
166         if (registrar3 != null) {
167             node3.stop(registrar3.getRef());
168         }
169     }
170
171     /**
172      * One node cluster. 1. Register rpc, ensure router can be found 2. Then remove rpc, ensure its
173      * deleted
174      */
175     @Test
176     public void testAddRemoveRpcOnSameNode() {
177         LOG.info("testAddRemoveRpcOnSameNode starting");
178
179         Address nodeAddress = node1.provider().getDefaultAddress();
180
181         // Add rpc on node 1
182
183         List<DOMRpcIdentifier> addedRouteIds = createRouteIds();
184
185         registry1.tell(new AddOrUpdateRoutes(addedRouteIds), ActorRef.noSender());
186
187         // Bucket store should get an update bucket message. Updated bucket contains added rpc.
188         final TestKit testKit = new TestKit(node1);
189
190         Map<Address, Bucket<RoutingTable>> buckets = retrieveBuckets(registry1, testKit, nodeAddress);
191         verifyBucket(buckets.get(nodeAddress), addedRouteIds);
192
193         Map<Address, Long> versions = retrieveVersions(registry1, testKit);
194         assertEquals("Version for bucket " + nodeAddress, (Long) buckets.get(nodeAddress).getVersion(),
195                 versions.get(nodeAddress));
196
197         // Now remove rpc
198         registry1.tell(new RemoveRoutes(addedRouteIds), ActorRef.noSender());
199
200         // Bucket store should get an update bucket message. Rpc is removed in the updated bucket
201
202         verifyEmptyBucket(testKit, registry1, nodeAddress);
203
204         LOG.info("testAddRemoveRpcOnSameNode ending");
205
206     }
207
208     /**
209      * Three node cluster. 1. Register rpc on 1 node, ensure 2nd node gets updated 2. Remove rpc on
210      * 1 node, ensure 2nd node gets updated
211      */
212     @Test
213     public void testRpcAddRemoveInCluster() {
214
215         LOG.info("testRpcAddRemoveInCluster starting");
216
217         List<DOMRpcIdentifier> addedRouteIds = createRouteIds();
218
219         Address node1Address = node1.provider().getDefaultAddress();
220
221         // Add rpc on node 1
222         registry1.tell(new AddOrUpdateRoutes(addedRouteIds), ActorRef.noSender());
223
224         // Bucket store on node2 should get a message to update its local copy of remote buckets
225         final TestKit testKit = new TestKit(node2);
226
227         Map<Address, Bucket<RoutingTable>> buckets = retrieveBuckets(registry2, testKit, node1Address);
228         verifyBucket(buckets.get(node1Address), addedRouteIds);
229
230         // Now remove
231         registry1.tell(new RemoveRoutes(addedRouteIds), ActorRef.noSender());
232
233         // Bucket store on node2 should get a message to update its local copy of remote buckets.
234         // Wait for the bucket for node1 to be empty.
235
236         verifyEmptyBucket(testKit, registry2, node1Address);
237
238         LOG.info("testRpcAddRemoveInCluster ending");
239     }
240
241     private void verifyEmptyBucket(final TestKit testKit, final ActorRef registry, final Address address)
242             throws AssertionError {
243         Map<Address, Bucket<RoutingTable>> buckets;
244         int numTries = 0;
245         while (true) {
246             buckets = retrieveBuckets(registry1, testKit, address);
247
248             try {
249                 verifyBucket(buckets.get(address), Collections.emptyList());
250                 break;
251             } catch (AssertionError e) {
252                 if (++numTries >= 50) {
253                     throw e;
254                 }
255             }
256
257             Uninterruptibles.sleepUninterruptibly(200, TimeUnit.MILLISECONDS);
258         }
259     }
260
261     /**
262      * Three node cluster. Register rpc on 2 nodes. Ensure 3rd gets updated.
263      */
264     @Test
265     public void testRpcAddedOnMultiNodes() {
266         final TestKit testKit = new TestKit(node3);
267
268         // Add rpc on node 1
269         List<DOMRpcIdentifier> addedRouteIds1 = createRouteIds();
270         registry1.tell(new AddOrUpdateRoutes(addedRouteIds1), ActorRef.noSender());
271
272         final UpdateRemoteEndpoints req1 = registrar3.expectMsgClass(Duration.ofSeconds(3),
273             UpdateRemoteEndpoints.class);
274
275         // Add rpc on node 2
276         List<DOMRpcIdentifier> addedRouteIds2 = createRouteIds();
277         registry2.tell(new AddOrUpdateRoutes(addedRouteIds2), ActorRef.noSender());
278
279         final UpdateRemoteEndpoints req2 = registrar3.expectMsgClass(Duration.ofSeconds(3),
280             UpdateRemoteEndpoints.class);
281         Address node2Address = node2.provider().getDefaultAddress();
282         Address node1Address = node1.provider().getDefaultAddress();
283
284         Map<Address, Bucket<RoutingTable>> buckets = retrieveBuckets(registry3, testKit, node1Address,
285                 node2Address);
286
287         verifyBucket(buckets.get(node1Address), addedRouteIds1);
288         verifyBucket(buckets.get(node2Address), addedRouteIds2);
289
290         Map<Address, Long> versions = retrieveVersions(registry3, testKit);
291         assertEquals("Version for bucket " + node1Address, (Long) buckets.get(node1Address).getVersion(),
292                 versions.get(node1Address));
293         assertEquals("Version for bucket " + node2Address, (Long) buckets.get(node2Address).getVersion(),
294                 versions.get(node2Address));
295
296         assertEndpoints(req1, node1Address, invoker1);
297         assertEndpoints(req2, node2Address, invoker2);
298
299     }
300
301     private static void assertEndpoints(final UpdateRemoteEndpoints msg, final Address address, final TestKit invoker) {
302         final Map<Address, Optional<RemoteRpcEndpoint>> endpoints = msg.getRpcEndpoints();
303         assertEquals(1, endpoints.size());
304
305         final Optional<RemoteRpcEndpoint> maybeEndpoint = endpoints.get(address);
306         assertNotNull(maybeEndpoint);
307         assertTrue(maybeEndpoint.isPresent());
308
309         final RemoteRpcEndpoint endpoint = maybeEndpoint.get();
310         final ActorRef router = endpoint.getRouter();
311         assertNotNull(router);
312
313         router.tell("hello", ActorRef.noSender());
314         final String s = invoker.expectMsgClass(Duration.ofSeconds(3), String.class);
315         assertEquals("hello", s);
316     }
317
318     private static Map<Address, Long> retrieveVersions(final ActorRef bucketStore, final TestKit testKit) {
319         bucketStore.tell(GET_BUCKET_VERSIONS, testKit.getRef());
320         @SuppressWarnings("unchecked")
321         final Map<Address, Long> reply = testKit.expectMsgClass(Duration.ofSeconds(3), Map.class);
322         return reply;
323     }
324
325     private static void verifyBucket(final Bucket<RoutingTable> bucket, final List<DOMRpcIdentifier> expRouteIds) {
326         RoutingTable table = bucket.getData();
327         assertNotNull("Bucket RoutingTable is null", table);
328         for (DOMRpcIdentifier r : expRouteIds) {
329             if (!table.contains(r)) {
330                 fail("RoutingTable does not contain " + r + ". Actual: " + table);
331             }
332         }
333
334         assertEquals("RoutingTable size", expRouteIds.size(), table.size());
335     }
336
337     private static Map<Address, Bucket<RoutingTable>> retrieveBuckets(final ActorRef bucketStore,
338             final TestKit testKit, final Address... addresses) {
339         int numTries = 0;
340         while (true) {
341             bucketStore.tell(GET_ALL_BUCKETS, testKit.getRef());
342             @SuppressWarnings("unchecked")
343             Map<Address, Bucket<RoutingTable>> buckets = testKit.expectMsgClass(Duration.ofSeconds(3), Map.class);
344
345             boolean foundAll = true;
346             for (Address addr : addresses) {
347                 Bucket<RoutingTable> bucket = buckets.get(addr);
348                 if (bucket == null) {
349                     foundAll = false;
350                     break;
351                 }
352             }
353
354             if (foundAll) {
355                 return buckets;
356             }
357
358             if (++numTries >= 50) {
359                 fail("Missing expected buckets for addresses: " + Arrays.toString(addresses) + ", Actual: " + buckets);
360             }
361
362             Uninterruptibles.sleepUninterruptibly(200, TimeUnit.MILLISECONDS);
363         }
364     }
365
366     @Test
367     public void testAddRoutesConcurrency() {
368         final TestKit testKit = new TestKit(node1);
369
370         final int nRoutes = 500;
371         final Collection<DOMRpcIdentifier> added = new ArrayList<>(nRoutes);
372         for (int i = 0; i < nRoutes; i++) {
373             final DOMRpcIdentifier routeId = DOMRpcIdentifier.create(SchemaPath.create(true,
374                     QName.create(URI.create("/mockrpc"), "type" + i)));
375             added.add(routeId);
376
377             //Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
378             registry1.tell(new AddOrUpdateRoutes(Arrays.asList(routeId)),
379                     ActorRef.noSender());
380         }
381
382         int numTries = 0;
383         while (true) {
384             registry1.tell(GET_ALL_BUCKETS, testKit.getRef());
385             @SuppressWarnings("unchecked")
386             Map<Address, Bucket<RoutingTable>> buckets = testKit.expectMsgClass(Duration.ofSeconds(3), Map.class);
387
388             Bucket<RoutingTable> localBucket = buckets.values().iterator().next();
389             RoutingTable table = localBucket.getData();
390             if (table != null && table.size() == nRoutes) {
391                 for (DOMRpcIdentifier r : added) {
392                     assertTrue("RoutingTable contains " + r, table.contains(r));
393                 }
394
395                 break;
396             }
397
398             if (++numTries >= 50) {
399                 fail("Expected # routes: " + nRoutes + ", Actual: " + table.size());
400             }
401
402             Uninterruptibles.sleepUninterruptibly(200, TimeUnit.MILLISECONDS);
403         }
404     }
405
406     private List<DOMRpcIdentifier> createRouteIds() {
407         QName type = QName.create(URI.create("/mockrpc"), "mockrpc" + routeIdCounter++);
408         List<DOMRpcIdentifier> routeIds = new ArrayList<>(1);
409         routeIds.add(DOMRpcIdentifier.create(SchemaPath.create(true, type)));
410         return routeIds;
411     }
412 }

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