Improve segmented journal actor metrics
[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.time.Duration;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.Collection;
34 import java.util.Collections;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Optional;
38 import java.util.Set;
39 import java.util.concurrent.TimeUnit;
40 import org.junit.After;
41 import org.junit.AfterClass;
42 import org.junit.Before;
43 import org.junit.BeforeClass;
44 import org.junit.Test;
45 import org.opendaylight.controller.cluster.common.actor.AkkaConfigurationReader;
46 import org.opendaylight.controller.remote.rpc.RemoteOpsProviderConfig;
47 import org.opendaylight.controller.remote.rpc.registry.ActionRegistry.Messages.UpdateActions;
48 import org.opendaylight.controller.remote.rpc.registry.ActionRegistry.Messages.UpdateRemoteActionEndpoints;
49 import org.opendaylight.controller.remote.rpc.registry.ActionRegistry.RemoteActionEndpoint;
50 import org.opendaylight.controller.remote.rpc.registry.gossip.Bucket;
51 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
52 import org.opendaylight.mdsal.dom.api.DOMActionInstance;
53 import org.opendaylight.yangtools.yang.common.QName;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
55 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 public class ActionRegistryTest {
60     private static final Logger LOG = LoggerFactory.getLogger(ActionRegistryTest.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(ActionRegistry.props(config(node1), invoker1.getRef(), registrar1.getRef()));
126         invoker2 = new TestKit(node2);
127         registrar2 = new TestKit(node2);
128         registry2 = node2.actorOf(ActionRegistry.props(config(node2), invoker2.getRef(), registrar2.getRef()));
129         invoker3 = new TestKit(node3);
130         registrar3 = new TestKit(node3);
131         registry3 = node3.actorOf(ActionRegistry.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 action, ensure router can be found 2. Then remove action, ensure its
173      * deleted
174      */
175     @Test
176     public void testAddRemoveActionOnSameNode() {
177         LOG.info("testAddRemoveActionOnSameNode starting");
178
179         Address nodeAddress = node1.provider().getDefaultAddress();
180
181         // Add action on node 1
182
183         List<DOMActionInstance> addedRouteIds = createRouteIds();
184
185         registry1.tell(new ActionRegistry.Messages.UpdateActions(addedRouteIds,
186                 Collections.emptyList()), ActorRef.noSender());
187
188         // Bucket store should get an update bucket message. Updated bucket contains added action.
189         final TestKit testKit = new TestKit(node1);
190
191         Map<Address, Bucket<ActionRoutingTable>> buckets = retrieveBuckets(registry1, testKit, nodeAddress);
192         verifyBucket(buckets.get(nodeAddress), addedRouteIds);
193
194         Map<Address, Long> versions = retrieveVersions(registry1, testKit);
195         assertEquals("Version for bucket " + nodeAddress, (Long) buckets.get(nodeAddress).getVersion(),
196                 versions.get(nodeAddress));
197
198         // Now remove action
199         registry1.tell(new UpdateActions(Collections.emptyList(),addedRouteIds), ActorRef.noSender());
200
201         // Bucket store should get an update bucket message. Action is removed in the updated bucket
202
203         verifyEmptyBucket(testKit, registry1, nodeAddress);
204
205         LOG.info("testAddRemoveActionOnSameNode ending");
206
207     }
208
209     /**
210      * Three node cluster. 1. Register action on 1 node, ensure 2nd node gets updated 2. Remove action on
211      * 1 node, ensure 2nd node gets updated
212      */
213     @Test
214     public void testActionAddRemoveInCluster() {
215
216         LOG.info("testActionAddRemoveInCluster starting");
217
218         List<DOMActionInstance> addedRouteIds = createRouteIds();
219
220         Address node1Address = node1.provider().getDefaultAddress();
221
222         // Add action on node 1
223         registry1.tell(new UpdateActions(addedRouteIds, Collections.emptyList()), ActorRef.noSender());
224
225         // Bucket store on node2 should get a message to update its local copy of remote buckets
226         final TestKit testKit = new TestKit(node2);
227
228         Map<Address, Bucket<ActionRoutingTable>> buckets = retrieveBuckets(registry2, testKit, node1Address);
229         verifyBucket(buckets.get(node1Address), addedRouteIds);
230
231         // Now remove
232         registry1.tell(new UpdateActions(Collections.emptyList(), addedRouteIds), ActorRef.noSender());
233
234         // Bucket store on node2 should get a message to update its local copy of remote buckets.
235         // Wait for the bucket for node1 to be empty.
236
237         verifyEmptyBucket(testKit, registry2, node1Address);
238
239         LOG.info("testActionAddRemoveInCluster ending");
240     }
241
242     private void verifyEmptyBucket(final TestKit testKit, final ActorRef registry, final Address address)
243             throws AssertionError {
244         Map<Address, Bucket<ActionRoutingTable>> buckets;
245         int numTries = 0;
246         while (true) {
247             buckets = retrieveBuckets(registry1, testKit, address);
248
249             try {
250                 verifyBucket(buckets.get(address), Collections.emptyList());
251                 break;
252             } catch (AssertionError e) {
253                 if (++numTries >= 50) {
254                     throw e;
255                 }
256             }
257
258             Uninterruptibles.sleepUninterruptibly(200, TimeUnit.MILLISECONDS);
259         }
260     }
261
262     /**
263      * Three node cluster. Register action on 2 nodes. Ensure 3rd gets updated.
264      */
265     @Test
266     public void testActionAddedOnMultiNodes() {
267         final TestKit testKit = new TestKit(node3);
268
269         // Add action on node 1
270         List<DOMActionInstance> addedRouteIds1 = createRouteIds();
271         registry1.tell(new UpdateActions(addedRouteIds1, Collections.emptyList()), ActorRef.noSender());
272
273         final UpdateRemoteActionEndpoints req1 = registrar3.expectMsgClass(Duration.ofSeconds(3),
274                 UpdateRemoteActionEndpoints.class);
275
276         // Add action on node 2
277         List<DOMActionInstance> addedRouteIds2 = createRouteIds();
278         registry2.tell(new UpdateActions(addedRouteIds2, Collections.emptyList()), ActorRef.noSender());
279
280         final UpdateRemoteActionEndpoints req2 = registrar3.expectMsgClass(Duration.ofSeconds(3),
281                 UpdateRemoteActionEndpoints.class);
282         Address node2Address = node2.provider().getDefaultAddress();
283         Address node1Address = node1.provider().getDefaultAddress();
284
285         Map<Address, Bucket<ActionRoutingTable>> buckets = retrieveBuckets(registry3, testKit, node1Address,
286                 node2Address);
287
288         verifyBucket(buckets.get(node1Address), addedRouteIds1);
289         verifyBucket(buckets.get(node2Address), addedRouteIds2);
290
291         Map<Address, Long> versions = retrieveVersions(registry3, testKit);
292         assertEquals("Version for bucket " + node1Address, (Long) buckets.get(node1Address).getVersion(),
293                 versions.get(node1Address));
294         assertEquals("Version for bucket " + node2Address, (Long) buckets.get(node2Address).getVersion(),
295                 versions.get(node2Address));
296
297         assertEndpoints(req1, node1Address, invoker1);
298         assertEndpoints(req2, node2Address, invoker2);
299
300     }
301
302     private static void assertEndpoints(final ActionRegistry.Messages.UpdateRemoteActionEndpoints msg,
303                                         final Address address, final TestKit invoker) {
304         final Map<Address, Optional<RemoteActionEndpoint>> endpoints = msg.getActionEndpoints();
305         assertEquals(1, endpoints.size());
306
307         final Optional<RemoteActionEndpoint> maybeEndpoint = endpoints.get(address);
308         assertNotNull(maybeEndpoint);
309         assertTrue(maybeEndpoint.isPresent());
310
311         final RemoteActionEndpoint endpoint = maybeEndpoint.orElseThrow();
312         final ActorRef router = endpoint.getRouter();
313         assertNotNull(router);
314
315         router.tell("hello", ActorRef.noSender());
316         final String s = invoker.expectMsgClass(Duration.ofSeconds(3), String.class);
317         assertEquals("hello", s);
318     }
319
320     private static Map<Address, Long> retrieveVersions(final ActorRef bucketStore, final TestKit testKit) {
321         bucketStore.tell(GET_BUCKET_VERSIONS, testKit.getRef());
322         @SuppressWarnings("unchecked")
323         final Map<Address, Long> reply = testKit.expectMsgClass(Duration.ofSeconds(3), Map.class);
324         return reply;
325     }
326
327     private static void verifyBucket(final Bucket<ActionRoutingTable> bucket,
328                                      final List<DOMActionInstance> expRouteIds) {
329         ActionRoutingTable table = bucket.getData();
330         assertNotNull("Bucket ActionRoutingTable is null", table);
331         for (DOMActionInstance r : expRouteIds) {
332             if (!table.contains(r)) {
333                 fail("ActionRoutingTable does not contain " + r + ". Actual: " + table);
334             }
335         }
336
337         assertEquals("ActionRoutingTable size", expRouteIds.size(), table.size());
338     }
339
340     private static Map<Address, Bucket<ActionRoutingTable>> retrieveBuckets(
341             final ActorRef bucketStore, final TestKit testKit, final Address... addresses) {
342         int numTries = 0;
343         while (true) {
344             bucketStore.tell(GET_ALL_BUCKETS, testKit.getRef());
345             @SuppressWarnings("unchecked")
346             Map<Address, Bucket<ActionRoutingTable>> buckets = testKit.expectMsgClass(Duration.ofSeconds(3),
347                     Map.class);
348
349             boolean foundAll = true;
350             for (Address addr : addresses) {
351                 Bucket<ActionRoutingTable> bucket = buckets.get(addr);
352                 if (bucket == null) {
353                     foundAll = false;
354                     break;
355                 }
356             }
357
358             if (foundAll) {
359                 return buckets;
360             }
361
362             if (++numTries >= 50) {
363                 fail("Missing expected buckets for addresses: " + Arrays.toString(addresses)
364                         + ", Actual: " + buckets);
365             }
366
367             Uninterruptibles.sleepUninterruptibly(200, TimeUnit.MILLISECONDS);
368         }
369     }
370
371     @Test
372     public void testAddRoutesConcurrency() {
373         final TestKit testKit = new TestKit(node1);
374
375         final int nRoutes = 500;
376         final Collection<DOMActionInstance> added = new ArrayList<>(nRoutes);
377         for (int i = 0; i < nRoutes; i++) {
378             QName type = QName.create("/mockaction", "mockaction" + routeIdCounter++);
379             final DOMActionInstance routeId = DOMActionInstance.of(Absolute.of(type), LogicalDatastoreType.OPERATIONAL,
380                     YangInstanceIdentifier.of(type));
381             added.add(routeId);
382
383             //Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
384             registry1.tell(new UpdateActions(Arrays.asList(routeId), Collections.emptyList()),
385                     ActorRef.noSender());
386         }
387
388         int numTries = 0;
389         while (true) {
390             registry1.tell(GET_ALL_BUCKETS, testKit.getRef());
391             @SuppressWarnings("unchecked")
392             Map<Address, Bucket<ActionRoutingTable>> buckets = testKit.expectMsgClass(Duration.ofSeconds(3),
393                     Map.class);
394
395             Bucket<ActionRoutingTable> localBucket = buckets.values().iterator().next();
396             ActionRoutingTable table = localBucket.getData();
397             if (table != null && table.size() == nRoutes) {
398                 for (DOMActionInstance r : added) {
399                     assertTrue("ActionRoutingTable contains " + r, table.contains(r));
400                 }
401
402                 break;
403             }
404
405             if (++numTries >= 50) {
406                 fail("Expected # routes: " + nRoutes + ", Actual: " + table.size());
407             }
408
409             Uninterruptibles.sleepUninterruptibly(200, TimeUnit.MILLISECONDS);
410         }
411     }
412
413     private List<DOMActionInstance> createRouteIds() {
414         QName type = QName.create("/mockaction", "mockaction" + routeIdCounter++);
415         var routeIds = new ArrayList<DOMActionInstance>(1);
416         routeIds.add(DOMActionInstance.of(Absolute.of(type), LogicalDatastoreType.OPERATIONAL,
417             YangInstanceIdentifier.of(type)));
418         return routeIds;
419     }
420 }