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