blob: 1d962d087d7f8a379afa4e61b36d667edb43be64 [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
Ray Milkey34c95902015-04-15 09:47:53 -07002 * Copyright 2014-2015 Open Networking Laboratory
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -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 */
Brian O'Connorabafb502014-12-02 22:26:20 -080016package org.onosproject.store.cluster.messaging.impl;
Madan Jampani890bc352014-10-01 22:35:29 -070017
Aaron Kruglikove2411892016-02-10 18:18:17 -080018import com.google.common.base.Throwables;
Madan Jampani890bc352014-10-01 22:35:29 -070019import org.apache.felix.scr.annotations.Activate;
20import org.apache.felix.scr.annotations.Component;
21import org.apache.felix.scr.annotations.Deactivate;
Madan Jampania5d0d782014-10-07 14:36:00 -070022import org.apache.felix.scr.annotations.Reference;
23import org.apache.felix.scr.annotations.ReferenceCardinality;
Madan Jampani890bc352014-10-01 22:35:29 -070024import org.apache.felix.scr.annotations.Service;
Madan Jampani27b69c62015-05-15 15:49:02 -070025import org.onlab.util.Tools;
Brian O'Connorabafb502014-12-02 22:26:20 -080026import org.onosproject.cluster.ClusterService;
27import org.onosproject.cluster.ControllerNode;
28import org.onosproject.cluster.NodeId;
29import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
30import org.onosproject.store.cluster.messaging.ClusterMessage;
31import org.onosproject.store.cluster.messaging.ClusterMessageHandler;
Madan Jampanic26eede2015-04-16 11:42:16 -070032import org.onosproject.store.cluster.messaging.Endpoint;
Brian O'Connorabafb502014-12-02 22:26:20 -080033import org.onosproject.store.cluster.messaging.MessageSubject;
Madan Jampanic26eede2015-04-16 11:42:16 -070034import org.onosproject.store.cluster.messaging.MessagingService;
Aaron Kruglikov1110b2c2016-02-02 16:24:37 -080035import org.onosproject.utils.MeteringAgent;
Madan Jampani890bc352014-10-01 22:35:29 -070036import org.slf4j.Logger;
37import org.slf4j.LoggerFactory;
38
Madan Jampani2bfa94c2015-04-11 05:03:49 -070039import com.google.common.base.Objects;
Madan Jampanid36def02016-01-13 11:21:56 -080040
Madan Jampani2bfa94c2015-04-11 05:03:49 -070041import java.util.Set;
42import java.util.concurrent.CompletableFuture;
Madan Jampaniec5ae342015-04-13 15:43:10 -070043import java.util.concurrent.Executor;
Madan Jampani2af244a2015-02-22 13:12:01 -080044import java.util.concurrent.ExecutorService;
Madan Jampanid36def02016-01-13 11:21:56 -080045import java.util.function.BiConsumer;
46import java.util.function.BiFunction;
Madan Jampani2bfa94c2015-04-11 05:03:49 -070047import java.util.function.Consumer;
48import java.util.function.Function;
49import java.util.stream.Collectors;
Jonathan Hart7d656f42015-01-27 14:07:23 -080050
51import static com.google.common.base.Preconditions.checkArgument;
Aaron Kruglikov1110b2c2016-02-02 16:24:37 -080052import static com.google.common.base.Preconditions.checkNotNull;
Madan Jampani24f9efb2014-10-24 18:56:23 -070053
Madan Jampani890bc352014-10-01 22:35:29 -070054@Component(immediate = true)
55@Service
Madan Jampani3b0dfd52014-10-02 16:48:13 -070056public class ClusterCommunicationManager
Yuta HIGUCHIbbfc96a2014-10-13 18:05:44 -070057 implements ClusterCommunicationService {
Madan Jampani890bc352014-10-01 22:35:29 -070058
59 private final Logger log = LoggerFactory.getLogger(getClass());
60
Aaron Kruglikov1110b2c2016-02-02 16:24:37 -080061 private final MeteringAgent subjectMeteringAgent = new MeteringAgent(PRIMITIVE_NAME, SUBJECT_PREFIX, true);
62 private final MeteringAgent endpointMeteringAgent = new MeteringAgent(PRIMITIVE_NAME, ENDPOINT_PREFIX, true);
63
64 private static final String PRIMITIVE_NAME = "clusterCommunication";
65 private static final String SUBJECT_PREFIX = "subject";
66 private static final String ENDPOINT_PREFIX = "endpoint";
67
68 private static final String SERIALIZING = "serialization";
69 private static final String DESERIALIZING = "deserialization";
70 private static final String NODE_PREFIX = "node:";
71 private static final String ROUND_TRIP_SUFFIX = ".rtt";
Aaron Kruglikove2411892016-02-10 18:18:17 -080072 private static final String ONE_WAY_SUFFIX = ".oneway";
Aaron Kruglikov1110b2c2016-02-02 16:24:37 -080073
Madan Jampania5d0d782014-10-07 14:36:00 -070074 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
75 private ClusterService clusterService;
76
Madan Jampaniafeebbd2015-05-19 15:26:01 -070077 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
78 protected MessagingService messagingService;
Madan Jampanic26eede2015-04-16 11:42:16 -070079
Madan Jampani175e8fd2015-05-20 14:10:45 -070080 private NodeId localNodeId;
81
Madan Jampani890bc352014-10-01 22:35:29 -070082 @Activate
83 public void activate() {
Madan Jampani175e8fd2015-05-20 14:10:45 -070084 localNodeId = clusterService.getLocalNode().id();
Madan Jampaniafeebbd2015-05-19 15:26:01 -070085 log.info("Started");
Madan Jampani890bc352014-10-01 22:35:29 -070086 }
87
88 @Deactivate
89 public void deactivate() {
Madan Jampani890bc352014-10-01 22:35:29 -070090 log.info("Stopped");
91 }
92
93 @Override
Madan Jampani2bfa94c2015-04-11 05:03:49 -070094 public <M> void broadcast(M message,
95 MessageSubject subject,
96 Function<M, byte[]> encoder) {
97 multicast(message,
98 subject,
99 encoder,
100 clusterService.getNodes()
101 .stream()
102 .filter(node -> !Objects.equal(node, clusterService.getLocalNode()))
103 .map(ControllerNode::id)
104 .collect(Collectors.toSet()));
105 }
106
107 @Override
108 public <M> void broadcastIncludeSelf(M message,
109 MessageSubject subject,
110 Function<M, byte[]> encoder) {
111 multicast(message,
112 subject,
113 encoder,
114 clusterService.getNodes()
115 .stream()
116 .map(ControllerNode::id)
117 .collect(Collectors.toSet()));
118 }
119
120 @Override
Madan Jampani175e8fd2015-05-20 14:10:45 -0700121 public <M> CompletableFuture<Void> unicast(M message,
122 MessageSubject subject,
123 Function<M, byte[]> encoder,
124 NodeId toNodeId) {
125 try {
126 byte[] payload = new ClusterMessage(
127 localNodeId,
128 subject,
Aaron Kruglikov1110b2c2016-02-02 16:24:37 -0800129 timeFunction(encoder, subjectMeteringAgent, SERIALIZING).apply(message)
130 ).getBytes();
Madan Jampani175e8fd2015-05-20 14:10:45 -0700131 return doUnicast(subject, payload, toNodeId);
132 } catch (Exception e) {
133 return Tools.exceptionalFuture(e);
134 }
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700135 }
136
137 @Override
138 public <M> void multicast(M message,
139 MessageSubject subject,
140 Function<M, byte[]> encoder,
141 Set<NodeId> nodes) {
142 byte[] payload = new ClusterMessage(
Madan Jampani175e8fd2015-05-20 14:10:45 -0700143 localNodeId,
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700144 subject,
Aaron Kruglikov1110b2c2016-02-02 16:24:37 -0800145 timeFunction(encoder, subjectMeteringAgent, SERIALIZING).apply(message))
146 .getBytes();
Madan Jampani175e8fd2015-05-20 14:10:45 -0700147 nodes.forEach(nodeId -> doUnicast(subject, payload, nodeId));
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700148 }
149
150 @Override
151 public <M, R> CompletableFuture<R> sendAndReceive(M message,
152 MessageSubject subject,
153 Function<M, byte[]> encoder,
154 Function<byte[], R> decoder,
155 NodeId toNodeId) {
Madan Jampani27b69c62015-05-15 15:49:02 -0700156 try {
157 ClusterMessage envelope = new ClusterMessage(
158 clusterService.getLocalNode().id(),
159 subject,
Aaron Kruglikov1110b2c2016-02-02 16:24:37 -0800160 timeFunction(encoder, subjectMeteringAgent, SERIALIZING).
161 apply(message));
162 return sendAndReceive(subject, envelope.getBytes(), toNodeId).
163 thenApply(bytes -> timeFunction(decoder, subjectMeteringAgent, DESERIALIZING).apply(bytes));
Madan Jampani27b69c62015-05-15 15:49:02 -0700164 } catch (Exception e) {
165 return Tools.exceptionalFuture(e);
166 }
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700167 }
168
Madan Jampani175e8fd2015-05-20 14:10:45 -0700169 private CompletableFuture<Void> doUnicast(MessageSubject subject, byte[] payload, NodeId toNodeId) {
Yuta HIGUCHI7a8d4aa2014-10-07 17:37:11 -0700170 ControllerNode node = clusterService.getNode(toNodeId);
Madan Jampani890bc352014-10-01 22:35:29 -0700171 checkArgument(node != null, "Unknown nodeId: %s", toNodeId);
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800172 Endpoint nodeEp = new Endpoint(node.ip(), node.tcpPort());
Aaron Kruglikove2411892016-02-10 18:18:17 -0800173 MeteringAgent.Context context = subjectMeteringAgent.startTimer(subject.toString() + ONE_WAY_SUFFIX);
174 return messagingService.sendAsync(nodeEp, subject.value(), payload).whenComplete((r, e) -> context.stop(e));
Madan Jampani98c17602014-10-23 15:33:23 -0700175 }
176
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700177 private CompletableFuture<byte[]> sendAndReceive(MessageSubject subject, byte[] payload, NodeId toNodeId) {
Madan Jampani4a9cb6d2014-10-17 10:48:50 -0700178 ControllerNode node = clusterService.getNode(toNodeId);
179 checkArgument(node != null, "Unknown nodeId: %s", toNodeId);
Madan Jampani2e5f87b2015-02-22 10:37:15 -0800180 Endpoint nodeEp = new Endpoint(node.ip(), node.tcpPort());
Aaron Kruglikove2411892016-02-10 18:18:17 -0800181 MeteringAgent.Context epContext = endpointMeteringAgent.
Aaron Kruglikov1110b2c2016-02-02 16:24:37 -0800182 startTimer(NODE_PREFIX + toNodeId.toString() + ROUND_TRIP_SUFFIX);
Aaron Kruglikove2411892016-02-10 18:18:17 -0800183 MeteringAgent.Context subjectContext = subjectMeteringAgent.
Aaron Kruglikov1110b2c2016-02-02 16:24:37 -0800184 startTimer(subject.toString() + ROUND_TRIP_SUFFIX);
185 return messagingService.sendAndReceive(nodeEp, subject.value(), payload).
186 whenComplete((bytes, throwable) -> {
187 subjectContext.stop(throwable);
188 epContext.stop(throwable);
189 });
Madan Jampani890bc352014-10-01 22:35:29 -0700190 }
191
Yuta HIGUCHI76b54bf2014-11-07 01:56:55 -0800192 @Override
Madan Jampani2af244a2015-02-22 13:12:01 -0800193 public void addSubscriber(MessageSubject subject,
194 ClusterMessageHandler subscriber,
195 ExecutorService executor) {
Madan Jampanic26eede2015-04-16 11:42:16 -0700196 messagingService.registerHandler(subject.value(),
197 new InternalClusterMessageHandler(subscriber),
198 executor);
Madan Jampani2af244a2015-02-22 13:12:01 -0800199 }
200
201 @Override
Yuta HIGUCHI76b54bf2014-11-07 01:56:55 -0800202 public void removeSubscriber(MessageSubject subject) {
203 messagingService.unregisterHandler(subject.value());
204 }
205
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700206 @Override
207 public <M, R> void addSubscriber(MessageSubject subject,
208 Function<byte[], M> decoder,
209 Function<M, R> handler,
210 Function<R, byte[]> encoder,
Madan Jampaniec5ae342015-04-13 15:43:10 -0700211 Executor executor) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700212 messagingService.registerHandler(subject.value(),
Madan Jampani27b69c62015-05-15 15:49:02 -0700213 new InternalMessageResponder<M, R>(decoder, encoder, m -> {
214 CompletableFuture<R> responseFuture = new CompletableFuture<>();
215 executor.execute(() -> {
216 try {
217 responseFuture.complete(handler.apply(m));
218 } catch (Exception e) {
219 responseFuture.completeExceptionally(e);
220 }
221 });
222 return responseFuture;
223 }));
224 }
225
226 @Override
227 public <M, R> void addSubscriber(MessageSubject subject,
228 Function<byte[], M> decoder,
229 Function<M, CompletableFuture<R>> handler,
230 Function<R, byte[]> encoder) {
231 messagingService.registerHandler(subject.value(),
232 new InternalMessageResponder<>(decoder, encoder, handler));
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700233 }
234
235 @Override
236 public <M> void addSubscriber(MessageSubject subject,
237 Function<byte[], M> decoder,
238 Consumer<M> handler,
Madan Jampaniec5ae342015-04-13 15:43:10 -0700239 Executor executor) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700240 messagingService.registerHandler(subject.value(),
241 new InternalMessageConsumer<>(decoder, handler),
242 executor);
243 }
244
Aaron Kruglikov1110b2c2016-02-02 16:24:37 -0800245 /**
246 * Performs the timed function, returning the value it would while timing the operation.
247 *
248 * @param timedFunction the function to be timed
249 * @param meter the metering agent to be used to time the function
250 * @param opName the opname to be used when starting the meter
251 * @param <A> The param type of the function
252 * @param <B> The return type of the function
253 * @return the value returned by the timed function
254 */
255 private <A, B> Function<A, B> timeFunction(Function<A, B> timedFunction,
256 MeteringAgent meter, String opName) {
257 checkNotNull(timedFunction);
258 checkNotNull(meter);
259 checkNotNull(opName);
260 return new Function<A, B>() {
261 @Override
262 public B apply(A a) {
263 final MeteringAgent.Context context = meter.startTimer(opName);
264 B result = null;
265 try {
266 result = timedFunction.apply(a);
Aaron Kruglikov1110b2c2016-02-02 16:24:37 -0800267 context.stop(null);
268 return result;
Aaron Kruglikove2411892016-02-10 18:18:17 -0800269 } catch (Exception e) {
270 context.stop(e);
271 Throwables.propagate(e);
272 return null;
Aaron Kruglikov1110b2c2016-02-02 16:24:37 -0800273 }
274 }
275 };
276 }
277
278
Madan Jampanid36def02016-01-13 11:21:56 -0800279 private class InternalClusterMessageHandler implements BiFunction<Endpoint, byte[], byte[]> {
Madan Jampanic26eede2015-04-16 11:42:16 -0700280 private ClusterMessageHandler handler;
281
282 public InternalClusterMessageHandler(ClusterMessageHandler handler) {
283 this.handler = handler;
284 }
285
286 @Override
Madan Jampanid36def02016-01-13 11:21:56 -0800287 public byte[] apply(Endpoint sender, byte[] bytes) {
Madan Jampanic26eede2015-04-16 11:42:16 -0700288 ClusterMessage message = ClusterMessage.fromBytes(bytes);
289 handler.handle(message);
290 return message.response();
291 }
292 }
293
Madan Jampanid36def02016-01-13 11:21:56 -0800294 private class InternalMessageResponder<M, R> implements BiFunction<Endpoint, byte[], CompletableFuture<byte[]>> {
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700295 private final Function<byte[], M> decoder;
296 private final Function<R, byte[]> encoder;
Madan Jampani27b69c62015-05-15 15:49:02 -0700297 private final Function<M, CompletableFuture<R>> handler;
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700298
299 public InternalMessageResponder(Function<byte[], M> decoder,
300 Function<R, byte[]> encoder,
Madan Jampani27b69c62015-05-15 15:49:02 -0700301 Function<M, CompletableFuture<R>> handler) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700302 this.decoder = decoder;
303 this.encoder = encoder;
304 this.handler = handler;
305 }
Madan Jampanic26eede2015-04-16 11:42:16 -0700306
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700307 @Override
Madan Jampanid36def02016-01-13 11:21:56 -0800308 public CompletableFuture<byte[]> apply(Endpoint sender, byte[] bytes) {
Aaron Kruglikov1110b2c2016-02-02 16:24:37 -0800309 return handler.apply(timeFunction(decoder, subjectMeteringAgent, DESERIALIZING).
310 apply(ClusterMessage.fromBytes(bytes).payload())).
311 thenApply(m -> timeFunction(encoder, subjectMeteringAgent, SERIALIZING).apply(m));
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700312 }
313 }
314
Madan Jampanid36def02016-01-13 11:21:56 -0800315 private class InternalMessageConsumer<M> implements BiConsumer<Endpoint, byte[]> {
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700316 private final Function<byte[], M> decoder;
317 private final Consumer<M> consumer;
318
319 public InternalMessageConsumer(Function<byte[], M> decoder, Consumer<M> consumer) {
320 this.decoder = decoder;
321 this.consumer = consumer;
322 }
Madan Jampani8a895092014-10-17 16:55:50 -0700323
324 @Override
Madan Jampanid36def02016-01-13 11:21:56 -0800325 public void accept(Endpoint sender, byte[] bytes) {
Aaron Kruglikov1110b2c2016-02-02 16:24:37 -0800326 consumer.accept(timeFunction(decoder, subjectMeteringAgent, DESERIALIZING).
327 apply(ClusterMessage.fromBytes(bytes).payload()));
Madan Jampani8a895092014-10-17 16:55:50 -0700328 }
329 }
Madan Jampanif5d263b2014-11-13 10:04:40 -0800330}