2 * Copyright (c) 2013 Pantheon Technologies s.r.o. and others. All rights reserved.
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
10 package org.opendaylight.openflowjava.protocol.impl.core.connection;
12 import com.google.common.base.Preconditions;
13 import com.google.common.cache.Cache;
14 import com.google.common.cache.CacheBuilder;
15 import com.google.common.cache.RemovalCause;
16 import com.google.common.cache.RemovalListener;
17 import com.google.common.cache.RemovalNotification;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.SettableFuture;
20 import io.netty.channel.Channel;
21 import io.netty.channel.ChannelFuture;
22 import io.netty.util.concurrent.GenericFutureListener;
23 import java.net.InetSocketAddress;
24 import java.util.concurrent.Future;
25 import java.util.concurrent.RejectedExecutionException;
26 import java.util.concurrent.TimeUnit;
27 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionReadyListener;
28 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandler;
29 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandlerRegistration;
30 import org.opendaylight.openflowjava.statistics.CounterEventTypes;
31 import org.opendaylight.openflowjava.statistics.StatisticsCounters;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoInput;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoOutput;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoReplyInput;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoRequestMessage;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterInput;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessage;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowModInput;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncInput;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncOutput;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigInput;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigOutput;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesInput;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigInput;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigOutput;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GroupModInput;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloInput;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessage;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MeterModInput;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInput;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OpenflowProtocolListener;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketOutInput;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortModInput;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestInput;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutput;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetAsyncInput;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetConfigInput;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.TableModInput;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.DisconnectEvent;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SwitchIdleEvent;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SystemNotificationsListener;
71 import org.opendaylight.yangtools.yang.binding.DataObject;
72 import org.opendaylight.yangtools.yang.binding.Notification;
73 import org.opendaylight.yangtools.yang.common.RpcResult;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
78 * Handles messages (notifications + rpcs) and connections
80 * @author michal.polkorab
82 public class ConnectionAdapterImpl implements ConnectionFacade {
83 /** after this time, RPC future response objects will be thrown away (in minutes) */
84 public static final int RPC_RESPONSE_EXPIRATION = 1;
87 * Default depth of write queue, e.g. we allow these many messages
88 * to be queued up before blocking producers.
90 public static final int DEFAULT_QUEUE_DEPTH = 1024;
92 private static final Logger LOG = LoggerFactory
93 .getLogger(ConnectionAdapterImpl.class);
94 private static final Exception QUEUE_FULL_EXCEPTION =
95 new RejectedExecutionException("Output queue is full");
97 private static final RemovalListener<RpcResponseKey, ResponseExpectedRpcListener<?>> REMOVAL_LISTENER =
98 new RemovalListener<RpcResponseKey, ResponseExpectedRpcListener<?>>() {
100 public void onRemoval(
101 final RemovalNotification<RpcResponseKey, ResponseExpectedRpcListener<?>> notification) {
102 if (! notification.getCause().equals(RemovalCause.EXPLICIT)) {
103 notification.getValue().discard();
108 /** expiring cache for future rpcResponses */
109 private Cache<RpcResponseKey, ResponseExpectedRpcListener<?>> responseCache;
111 private final ChannelOutboundQueue output;
112 private final Channel channel;
114 private ConnectionReadyListener connectionReadyListener;
115 private OpenflowProtocolListener messageListener;
116 private SystemNotificationsListener systemListener;
117 private OutboundQueueManager<?> outputManager;
118 private boolean disconnectOccured = false;
119 private final StatisticsCounters statisticsCounters;
120 private final InetSocketAddress address;
124 * @param channel the channel to be set - used for communication
125 * @param address client address (used only in case of UDP communication,
126 * as there is no need to store address over tcp (stable channel))
128 public ConnectionAdapterImpl(final Channel channel, final InetSocketAddress address) {
129 responseCache = CacheBuilder.newBuilder()
131 .expireAfterWrite(RPC_RESPONSE_EXPIRATION, TimeUnit.MINUTES)
132 .removalListener(REMOVAL_LISTENER).build();
133 this.channel = Preconditions.checkNotNull(channel);
134 this.output = new ChannelOutboundQueue(channel, DEFAULT_QUEUE_DEPTH, address);
135 this.address = address;
136 channel.pipeline().addLast(output);
137 statisticsCounters = StatisticsCounters.getInstance();
138 LOG.debug("ConnectionAdapter created");
142 public Future<RpcResult<BarrierOutput>> barrier(final BarrierInput input) {
143 return sendToSwitchExpectRpcResultFuture(
144 input, BarrierOutput.class, "barrier-input sending failed");
148 public Future<RpcResult<EchoOutput>> echo(final EchoInput input) {
149 return sendToSwitchExpectRpcResultFuture(
150 input, EchoOutput.class, "echo-input sending failed");
154 public Future<RpcResult<Void>> echoReply(final EchoReplyInput input) {
155 return sendToSwitchFuture(input, "echo-reply sending failed");
159 public Future<RpcResult<Void>> experimenter(final ExperimenterInput input) {
160 return sendToSwitchFuture(input, "experimenter sending failed");
164 public Future<RpcResult<Void>> flowMod(final FlowModInput input) {
165 statisticsCounters.incrementCounter(CounterEventTypes.DS_FLOW_MODS_ENTERED);
166 return sendToSwitchFuture(input, "flow-mod sending failed");
170 public Future<RpcResult<GetConfigOutput>> getConfig(final GetConfigInput input) {
171 return sendToSwitchExpectRpcResultFuture(
172 input, GetConfigOutput.class, "get-config-input sending failed");
176 public Future<RpcResult<GetFeaturesOutput>> getFeatures(
177 final GetFeaturesInput input) {
178 return sendToSwitchExpectRpcResultFuture(
179 input, GetFeaturesOutput.class, "get-features-input sending failed");
183 public Future<RpcResult<GetQueueConfigOutput>> getQueueConfig(
184 final GetQueueConfigInput input) {
185 return sendToSwitchExpectRpcResultFuture(
186 input, GetQueueConfigOutput.class, "get-queue-config-input sending failed");
190 public Future<RpcResult<Void>> groupMod(final GroupModInput input) {
191 return sendToSwitchFuture(input, "group-mod-input sending failed");
195 public Future<RpcResult<Void>> hello(final HelloInput input) {
196 return sendToSwitchFuture(input, "hello-input sending failed");
200 public Future<RpcResult<Void>> meterMod(final MeterModInput input) {
201 return sendToSwitchFuture(input, "meter-mod-input sending failed");
205 public Future<RpcResult<Void>> packetOut(final PacketOutInput input) {
206 return sendToSwitchFuture(input, "packet-out-input sending failed");
210 public Future<RpcResult<Void>> multipartRequest(final MultipartRequestInput input) {
211 return sendToSwitchFuture(input, "multi-part-request sending failed");
215 public Future<RpcResult<Void>> portMod(final PortModInput input) {
216 return sendToSwitchFuture(input, "port-mod-input sending failed");
220 public Future<RpcResult<RoleRequestOutput>> roleRequest(
221 final RoleRequestInput input) {
222 return sendToSwitchExpectRpcResultFuture(
223 input, RoleRequestOutput.class, "role-request-config-input sending failed");
227 public Future<RpcResult<Void>> setConfig(final SetConfigInput input) {
228 return sendToSwitchFuture(input, "set-config-input sending failed");
232 public Future<RpcResult<Void>> tableMod(final TableModInput input) {
233 return sendToSwitchFuture(input, "table-mod-input sending failed");
237 public Future<RpcResult<GetAsyncOutput>> getAsync(final GetAsyncInput input) {
238 return sendToSwitchExpectRpcResultFuture(
239 input, GetAsyncOutput.class, "get-async-input sending failed");
243 public Future<RpcResult<Void>> setAsync(final SetAsyncInput input) {
244 return sendToSwitchFuture(input, "set-async-input sending failed");
248 public Future<Boolean> disconnect() {
249 ChannelFuture disconnectResult = channel.disconnect();
250 responseCache.invalidateAll();
251 disconnectOccured = true;
253 return handleTransportChannelFuture(disconnectResult);
257 public boolean isAlive() {
258 return channel.isOpen();
262 public void setMessageListener(final OpenflowProtocolListener messageListener) {
263 this.messageListener = messageListener;
267 public void consume(final DataObject message) {
268 LOG.debug("ConsumeIntern msg on {}", channel);
269 if (disconnectOccured ) {
272 if (message instanceof Notification) {
275 if (message instanceof DisconnectEvent) {
276 systemListener.onDisconnectEvent((DisconnectEvent) message);
277 responseCache.invalidateAll();
278 disconnectOccured = true;
279 } else if (message instanceof SwitchIdleEvent) {
280 systemListener.onSwitchIdleEvent((SwitchIdleEvent) message);
282 } else if (message instanceof EchoRequestMessage) {
283 if (outputManager != null) {
284 outputManager.onEchoRequest((EchoRequestMessage) message);
286 messageListener.onEchoRequestMessage((EchoRequestMessage) message);
288 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
289 } else if (message instanceof ErrorMessage) {
290 // Send only unmatched errors
291 if (outputManager == null || !outputManager.onMessage((OfHeader) message)) {
292 messageListener.onErrorMessage((ErrorMessage) message);
294 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
295 } else if (message instanceof ExperimenterMessage) {
296 if (outputManager != null) {
297 outputManager.onMessage((OfHeader) message);
299 messageListener.onExperimenterMessage((ExperimenterMessage) message);
300 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
301 } else if (message instanceof FlowRemovedMessage) {
302 messageListener.onFlowRemovedMessage((FlowRemovedMessage) message);
303 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
304 } else if (message instanceof HelloMessage) {
305 LOG.info("Hello received / branch");
306 messageListener.onHelloMessage((HelloMessage) message);
307 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
308 } else if (message instanceof MultipartReplyMessage) {
309 if (outputManager != null) {
310 outputManager.onMessage((OfHeader) message);
312 messageListener.onMultipartReplyMessage((MultipartReplyMessage) message);
313 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
314 } else if (message instanceof PacketInMessage) {
315 messageListener.onPacketInMessage((PacketInMessage) message);
316 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
317 } else if (message instanceof PortStatusMessage) {
318 messageListener.onPortStatusMessage((PortStatusMessage) message);
319 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
321 LOG.warn("message listening not supported for type: {}", message.getClass());
323 } else if (message instanceof OfHeader) {
324 LOG.debug("OFheader msg received");
326 if (outputManager == null || !outputManager.onMessage((OfHeader) message)) {
327 RpcResponseKey key = createRpcResponseKey((OfHeader) message);
328 final ResponseExpectedRpcListener<?> listener = findRpcResponse(key);
329 if (listener != null) {
330 LOG.debug("corresponding rpcFuture found");
331 listener.completed((OfHeader)message);
332 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
333 LOG.debug("after setting rpcFuture");
334 responseCache.invalidate(key);
336 LOG.warn("received unexpected rpc response: {}", key);
340 LOG.warn("message listening not supported for type: {}", message.getClass());
344 private <T> ListenableFuture<RpcResult<T>> enqueueMessage(final AbstractRpcListener<T> promise) {
345 LOG.debug("Submitting promise {}", promise);
347 if (!output.enqueue(promise)) {
348 LOG.debug("Message queue is full, rejecting execution");
349 promise.failedRpc(QUEUE_FULL_EXCEPTION);
351 LOG.debug("Promise enqueued successfully");
354 return promise.getResult();
358 * sends given message to switch, sending result will be reported via return value
359 * @param input message to send
360 * @param failureInfo describes, what type of message caused failure by sending
361 * @return future object, <ul>
362 * <li>if send successful, {@link RpcResult} without errors and successful
363 * status will be returned, </li>
364 * <li>else {@link RpcResult} will contain errors and failed status</li>
367 private ListenableFuture<RpcResult<Void>> sendToSwitchFuture(
368 final DataObject input, final String failureInfo) {
369 statisticsCounters.incrementCounter(CounterEventTypes.DS_ENTERED_OFJAVA);
370 return enqueueMessage(new SimpleRpcListener(input, failureInfo));
374 * sends given message to switch, sending result or switch response will be reported via return value
375 * @param input message to send
376 * @param responseClazz type of response
377 * @param failureInfo describes, what type of message caused failure by sending
378 * @return future object, <ul>
379 * <li>if send fails, {@link RpcResult} will contain errors and failed status </li>
380 * <li>else {@link RpcResult} will be stored in responseCache and wait for particular timeout
381 * ({@link ConnectionAdapterImpl#RPC_RESPONSE_EXPIRATION}),
382 * <ul><li>either switch will manage to answer
383 * and then corresponding response message will be set into returned future</li>
384 * <li>or response in cache will expire and returned future will be cancelled</li></ul>
388 private <IN extends OfHeader, OUT extends OfHeader> ListenableFuture<RpcResult<OUT>> sendToSwitchExpectRpcResultFuture(
389 final IN input, final Class<OUT> responseClazz, final String failureInfo) {
390 final RpcResponseKey key = new RpcResponseKey(input.getXid(), responseClazz.getName());
391 final ResponseExpectedRpcListener<OUT> listener =
392 new ResponseExpectedRpcListener<>(input, failureInfo, responseCache, key);
393 statisticsCounters.incrementCounter(CounterEventTypes.DS_ENTERED_OFJAVA);
394 return enqueueMessage(listener);
398 * @param resultFuture
400 * @param errorSeverity
404 private static SettableFuture<Boolean> handleTransportChannelFuture(
405 final ChannelFuture resultFuture) {
407 final SettableFuture<Boolean> transportResult = SettableFuture.create();
409 resultFuture.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
412 public void operationComplete(
413 final io.netty.util.concurrent.Future<? super Void> future)
415 transportResult.set(future.isSuccess());
416 if (!future.isSuccess()) {
417 transportResult.setException(future.cause());
421 return transportResult;
428 private static RpcResponseKey createRpcResponseKey(final OfHeader message) {
429 return new RpcResponseKey(message.getXid(), message.getImplementedInterface().getName());
435 private ResponseExpectedRpcListener<?> findRpcResponse(final RpcResponseKey key) {
436 return responseCache.getIfPresent(key);
440 public void setSystemListener(final SystemNotificationsListener systemListener) {
441 this.systemListener = systemListener;
445 public void checkListeners() {
446 final StringBuilder buffer = new StringBuilder();
447 if (systemListener == null) {
448 buffer.append("SystemListener ");
450 if (messageListener == null) {
451 buffer.append("MessageListener ");
453 if (connectionReadyListener == null) {
454 buffer.append("ConnectionReadyListener ");
457 Preconditions.checkState(buffer.length() == 0, "Missing listeners: %s", buffer.toString());
461 public void fireConnectionReadyNotification() {
462 new Thread(new Runnable() {
465 connectionReadyListener.onConnectionReady();
471 public void setConnectionReadyListener(
472 final ConnectionReadyListener connectionReadyListener) {
473 this.connectionReadyListener = connectionReadyListener;
477 public InetSocketAddress getRemoteAddress() {
478 return (InetSocketAddress) channel.remoteAddress();
482 * Used only for testing purposes
485 public void setResponseCache(final Cache<RpcResponseKey, ResponseExpectedRpcListener<?>> cache) {
486 this.responseCache = cache;
490 public boolean isAutoRead() {
491 return channel.config().isAutoRead();
495 public void setAutoRead(final boolean autoRead) {
496 channel.config().setAutoRead(autoRead);
500 public <T extends OutboundQueueHandler> OutboundQueueHandlerRegistration<T> registerOutboundQueueHandler(
501 final T handler, final int maxQueueDepth, final long maxBarrierNanos) {
502 Preconditions.checkState(outputManager == null, "Manager %s already registered", outputManager);
504 final OutboundQueueManager<T> ret = new OutboundQueueManager<>(this, address, handler, maxQueueDepth, maxBarrierNanos);
506 channel.pipeline().addLast(outputManager);
508 return new OutboundQueueHandlerRegistrationImpl<T>(handler) {
510 protected void removeRegistration() {
511 outputManager.close();
512 channel.pipeline().remove(outputManager);
513 outputManager = null;
518 Channel getChannel() {