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 io.netty.channel.Channel;
13 import io.netty.channel.ChannelFuture;
14 import io.netty.util.concurrent.GenericFutureListener;
16 import java.net.InetSocketAddress;
17 import java.util.concurrent.Future;
18 import java.util.concurrent.RejectedExecutionException;
19 import java.util.concurrent.TimeUnit;
21 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionReadyListener;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoInput;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoOutput;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoReplyInput;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoRequestMessage;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterInput;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessage;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowModInput;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncInput;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncOutput;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigInput;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigOutput;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesInput;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigInput;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigOutput;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GroupModInput;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloInput;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessage;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MeterModInput;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInput;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OpenflowProtocolListener;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketOutInput;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortModInput;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestInput;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutput;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetAsyncInput;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetConfigInput;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.TableModInput;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.DisconnectEvent;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SwitchIdleEvent;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SystemNotificationsListener;
61 import org.opendaylight.yangtools.yang.binding.DataObject;
62 import org.opendaylight.yangtools.yang.binding.Notification;
63 import org.opendaylight.yangtools.yang.common.RpcResult;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
67 import com.google.common.base.Preconditions;
68 import com.google.common.cache.Cache;
69 import com.google.common.cache.CacheBuilder;
70 import com.google.common.cache.RemovalCause;
71 import com.google.common.cache.RemovalListener;
72 import com.google.common.cache.RemovalNotification;
73 import com.google.common.util.concurrent.ListenableFuture;
74 import com.google.common.util.concurrent.SettableFuture;
77 * Handles messages (notifications + rpcs) and connections
79 * @author michal.polkorab
81 public class ConnectionAdapterImpl implements ConnectionFacade {
82 /** after this time, RPC future response objects will be thrown away (in minutes) */
83 public static final int RPC_RESPONSE_EXPIRATION = 1;
86 * Default depth of write queue, e.g. we allow these many messages
87 * to be queued up before blocking producers.
89 public static final int DEFAULT_QUEUE_DEPTH = 1024;
91 private static final Logger LOG = LoggerFactory
92 .getLogger(ConnectionAdapterImpl.class);
93 private static final Exception QUEUE_FULL_EXCEPTION =
94 new RejectedExecutionException("Output queue is full");
96 private static final String APPLICATION_TAG = "OPENFLOW_LIBRARY";
97 private static final String TAG = "OPENFLOW";
98 private static final RemovalListener<RpcResponseKey, ResponseExpectedRpcListener<?>> REMOVAL_LISTENER =
99 new RemovalListener<RpcResponseKey, ResponseExpectedRpcListener<?>>() {
101 public void onRemoval(
102 final RemovalNotification<RpcResponseKey, ResponseExpectedRpcListener<?>> notification) {
103 if (! notification.getCause().equals(RemovalCause.EXPLICIT)) {
104 notification.getValue().discard();
109 /** expiring cache for future rpcResponses */
110 private Cache<RpcResponseKey, ResponseExpectedRpcListener<?>> responseCache;
112 private final ChannelOutboundQueue output;
113 private final Channel channel;
115 private ConnectionReadyListener connectionReadyListener;
116 private OpenflowProtocolListener messageListener;
117 private SystemNotificationsListener systemListener;
118 private boolean disconnectOccured = false;
122 * @param channel the channel to be set - used for communication
123 * @param address client address (used only in case of UDP communication,
124 * as there is no need to store address over tcp (stable channel))
126 public ConnectionAdapterImpl(final Channel channel, final InetSocketAddress address) {
127 responseCache = CacheBuilder.newBuilder()
129 .expireAfterWrite(RPC_RESPONSE_EXPIRATION, TimeUnit.MINUTES)
130 .removalListener(REMOVAL_LISTENER).build();
131 this.channel = Preconditions.checkNotNull(channel);
132 this.output = new ChannelOutboundQueue(channel, DEFAULT_QUEUE_DEPTH, address);
133 channel.pipeline().addLast(output);
134 LOG.debug("ConnectionAdapter created");
138 public Future<RpcResult<BarrierOutput>> barrier(final BarrierInput input) {
139 return sendToSwitchExpectRpcResultFuture(
140 input, BarrierOutput.class, "barrier-input sending failed");
144 public Future<RpcResult<EchoOutput>> echo(final EchoInput input) {
145 return sendToSwitchExpectRpcResultFuture(
146 input, EchoOutput.class, "echo-input sending failed");
150 public Future<RpcResult<Void>> echoReply(final EchoReplyInput input) {
151 return sendToSwitchFuture(input, "echo-reply sending failed");
155 public Future<RpcResult<Void>> experimenter(final ExperimenterInput input) {
156 return sendToSwitchFuture(input, "experimenter sending failed");
160 public Future<RpcResult<Void>> flowMod(final FlowModInput input) {
161 return sendToSwitchFuture(input, "flow-mod sending failed");
165 public Future<RpcResult<GetConfigOutput>> getConfig(final GetConfigInput input) {
166 return sendToSwitchExpectRpcResultFuture(
167 input, GetConfigOutput.class, "get-config-input sending failed");
171 public Future<RpcResult<GetFeaturesOutput>> getFeatures(
172 final GetFeaturesInput input) {
173 return sendToSwitchExpectRpcResultFuture(
174 input, GetFeaturesOutput.class, "get-features-input sending failed");
178 public Future<RpcResult<GetQueueConfigOutput>> getQueueConfig(
179 final GetQueueConfigInput input) {
180 return sendToSwitchExpectRpcResultFuture(
181 input, GetQueueConfigOutput.class, "get-queue-config-input sending failed");
185 public Future<RpcResult<Void>> groupMod(final GroupModInput input) {
186 return sendToSwitchFuture(input, "group-mod-input sending failed");
190 public Future<RpcResult<Void>> hello(final HelloInput input) {
191 return sendToSwitchFuture(input, "hello-input sending failed");
195 public Future<RpcResult<Void>> meterMod(final MeterModInput input) {
196 return sendToSwitchFuture(input, "meter-mod-input sending failed");
200 public Future<RpcResult<Void>> packetOut(final PacketOutInput input) {
201 return sendToSwitchFuture(input, "packet-out-input sending failed");
205 public Future<RpcResult<Void>> multipartRequest(final MultipartRequestInput input) {
206 return sendToSwitchFuture(input, "multi-part-request sending failed");
210 public Future<RpcResult<Void>> portMod(final PortModInput input) {
211 return sendToSwitchFuture(input, "port-mod-input sending failed");
215 public Future<RpcResult<RoleRequestOutput>> roleRequest(
216 final RoleRequestInput input) {
217 return sendToSwitchExpectRpcResultFuture(
218 input, RoleRequestOutput.class, "role-request-config-input sending failed");
222 public Future<RpcResult<Void>> setConfig(final SetConfigInput input) {
223 return sendToSwitchFuture(input, "set-config-input sending failed");
227 public Future<RpcResult<Void>> tableMod(final TableModInput input) {
228 return sendToSwitchFuture(input, "table-mod-input sending failed");
232 public Future<RpcResult<GetAsyncOutput>> getAsync(final GetAsyncInput input) {
233 return sendToSwitchExpectRpcResultFuture(
234 input, GetAsyncOutput.class, "get-async-input sending failed");
238 public Future<RpcResult<Void>> setAsync(final SetAsyncInput input) {
239 return sendToSwitchFuture(input, "set-async-input sending failed");
243 public Future<Boolean> disconnect() {
244 ChannelFuture disconnectResult = channel.disconnect();
245 responseCache.invalidateAll();
246 disconnectOccured = true;
248 return handleTransportChannelFuture(disconnectResult);
252 public boolean isAlive() {
253 return channel.isOpen();
257 public void setMessageListener(final OpenflowProtocolListener messageListener) {
258 this.messageListener = messageListener;
262 public void consume(final DataObject message) {
263 LOG.debug("ConsumeIntern msg");
264 if (disconnectOccured ) {
267 if (message instanceof Notification) {
269 if (message instanceof DisconnectEvent) {
270 systemListener.onDisconnectEvent((DisconnectEvent) message);
271 responseCache.invalidateAll();
272 disconnectOccured = true;
273 } else if (message instanceof SwitchIdleEvent) {
274 systemListener.onSwitchIdleEvent((SwitchIdleEvent) message);
277 else if (message instanceof EchoRequestMessage) {
278 messageListener.onEchoRequestMessage((EchoRequestMessage) message);
279 } else if (message instanceof ErrorMessage) {
280 messageListener.onErrorMessage((ErrorMessage) message);
281 } else if (message instanceof ExperimenterMessage) {
282 messageListener.onExperimenterMessage((ExperimenterMessage) message);
283 } else if (message instanceof FlowRemovedMessage) {
284 messageListener.onFlowRemovedMessage((FlowRemovedMessage) message);
285 } else if (message instanceof HelloMessage) {
286 LOG.info("Hello received / branch");
287 messageListener.onHelloMessage((HelloMessage) message);
288 } else if (message instanceof MultipartReplyMessage) {
289 messageListener.onMultipartReplyMessage((MultipartReplyMessage) message);
290 } else if (message instanceof PacketInMessage) {
291 messageListener.onPacketInMessage((PacketInMessage) message);
292 } else if (message instanceof PortStatusMessage) {
293 messageListener.onPortStatusMessage((PortStatusMessage) message);
295 LOG.warn("message listening not supported for type: {}", message.getClass());
298 if (message instanceof OfHeader) {
299 LOG.debug("OFheader msg received");
300 RpcResponseKey key = createRpcResponseKey((OfHeader) message);
301 final ResponseExpectedRpcListener<?> listener = findRpcResponse(key);
302 if (listener != null) {
303 LOG.debug("corresponding rpcFuture found");
304 listener.completed((OfHeader)message);
305 LOG.debug("after setting rpcFuture");
306 responseCache.invalidate(key);
308 LOG.warn("received unexpected rpc response: {}", key);
311 LOG.warn("message listening not supported for type: {}", message.getClass());
316 private <T> ListenableFuture<RpcResult<T>> enqueueMessage(final AbstractRpcListener<T> promise) {
317 LOG.debug("Submitting promise {}", promise);
319 if (!output.enqueue(promise)) {
320 LOG.debug("Message queue is full, rejecting execution");
321 promise.failedRpc(QUEUE_FULL_EXCEPTION);
323 LOG.debug("Promise enqueued successfully");
326 return promise.getResult();
330 * sends given message to switch, sending result will be reported via return value
331 * @param input message to send
332 * @param failureInfo describes, what type of message caused failure by sending
333 * @return future object, <ul>
334 * <li>if send successful, {@link RpcResult} without errors and successful
335 * status will be returned, </li>
336 * <li>else {@link RpcResult} will contain errors and failed status</li>
339 private ListenableFuture<RpcResult<Void>> sendToSwitchFuture(
340 final DataObject input, final String failureInfo) {
341 return enqueueMessage(new SimpleRpcListener(input, failureInfo));
345 * sends given message to switch, sending result or switch response will be reported via return value
346 * @param input message to send
347 * @param responseClazz type of response
348 * @param failureInfo describes, what type of message caused failure by sending
349 * @return future object, <ul>
350 * <li>if send fails, {@link RpcResult} will contain errors and failed status </li>
351 * <li>else {@link RpcResult} will be stored in responseCache and wait for particular timeout
352 * ({@link ConnectionAdapterImpl#RPC_RESPONSE_EXPIRATION}),
353 * <ul><li>either switch will manage to answer
354 * and then corresponding response message will be set into returned future</li>
355 * <li>or response in cache will expire and returned future will be cancelled</li></ul>
359 private <IN extends OfHeader, OUT extends OfHeader> ListenableFuture<RpcResult<OUT>> sendToSwitchExpectRpcResultFuture(
360 final IN input, final Class<OUT> responseClazz, final String failureInfo) {
361 final RpcResponseKey key = new RpcResponseKey(input.getXid(), responseClazz.getName());
362 final ResponseExpectedRpcListener<OUT> listener =
363 new ResponseExpectedRpcListener<>(input, failureInfo, responseCache, key);
364 return enqueueMessage(listener);
368 * @param resultFuture
370 * @param errorSeverity
374 private static SettableFuture<Boolean> handleTransportChannelFuture(
375 final ChannelFuture resultFuture) {
377 final SettableFuture<Boolean> transportResult = SettableFuture.create();
379 resultFuture.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
382 public void operationComplete(
383 final io.netty.util.concurrent.Future<? super Void> future)
385 transportResult.set(future.isSuccess());
386 if (!future.isSuccess()) {
387 transportResult.setException(future.cause());
391 return transportResult;
398 private static RpcResponseKey createRpcResponseKey(final OfHeader message) {
399 return new RpcResponseKey(message.getXid(), message.getImplementedInterface().getName());
405 private ResponseExpectedRpcListener<?> findRpcResponse(final RpcResponseKey key) {
406 return responseCache.getIfPresent(key);
410 public void setSystemListener(final SystemNotificationsListener systemListener) {
411 this.systemListener = systemListener;
415 public void checkListeners() {
416 final StringBuilder buffer = new StringBuilder();
417 if (systemListener == null) {
418 buffer.append("SystemListener ");
420 if (messageListener == null) {
421 buffer.append("MessageListener ");
423 if (connectionReadyListener == null) {
424 buffer.append("ConnectionReadyListener ");
427 Preconditions.checkState(buffer.length() == 0, "Missing listeners: %s", buffer.toString());
431 public void fireConnectionReadyNotification() {
432 new Thread(new Runnable() {
435 connectionReadyListener.onConnectionReady();
441 public void setConnectionReadyListener(
442 final ConnectionReadyListener connectionReadyListener) {
443 this.connectionReadyListener = connectionReadyListener;
447 public InetSocketAddress getRemoteAddress() {
448 return (InetSocketAddress) channel.remoteAddress();
452 * Used only for testing purposes
455 public void setResponseCache(Cache<RpcResponseKey, ResponseExpectedRpcListener<?>> cache) {
456 this.responseCache = cache;