blob: e77cf41bfa8d61a5fb295363be153e5876c23eb0 [file] [log] [blame]
Thomas Vachuska58de4162015-09-10 16:15:33 -07001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2015-present Open Networking Laboratory
Thomas Vachuska58de4162015-09-10 16:15:33 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Madan Jampani6cc224b2015-04-20 16:56:00 -070016package org.onosproject.messagingperf;
17
18import static com.google.common.base.Strings.isNullOrEmpty;
19import static org.apache.felix.scr.annotations.ReferenceCardinality.MANDATORY_UNARY;
20import static org.onlab.util.Tools.get;
21import static org.onlab.util.Tools.groupedThreads;
22import static org.slf4j.LoggerFactory.getLogger;
23
24import java.util.Dictionary;
25import java.util.List;
26import java.util.Objects;
27import java.util.Set;
28import java.util.concurrent.CompletableFuture;
29import java.util.concurrent.Executor;
30import java.util.concurrent.ExecutorService;
31import java.util.concurrent.Executors;
32import java.util.concurrent.ScheduledExecutorService;
33import java.util.concurrent.TimeUnit;
34import java.util.concurrent.atomic.AtomicInteger;
35import java.util.function.Function;
36import java.util.stream.IntStream;
37
38import org.apache.felix.scr.annotations.Activate;
39import org.apache.felix.scr.annotations.Component;
40import org.apache.felix.scr.annotations.Deactivate;
41import org.apache.felix.scr.annotations.Modified;
42import org.apache.felix.scr.annotations.Property;
43import org.apache.felix.scr.annotations.Reference;
44import org.apache.felix.scr.annotations.ReferenceCardinality;
45import org.apache.felix.scr.annotations.Service;
46import org.onlab.util.BoundedThreadPool;
47import org.onlab.util.KryoNamespace;
48import org.onosproject.cfg.ComponentConfigService;
49import org.onosproject.cluster.ClusterService;
50import org.onosproject.cluster.NodeId;
51import org.onosproject.core.CoreService;
52import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
53import org.onosproject.store.cluster.messaging.MessageSubject;
54import org.onosproject.store.serializers.KryoNamespaces;
55import org.onosproject.store.serializers.KryoSerializer;
56import org.osgi.service.component.ComponentContext;
57import org.slf4j.Logger;
58
59import com.google.common.collect.ImmutableList;
60import com.google.common.collect.ImmutableSet;
61import com.google.common.collect.Lists;
62import com.google.common.collect.Sets;
63import com.google.common.util.concurrent.MoreExecutors;
64
65/**
66 * Application for measuring cluster messaging performance.
67 */
68@Component(immediate = true, enabled = true)
69@Service(value = MessagingPerfApp.class)
70public class MessagingPerfApp {
71 private final Logger log = getLogger(getClass());
72
73 @Reference(cardinality = MANDATORY_UNARY)
74 protected ClusterService clusterService;
75
76 @Reference(cardinality = MANDATORY_UNARY)
77 protected ClusterCommunicationService communicationService;
78
79 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
80 protected CoreService coreService;
81
82 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
83 protected ComponentConfigService configService;
84
85 private static final MessageSubject TEST_UNICAST_MESSAGE_TOPIC =
86 new MessageSubject("net-perf-unicast-message");
87
88 private static final MessageSubject TEST_REQUEST_REPLY_TOPIC =
89 new MessageSubject("net-perf-rr-message");
90
91 private static final int DEFAULT_SENDER_THREAD_POOL_SIZE = 2;
92 private static final int DEFAULT_RECEIVER_THREAD_POOL_SIZE = 2;
93
94 @Property(name = "totalSenderThreads", intValue = DEFAULT_SENDER_THREAD_POOL_SIZE,
95 label = "Number of sender threads")
96 protected int totalSenderThreads = DEFAULT_SENDER_THREAD_POOL_SIZE;
97
98 @Property(name = "totalReceiverThreads", intValue = DEFAULT_RECEIVER_THREAD_POOL_SIZE,
99 label = "Number of receiver threads")
100 protected int totalReceiverThreads = DEFAULT_RECEIVER_THREAD_POOL_SIZE;
101
102 @Property(name = "serializationOn", boolValue = true,
103 label = "Turn serialization on/off")
104 private boolean serializationOn = true;
105
106 @Property(name = "receiveOnIOLoopThread", boolValue = false,
107 label = "Set this to true to handle message on IO thread")
108 private boolean receiveOnIOLoopThread = false;
109
110 protected int reportIntervalSeconds = 1;
111
112 private Executor messageReceivingExecutor;
113
114 private ExecutorService messageSendingExecutor =
115 BoundedThreadPool.newFixedThreadPool(totalSenderThreads,
116 groupedThreads("onos/messaging-perf-test", "sender-%d"));
117
118 private final ScheduledExecutorService reporter =
119 Executors.newSingleThreadScheduledExecutor(
120 groupedThreads("onos/net-perf-test", "reporter"));
121
122 private AtomicInteger received = new AtomicInteger(0);
123 private AtomicInteger sent = new AtomicInteger(0);
124 private AtomicInteger attempted = new AtomicInteger(0);
125 private AtomicInteger completed = new AtomicInteger(0);
126
127 protected static final KryoSerializer SERIALIZER = new KryoSerializer() {
128 @Override
129 protected void setupKryoPool() {
130 serializerPool = KryoNamespace.newBuilder()
131 .register(KryoNamespaces.BASIC)
132 .register(KryoNamespaces.MISC)
133 .register(byte[].class)
134 .register(Data.class)
135 .build();
136 }
137 };
138
139 private final Data data = new Data().withStringField("test")
140 .withListField(Lists.newArrayList("1", "2", "3"))
141 .withSetField(Sets.newHashSet("1", "2", "3"));
142 private final byte[] dataBytes = SERIALIZER.encode(new Data().withStringField("test")
143 .withListField(Lists.newArrayList("1", "2", "3"))
144 .withSetField(Sets.newHashSet("1", "2", "3")));
145
146 private Function<Data, byte[]> encoder;
147 private Function<byte[], Data> decoder;
148
149 @Activate
150 public void activate(ComponentContext context) {
151 configService.registerProperties(getClass());
152 setupCodecs();
153 messageReceivingExecutor = receiveOnIOLoopThread
154 ? MoreExecutors.directExecutor()
155 : Executors.newFixedThreadPool(
156 totalReceiverThreads,
157 groupedThreads("onos/net-perf-test", "receiver-%d"));
158 registerMessageHandlers();
159 startTest();
160 reporter.scheduleWithFixedDelay(this::reportPerformance,
161 reportIntervalSeconds,
162 reportIntervalSeconds,
163 TimeUnit.SECONDS);
164 logConfig("Started");
165 }
166
167 @Deactivate
168 public void deactivate(ComponentContext context) {
169 configService.unregisterProperties(getClass(), false);
170 stopTest();
171 reporter.shutdown();
172 unregisterMessageHandlers();
173 log.info("Stopped.");
174 }
175
176 @Modified
177 public void modified(ComponentContext context) {
178 if (context == null) {
179 totalSenderThreads = DEFAULT_SENDER_THREAD_POOL_SIZE;
180 totalReceiverThreads = DEFAULT_RECEIVER_THREAD_POOL_SIZE;
181 serializationOn = true;
182 receiveOnIOLoopThread = false;
183 return;
184 }
185
186 Dictionary properties = context.getProperties();
187
188 int newTotalSenderThreads = totalSenderThreads;
189 int newTotalReceiverThreads = totalReceiverThreads;
190 boolean newSerializationOn = serializationOn;
191 boolean newReceiveOnIOLoopThread = receiveOnIOLoopThread;
192 try {
193 String s = get(properties, "totalSenderThreads");
194 newTotalSenderThreads = isNullOrEmpty(s)
195 ? totalSenderThreads : Integer.parseInt(s.trim());
196
197 s = get(properties, "totalReceiverThreads");
198 newTotalReceiverThreads = isNullOrEmpty(s)
199 ? totalReceiverThreads : Integer.parseInt(s.trim());
200
201 s = get(properties, "serializationOn");
202 newSerializationOn = isNullOrEmpty(s)
203 ? serializationOn : Boolean.parseBoolean(s.trim());
204
205 s = get(properties, "receiveOnIOLoopThread");
206 newReceiveOnIOLoopThread = isNullOrEmpty(s)
207 ? receiveOnIOLoopThread : Boolean.parseBoolean(s.trim());
208
209 } catch (NumberFormatException | ClassCastException e) {
210 return;
211 }
212
213 boolean modified = newTotalSenderThreads != totalSenderThreads ||
214 newTotalReceiverThreads != totalReceiverThreads ||
215 newSerializationOn != serializationOn ||
216 newReceiveOnIOLoopThread != receiveOnIOLoopThread;
217
218 // If nothing has changed, simply return.
219 if (!modified) {
220 return;
221 }
222
223 totalSenderThreads = newTotalSenderThreads;
224 totalReceiverThreads = newTotalReceiverThreads;
225 serializationOn = newSerializationOn;
226 if (!receiveOnIOLoopThread && newReceiveOnIOLoopThread != receiveOnIOLoopThread) {
227 ((ExecutorService) messageReceivingExecutor).shutdown();
228 }
229 receiveOnIOLoopThread = newReceiveOnIOLoopThread;
230
231 // restart test.
232
233 stopTest();
234 unregisterMessageHandlers();
235 setupCodecs();
236 messageSendingExecutor =
237 BoundedThreadPool.newFixedThreadPool(
238 totalSenderThreads,
239 groupedThreads("onos/net-perf-test", "sender-%d"));
240 messageReceivingExecutor = receiveOnIOLoopThread
241 ? MoreExecutors.directExecutor()
242 : Executors.newFixedThreadPool(
243 totalReceiverThreads,
244 groupedThreads("onos/net-perf-test", "receiver-%d"));
245
246 registerMessageHandlers();
247 startTest();
248
249 logConfig("Reconfigured");
250 }
251
252
253 private void logConfig(String prefix) {
254 log.info("{} with senderThreadPoolSize = {}; receivingThreadPoolSize = {}"
255 + " serializationOn = {}, receiveOnIOLoopThread = {}",
256 prefix,
257 totalSenderThreads,
258 totalReceiverThreads,
259 serializationOn,
260 receiveOnIOLoopThread);
261 }
262
263 private void setupCodecs() {
264 encoder = serializationOn ? SERIALIZER::encode : d -> dataBytes;
265 decoder = serializationOn ? SERIALIZER::decode : b -> data;
266 }
267
268 private void registerMessageHandlers() {
269 communicationService.<Data>addSubscriber(
270 TEST_UNICAST_MESSAGE_TOPIC,
271 decoder,
272 d -> { received.incrementAndGet(); },
273 messageReceivingExecutor);
274
275 communicationService.<Data, Data>addSubscriber(
276 TEST_REQUEST_REPLY_TOPIC,
277 decoder,
278 Function.identity(),
279 encoder,
280 messageReceivingExecutor);
281 }
282
283 private void unregisterMessageHandlers() {
284 communicationService.removeSubscriber(TEST_UNICAST_MESSAGE_TOPIC);
285 communicationService.removeSubscriber(TEST_REQUEST_REPLY_TOPIC);
286 }
287
288 private void startTest() {
289 IntStream.range(0, totalSenderThreads).forEach(i -> requestReply());
290 }
291
292 private void stopTest() {
293 messageSendingExecutor.shutdown();
294 }
295
296 private void requestReply() {
297 try {
298 attempted.incrementAndGet();
299 CompletableFuture<Data> response =
300 communicationService.<Data, Data>sendAndReceive(
301 data,
302 TEST_REQUEST_REPLY_TOPIC,
303 encoder,
304 decoder,
305 randomPeer());
306 response.whenComplete((result, error) -> {
307 if (Objects.equals(data, result)) {
308 completed.incrementAndGet();
309 }
310 messageSendingExecutor.submit(this::requestReply);
311 });
312 } catch (Exception e) {
Ray Milkey4fd3ceb2015-12-10 14:43:08 -0800313 log.info("requestReply()", e);
Madan Jampani6cc224b2015-04-20 16:56:00 -0700314 }
315 }
316
317 private void unicast() {
318 try {
319 sent.incrementAndGet();
320 communicationService.<Data>unicast(
321 data,
322 TEST_UNICAST_MESSAGE_TOPIC,
323 encoder,
324 randomPeer());
325 } catch (Exception e) {
Ray Milkey4fd3ceb2015-12-10 14:43:08 -0800326 log.info("unicast()", e);
Madan Jampani6cc224b2015-04-20 16:56:00 -0700327 }
328 messageSendingExecutor.submit(this::unicast);
329 }
330
331 private void broadcast() {
332 try {
333 sent.incrementAndGet();
334 communicationService.<Data>broadcast(
335 data,
336 TEST_UNICAST_MESSAGE_TOPIC,
337 encoder);
338 } catch (Exception e) {
Ray Milkey4fd3ceb2015-12-10 14:43:08 -0800339 log.info("broadcast()", e);
Madan Jampani6cc224b2015-04-20 16:56:00 -0700340 }
341 messageSendingExecutor.submit(this::broadcast);
342 }
343
344 private NodeId randomPeer() {
345 return clusterService.getNodes()
346 .stream()
347 .filter(node -> clusterService.getLocalNode().equals(node))
348 .findAny()
349 .get()
350 .id();
351 }
352
353 private void reportPerformance() {
354 log.info("Attempted: {} Completed: {}", attempted.getAndSet(0), completed.getAndSet(0));
355 }
356
357 private static class Data {
358 private String stringField;
359 private List<String> listField;
360 private Set<String> setField;
361
362 public Data withStringField(String value) {
363 stringField = value;
364 return this;
365 }
366
367 public Data withListField(List<String> value) {
368 listField = ImmutableList.copyOf(value);
369 return this;
370 }
371
372 public Data withSetField(Set<String> value) {
373 setField = ImmutableSet.copyOf(value);
374 return this;
375 }
376
377 @Override
378 public int hashCode() {
379 return Objects.hash(stringField, listField, setField);
380 }
381
382 @Override
383 public boolean equals(Object other) {
384 if (other instanceof Data) {
385 Data that = (Data) other;
386 return Objects.equals(this.stringField, that.stringField) &&
387 Objects.equals(this.listField, that.listField) &&
388 Objects.equals(this.setField, that.setField);
389 }
390 return false;
391 }
392 }
393}