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.openflowjava.statistics.CounterEventTypes;
23 import org.opendaylight.openflowjava.statistics.StatisticsCounters;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoInput;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoOutput;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoReplyInput;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoRequestMessage;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterInput;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessage;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowModInput;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncInput;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncOutput;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigInput;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigOutput;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesInput;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigInput;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigOutput;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GroupModInput;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloInput;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessage;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MeterModInput;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInput;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OpenflowProtocolListener;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketOutInput;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortModInput;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestInput;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutput;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetAsyncInput;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetConfigInput;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.TableModInput;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.DisconnectEvent;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SwitchIdleEvent;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SystemNotificationsListener;
63 import org.opendaylight.yangtools.yang.binding.DataObject;
64 import org.opendaylight.yangtools.yang.binding.Notification;
65 import org.opendaylight.yangtools.yang.common.RpcResult;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
69 import com.google.common.base.Preconditions;
70 import com.google.common.cache.Cache;
71 import com.google.common.cache.CacheBuilder;
72 import com.google.common.cache.RemovalCause;
73 import com.google.common.cache.RemovalListener;
74 import com.google.common.cache.RemovalNotification;
75 import com.google.common.util.concurrent.ListenableFuture;
76 import com.google.common.util.concurrent.SettableFuture;
79 * Handles messages (notifications + rpcs) and connections
81 * @author michal.polkorab
83 public class ConnectionAdapterImpl implements ConnectionFacade {
84 /** after this time, RPC future response objects will be thrown away (in minutes) */
85 public static final int RPC_RESPONSE_EXPIRATION = 1;
88 * Default depth of write queue, e.g. we allow these many messages
89 * to be queued up before blocking producers.
91 public static final int DEFAULT_QUEUE_DEPTH = 1024;
93 private static final Logger LOG = LoggerFactory
94 .getLogger(ConnectionAdapterImpl.class);
95 private static final Exception QUEUE_FULL_EXCEPTION =
96 new RejectedExecutionException("Output queue is full");
98 private static final String APPLICATION_TAG = "OPENFLOW_LIBRARY";
99 private static final String TAG = "OPENFLOW";
100 private static final RemovalListener<RpcResponseKey, ResponseExpectedRpcListener<?>> REMOVAL_LISTENER =
101 new RemovalListener<RpcResponseKey, ResponseExpectedRpcListener<?>>() {
103 public void onRemoval(
104 final RemovalNotification<RpcResponseKey, ResponseExpectedRpcListener<?>> notification) {
105 if (! notification.getCause().equals(RemovalCause.EXPLICIT)) {
106 notification.getValue().discard();
111 /** expiring cache for future rpcResponses */
112 private Cache<RpcResponseKey, ResponseExpectedRpcListener<?>> responseCache;
114 private final ChannelOutboundQueue output;
115 private final Channel channel;
117 private ConnectionReadyListener connectionReadyListener;
118 private OpenflowProtocolListener messageListener;
119 private SystemNotificationsListener systemListener;
120 private boolean disconnectOccured = false;
121 private StatisticsCounters statisticsCounters;
125 * @param channel the channel to be set - used for communication
126 * @param address client address (used only in case of UDP communication,
127 * as there is no need to store address over tcp (stable channel))
129 public ConnectionAdapterImpl(final Channel channel, final InetSocketAddress address) {
130 responseCache = CacheBuilder.newBuilder()
132 .expireAfterWrite(RPC_RESPONSE_EXPIRATION, TimeUnit.MINUTES)
133 .removalListener(REMOVAL_LISTENER).build();
134 this.channel = Preconditions.checkNotNull(channel);
135 this.output = new ChannelOutboundQueue(channel, DEFAULT_QUEUE_DEPTH, 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 return sendToSwitchFuture(input, "flow-mod sending failed");
169 public Future<RpcResult<GetConfigOutput>> getConfig(final GetConfigInput input) {
170 return sendToSwitchExpectRpcResultFuture(
171 input, GetConfigOutput.class, "get-config-input sending failed");
175 public Future<RpcResult<GetFeaturesOutput>> getFeatures(
176 final GetFeaturesInput input) {
177 return sendToSwitchExpectRpcResultFuture(
178 input, GetFeaturesOutput.class, "get-features-input sending failed");
182 public Future<RpcResult<GetQueueConfigOutput>> getQueueConfig(
183 final GetQueueConfigInput input) {
184 return sendToSwitchExpectRpcResultFuture(
185 input, GetQueueConfigOutput.class, "get-queue-config-input sending failed");
189 public Future<RpcResult<Void>> groupMod(final GroupModInput input) {
190 return sendToSwitchFuture(input, "group-mod-input sending failed");
194 public Future<RpcResult<Void>> hello(final HelloInput input) {
195 return sendToSwitchFuture(input, "hello-input sending failed");
199 public Future<RpcResult<Void>> meterMod(final MeterModInput input) {
200 return sendToSwitchFuture(input, "meter-mod-input sending failed");
204 public Future<RpcResult<Void>> packetOut(final PacketOutInput input) {
205 return sendToSwitchFuture(input, "packet-out-input sending failed");
209 public Future<RpcResult<Void>> multipartRequest(final MultipartRequestInput input) {
210 return sendToSwitchFuture(input, "multi-part-request sending failed");
214 public Future<RpcResult<Void>> portMod(final PortModInput input) {
215 return sendToSwitchFuture(input, "port-mod-input sending failed");
219 public Future<RpcResult<RoleRequestOutput>> roleRequest(
220 final RoleRequestInput input) {
221 return sendToSwitchExpectRpcResultFuture(
222 input, RoleRequestOutput.class, "role-request-config-input sending failed");
226 public Future<RpcResult<Void>> setConfig(final SetConfigInput input) {
227 return sendToSwitchFuture(input, "set-config-input sending failed");
231 public Future<RpcResult<Void>> tableMod(final TableModInput input) {
232 return sendToSwitchFuture(input, "table-mod-input sending failed");
236 public Future<RpcResult<GetAsyncOutput>> getAsync(final GetAsyncInput input) {
237 return sendToSwitchExpectRpcResultFuture(
238 input, GetAsyncOutput.class, "get-async-input sending failed");
242 public Future<RpcResult<Void>> setAsync(final SetAsyncInput input) {
243 return sendToSwitchFuture(input, "set-async-input sending failed");
247 public Future<Boolean> disconnect() {
248 ChannelFuture disconnectResult = channel.disconnect();
249 responseCache.invalidateAll();
250 disconnectOccured = true;
252 return handleTransportChannelFuture(disconnectResult);
256 public boolean isAlive() {
257 return channel.isOpen();
261 public void setMessageListener(final OpenflowProtocolListener messageListener) {
262 this.messageListener = messageListener;
266 public void consume(final DataObject message) {
267 LOG.debug("ConsumeIntern msg");
268 if (disconnectOccured ) {
271 if (message instanceof Notification) {
274 if (message instanceof DisconnectEvent) {
275 systemListener.onDisconnectEvent((DisconnectEvent) message);
276 responseCache.invalidateAll();
277 disconnectOccured = true;
278 } else if (message instanceof SwitchIdleEvent) {
279 systemListener.onSwitchIdleEvent((SwitchIdleEvent) message);
281 } else if (message instanceof EchoRequestMessage) {
282 messageListener.onEchoRequestMessage((EchoRequestMessage) message);
283 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
284 } else if (message instanceof ErrorMessage) {
285 messageListener.onErrorMessage((ErrorMessage) message);
286 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
287 } else if (message instanceof ExperimenterMessage) {
288 messageListener.onExperimenterMessage((ExperimenterMessage) message);
289 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
290 } else if (message instanceof FlowRemovedMessage) {
291 messageListener.onFlowRemovedMessage((FlowRemovedMessage) message);
292 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
293 } else if (message instanceof HelloMessage) {
294 LOG.info("Hello received / branch");
295 messageListener.onHelloMessage((HelloMessage) message);
296 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
297 } else if (message instanceof MultipartReplyMessage) {
298 messageListener.onMultipartReplyMessage((MultipartReplyMessage) message);
299 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
300 } else if (message instanceof PacketInMessage) {
301 messageListener.onPacketInMessage((PacketInMessage) message);
302 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
303 } else if (message instanceof PortStatusMessage) {
304 messageListener.onPortStatusMessage((PortStatusMessage) message);
305 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
307 LOG.warn("message listening not supported for type: {}", message.getClass());
310 if (message instanceof OfHeader) {
311 LOG.debug("OFheader msg received");
312 RpcResponseKey key = createRpcResponseKey((OfHeader) message);
313 final ResponseExpectedRpcListener<?> listener = findRpcResponse(key);
314 if (listener != null) {
315 LOG.debug("corresponding rpcFuture found");
316 listener.completed((OfHeader)message);
317 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
318 LOG.debug("after setting rpcFuture");
319 responseCache.invalidate(key);
321 LOG.warn("received unexpected rpc response: {}", key);
324 LOG.warn("message listening not supported for type: {}", message.getClass());
329 private <T> ListenableFuture<RpcResult<T>> enqueueMessage(final AbstractRpcListener<T> promise) {
330 LOG.debug("Submitting promise {}", promise);
332 if (!output.enqueue(promise)) {
333 LOG.debug("Message queue is full, rejecting execution");
334 promise.failedRpc(QUEUE_FULL_EXCEPTION);
336 LOG.debug("Promise enqueued successfully");
339 return promise.getResult();
343 * sends given message to switch, sending result will be reported via return value
344 * @param input message to send
345 * @param failureInfo describes, what type of message caused failure by sending
346 * @return future object, <ul>
347 * <li>if send successful, {@link RpcResult} without errors and successful
348 * status will be returned, </li>
349 * <li>else {@link RpcResult} will contain errors and failed status</li>
352 private ListenableFuture<RpcResult<Void>> sendToSwitchFuture(
353 final DataObject input, final String failureInfo) {
354 statisticsCounters.incrementCounter(CounterEventTypes.DS_ENTERED_OFJAVA);
355 return enqueueMessage(new SimpleRpcListener(input, failureInfo));
359 * sends given message to switch, sending result or switch response will be reported via return value
360 * @param input message to send
361 * @param responseClazz type of response
362 * @param failureInfo describes, what type of message caused failure by sending
363 * @return future object, <ul>
364 * <li>if send fails, {@link RpcResult} will contain errors and failed status </li>
365 * <li>else {@link RpcResult} will be stored in responseCache and wait for particular timeout
366 * ({@link ConnectionAdapterImpl#RPC_RESPONSE_EXPIRATION}),
367 * <ul><li>either switch will manage to answer
368 * and then corresponding response message will be set into returned future</li>
369 * <li>or response in cache will expire and returned future will be cancelled</li></ul>
373 private <IN extends OfHeader, OUT extends OfHeader> ListenableFuture<RpcResult<OUT>> sendToSwitchExpectRpcResultFuture(
374 final IN input, final Class<OUT> responseClazz, final String failureInfo) {
375 final RpcResponseKey key = new RpcResponseKey(input.getXid(), responseClazz.getName());
376 final ResponseExpectedRpcListener<OUT> listener =
377 new ResponseExpectedRpcListener<>(input, failureInfo, responseCache, key);
378 statisticsCounters.incrementCounter(CounterEventTypes.DS_ENTERED_OFJAVA);
379 return enqueueMessage(listener);
383 * @param resultFuture
385 * @param errorSeverity
389 private static SettableFuture<Boolean> handleTransportChannelFuture(
390 final ChannelFuture resultFuture) {
392 final SettableFuture<Boolean> transportResult = SettableFuture.create();
394 resultFuture.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
397 public void operationComplete(
398 final io.netty.util.concurrent.Future<? super Void> future)
400 transportResult.set(future.isSuccess());
401 if (!future.isSuccess()) {
402 transportResult.setException(future.cause());
406 return transportResult;
413 private static RpcResponseKey createRpcResponseKey(final OfHeader message) {
414 return new RpcResponseKey(message.getXid(), message.getImplementedInterface().getName());
420 private ResponseExpectedRpcListener<?> findRpcResponse(final RpcResponseKey key) {
421 return responseCache.getIfPresent(key);
425 public void setSystemListener(final SystemNotificationsListener systemListener) {
426 this.systemListener = systemListener;
430 public void checkListeners() {
431 final StringBuilder buffer = new StringBuilder();
432 if (systemListener == null) {
433 buffer.append("SystemListener ");
435 if (messageListener == null) {
436 buffer.append("MessageListener ");
438 if (connectionReadyListener == null) {
439 buffer.append("ConnectionReadyListener ");
442 Preconditions.checkState(buffer.length() == 0, "Missing listeners: %s", buffer.toString());
446 public void fireConnectionReadyNotification() {
447 new Thread(new Runnable() {
450 connectionReadyListener.onConnectionReady();
456 public void setConnectionReadyListener(
457 final ConnectionReadyListener connectionReadyListener) {
458 this.connectionReadyListener = connectionReadyListener;
462 public InetSocketAddress getRemoteAddress() {
463 return (InetSocketAddress) channel.remoteAddress();
467 * Used only for testing purposes
470 public void setResponseCache(Cache<RpcResponseKey, ResponseExpectedRpcListener<?>> cache) {
471 this.responseCache = cache;