1 package org.onosproject.messagingperf;
3 import static com.google.common.base.Strings.isNullOrEmpty;
4 import static org.apache.felix.scr.annotations.ReferenceCardinality.MANDATORY_UNARY;
5 import static org.onlab.util.Tools.get;
6 import static org.onlab.util.Tools.groupedThreads;
7 import static org.slf4j.LoggerFactory.getLogger;
9 import java.util.Dictionary;
10 import java.util.List;
11 import java.util.Objects;
13 import java.util.concurrent.CompletableFuture;
14 import java.util.concurrent.Executor;
15 import java.util.concurrent.ExecutorService;
16 import java.util.concurrent.Executors;
17 import java.util.concurrent.ScheduledExecutorService;
18 import java.util.concurrent.TimeUnit;
19 import java.util.concurrent.atomic.AtomicInteger;
20 import java.util.function.Function;
21 import java.util.stream.IntStream;
23 import org.apache.felix.scr.annotations.Activate;
24 import org.apache.felix.scr.annotations.Component;
25 import org.apache.felix.scr.annotations.Deactivate;
26 import org.apache.felix.scr.annotations.Modified;
27 import org.apache.felix.scr.annotations.Property;
28 import org.apache.felix.scr.annotations.Reference;
29 import org.apache.felix.scr.annotations.ReferenceCardinality;
30 import org.apache.felix.scr.annotations.Service;
31 import org.onlab.util.BoundedThreadPool;
32 import org.onlab.util.KryoNamespace;
33 import org.onosproject.cfg.ComponentConfigService;
34 import org.onosproject.cluster.ClusterService;
35 import org.onosproject.cluster.NodeId;
36 import org.onosproject.core.CoreService;
37 import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
38 import org.onosproject.store.cluster.messaging.MessageSubject;
39 import org.onosproject.store.serializers.KryoNamespaces;
40 import org.onosproject.store.serializers.KryoSerializer;
41 import org.osgi.service.component.ComponentContext;
42 import org.slf4j.Logger;
44 import com.google.common.collect.ImmutableList;
45 import com.google.common.collect.ImmutableSet;
46 import com.google.common.collect.Lists;
47 import com.google.common.collect.Sets;
48 import com.google.common.util.concurrent.MoreExecutors;
51 * Application for measuring cluster messaging performance.
53 @Component(immediate = true, enabled = true)
54 @Service(value = MessagingPerfApp.class)
55 public class MessagingPerfApp {
56 private final Logger log = getLogger(getClass());
58 @Reference(cardinality = MANDATORY_UNARY)
59 protected ClusterService clusterService;
61 @Reference(cardinality = MANDATORY_UNARY)
62 protected ClusterCommunicationService communicationService;
64 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
65 protected CoreService coreService;
67 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
68 protected ComponentConfigService configService;
70 private static final MessageSubject TEST_UNICAST_MESSAGE_TOPIC =
71 new MessageSubject("net-perf-unicast-message");
73 private static final MessageSubject TEST_REQUEST_REPLY_TOPIC =
74 new MessageSubject("net-perf-rr-message");
76 private static final int DEFAULT_SENDER_THREAD_POOL_SIZE = 2;
77 private static final int DEFAULT_RECEIVER_THREAD_POOL_SIZE = 2;
79 @Property(name = "totalSenderThreads", intValue = DEFAULT_SENDER_THREAD_POOL_SIZE,
80 label = "Number of sender threads")
81 protected int totalSenderThreads = DEFAULT_SENDER_THREAD_POOL_SIZE;
83 @Property(name = "totalReceiverThreads", intValue = DEFAULT_RECEIVER_THREAD_POOL_SIZE,
84 label = "Number of receiver threads")
85 protected int totalReceiverThreads = DEFAULT_RECEIVER_THREAD_POOL_SIZE;
87 @Property(name = "serializationOn", boolValue = true,
88 label = "Turn serialization on/off")
89 private boolean serializationOn = true;
91 @Property(name = "receiveOnIOLoopThread", boolValue = false,
92 label = "Set this to true to handle message on IO thread")
93 private boolean receiveOnIOLoopThread = false;
95 protected int reportIntervalSeconds = 1;
97 private Executor messageReceivingExecutor;
99 private ExecutorService messageSendingExecutor =
100 BoundedThreadPool.newFixedThreadPool(totalSenderThreads,
101 groupedThreads("onos/messaging-perf-test", "sender-%d"));
103 private final ScheduledExecutorService reporter =
104 Executors.newSingleThreadScheduledExecutor(
105 groupedThreads("onos/net-perf-test", "reporter"));
107 private AtomicInteger received = new AtomicInteger(0);
108 private AtomicInteger sent = new AtomicInteger(0);
109 private AtomicInteger attempted = new AtomicInteger(0);
110 private AtomicInteger completed = new AtomicInteger(0);
112 protected static final KryoSerializer SERIALIZER = new KryoSerializer() {
114 protected void setupKryoPool() {
115 serializerPool = KryoNamespace.newBuilder()
116 .register(KryoNamespaces.BASIC)
117 .register(KryoNamespaces.MISC)
118 .register(byte[].class)
119 .register(Data.class)
124 private final Data data = new Data().withStringField("test")
125 .withListField(Lists.newArrayList("1", "2", "3"))
126 .withSetField(Sets.newHashSet("1", "2", "3"));
127 private final byte[] dataBytes = SERIALIZER.encode(new Data().withStringField("test")
128 .withListField(Lists.newArrayList("1", "2", "3"))
129 .withSetField(Sets.newHashSet("1", "2", "3")));
131 private Function<Data, byte[]> encoder;
132 private Function<byte[], Data> decoder;
135 public void activate(ComponentContext context) {
136 configService.registerProperties(getClass());
138 messageReceivingExecutor = receiveOnIOLoopThread
139 ? MoreExecutors.directExecutor()
140 : Executors.newFixedThreadPool(
141 totalReceiverThreads,
142 groupedThreads("onos/net-perf-test", "receiver-%d"));
143 registerMessageHandlers();
145 reporter.scheduleWithFixedDelay(this::reportPerformance,
146 reportIntervalSeconds,
147 reportIntervalSeconds,
149 logConfig("Started");
153 public void deactivate(ComponentContext context) {
154 configService.unregisterProperties(getClass(), false);
157 unregisterMessageHandlers();
158 log.info("Stopped.");
162 public void modified(ComponentContext context) {
163 if (context == null) {
164 totalSenderThreads = DEFAULT_SENDER_THREAD_POOL_SIZE;
165 totalReceiverThreads = DEFAULT_RECEIVER_THREAD_POOL_SIZE;
166 serializationOn = true;
167 receiveOnIOLoopThread = false;
171 Dictionary properties = context.getProperties();
173 int newTotalSenderThreads = totalSenderThreads;
174 int newTotalReceiverThreads = totalReceiverThreads;
175 boolean newSerializationOn = serializationOn;
176 boolean newReceiveOnIOLoopThread = receiveOnIOLoopThread;
178 String s = get(properties, "totalSenderThreads");
179 newTotalSenderThreads = isNullOrEmpty(s)
180 ? totalSenderThreads : Integer.parseInt(s.trim());
182 s = get(properties, "totalReceiverThreads");
183 newTotalReceiverThreads = isNullOrEmpty(s)
184 ? totalReceiverThreads : Integer.parseInt(s.trim());
186 s = get(properties, "serializationOn");
187 newSerializationOn = isNullOrEmpty(s)
188 ? serializationOn : Boolean.parseBoolean(s.trim());
190 s = get(properties, "receiveOnIOLoopThread");
191 newReceiveOnIOLoopThread = isNullOrEmpty(s)
192 ? receiveOnIOLoopThread : Boolean.parseBoolean(s.trim());
194 } catch (NumberFormatException | ClassCastException e) {
198 boolean modified = newTotalSenderThreads != totalSenderThreads ||
199 newTotalReceiverThreads != totalReceiverThreads ||
200 newSerializationOn != serializationOn ||
201 newReceiveOnIOLoopThread != receiveOnIOLoopThread;
203 // If nothing has changed, simply return.
208 totalSenderThreads = newTotalSenderThreads;
209 totalReceiverThreads = newTotalReceiverThreads;
210 serializationOn = newSerializationOn;
211 if (!receiveOnIOLoopThread && newReceiveOnIOLoopThread != receiveOnIOLoopThread) {
212 ((ExecutorService) messageReceivingExecutor).shutdown();
214 receiveOnIOLoopThread = newReceiveOnIOLoopThread;
219 unregisterMessageHandlers();
221 messageSendingExecutor =
222 BoundedThreadPool.newFixedThreadPool(
224 groupedThreads("onos/net-perf-test", "sender-%d"));
225 messageReceivingExecutor = receiveOnIOLoopThread
226 ? MoreExecutors.directExecutor()
227 : Executors.newFixedThreadPool(
228 totalReceiverThreads,
229 groupedThreads("onos/net-perf-test", "receiver-%d"));
231 registerMessageHandlers();
234 logConfig("Reconfigured");
238 private void logConfig(String prefix) {
239 log.info("{} with senderThreadPoolSize = {}; receivingThreadPoolSize = {}"
240 + " serializationOn = {}, receiveOnIOLoopThread = {}",
243 totalReceiverThreads,
245 receiveOnIOLoopThread);
248 private void setupCodecs() {
249 encoder = serializationOn ? SERIALIZER::encode : d -> dataBytes;
250 decoder = serializationOn ? SERIALIZER::decode : b -> data;
253 private void registerMessageHandlers() {
254 communicationService.<Data>addSubscriber(
255 TEST_UNICAST_MESSAGE_TOPIC,
257 d -> { received.incrementAndGet(); },
258 messageReceivingExecutor);
260 communicationService.<Data, Data>addSubscriber(
261 TEST_REQUEST_REPLY_TOPIC,
265 messageReceivingExecutor);
268 private void unregisterMessageHandlers() {
269 communicationService.removeSubscriber(TEST_UNICAST_MESSAGE_TOPIC);
270 communicationService.removeSubscriber(TEST_REQUEST_REPLY_TOPIC);
273 private void startTest() {
274 IntStream.range(0, totalSenderThreads).forEach(i -> requestReply());
277 private void stopTest() {
278 messageSendingExecutor.shutdown();
281 private void requestReply() {
283 attempted.incrementAndGet();
284 CompletableFuture<Data> response =
285 communicationService.<Data, Data>sendAndReceive(
287 TEST_REQUEST_REPLY_TOPIC,
291 response.whenComplete((result, error) -> {
292 if (Objects.equals(data, result)) {
293 completed.incrementAndGet();
295 messageSendingExecutor.submit(this::requestReply);
297 } catch (Exception e) {
302 private void unicast() {
304 sent.incrementAndGet();
305 communicationService.<Data>unicast(
307 TEST_UNICAST_MESSAGE_TOPIC,
310 } catch (Exception e) {
313 messageSendingExecutor.submit(this::unicast);
316 private void broadcast() {
318 sent.incrementAndGet();
319 communicationService.<Data>broadcast(
321 TEST_UNICAST_MESSAGE_TOPIC,
323 } catch (Exception e) {
326 messageSendingExecutor.submit(this::broadcast);
329 private NodeId randomPeer() {
330 return clusterService.getNodes()
332 .filter(node -> clusterService.getLocalNode().equals(node))
338 private void reportPerformance() {
339 log.info("Attempted: {} Completed: {}", attempted.getAndSet(0), completed.getAndSet(0));
342 private static class Data {
343 private String stringField;
344 private List<String> listField;
345 private Set<String> setField;
347 public Data withStringField(String value) {
352 public Data withListField(List<String> value) {
353 listField = ImmutableList.copyOf(value);
357 public Data withSetField(Set<String> value) {
358 setField = ImmutableSet.copyOf(value);
363 public int hashCode() {
364 return Objects.hash(stringField, listField, setField);
368 public boolean equals(Object other) {
369 if (other instanceof Data) {
370 Data that = (Data) other;
371 return Objects.equals(this.stringField, that.stringField) &&
372 Objects.equals(this.listField, that.listField) &&
373 Objects.equals(this.setField, that.setField);