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");
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 messageListener.onEchoRequestMessage((EchoRequestMessage) message);
284 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
285 } else if (message instanceof ErrorMessage) {
286 messageListener.onErrorMessage((ErrorMessage) message);
287 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
288 } else if (message instanceof ExperimenterMessage) {
289 messageListener.onExperimenterMessage((ExperimenterMessage) message);
290 if (outputManager != null) {
291 outputManager.onMessage((OfHeader) message);
293 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
294 } else if (message instanceof FlowRemovedMessage) {
295 messageListener.onFlowRemovedMessage((FlowRemovedMessage) message);
296 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
297 } else if (message instanceof HelloMessage) {
298 LOG.info("Hello received / branch");
299 messageListener.onHelloMessage((HelloMessage) message);
300 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
301 } else if (message instanceof MultipartReplyMessage) {
302 messageListener.onMultipartReplyMessage((MultipartReplyMessage) message);
303 if (outputManager != null) {
304 outputManager.onMessage((OfHeader) message);
306 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
307 } else if (message instanceof PacketInMessage) {
308 messageListener.onPacketInMessage((PacketInMessage) message);
309 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
310 } else if (message instanceof PortStatusMessage) {
311 messageListener.onPortStatusMessage((PortStatusMessage) message);
312 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
314 LOG.warn("message listening not supported for type: {}", message.getClass());
316 } else if (message instanceof OfHeader) {
317 LOG.debug("OFheader msg received");
319 if (outputManager == null || !outputManager.onMessage((OfHeader) message)) {
320 RpcResponseKey key = createRpcResponseKey((OfHeader) message);
321 final ResponseExpectedRpcListener<?> listener = findRpcResponse(key);
322 if (listener != null) {
323 LOG.debug("corresponding rpcFuture found");
324 listener.completed((OfHeader)message);
325 statisticsCounters.incrementCounter(CounterEventTypes.US_MESSAGE_PASS);
326 LOG.debug("after setting rpcFuture");
327 responseCache.invalidate(key);
329 LOG.warn("received unexpected rpc response: {}", key);
333 LOG.warn("message listening not supported for type: {}", message.getClass());
337 private <T> ListenableFuture<RpcResult<T>> enqueueMessage(final AbstractRpcListener<T> promise) {
338 LOG.debug("Submitting promise {}", promise);
340 if (!output.enqueue(promise)) {
341 LOG.debug("Message queue is full, rejecting execution");
342 promise.failedRpc(QUEUE_FULL_EXCEPTION);
344 LOG.debug("Promise enqueued successfully");
347 return promise.getResult();
351 * sends given message to switch, sending result will be reported via return value
352 * @param input message to send
353 * @param failureInfo describes, what type of message caused failure by sending
354 * @return future object, <ul>
355 * <li>if send successful, {@link RpcResult} without errors and successful
356 * status will be returned, </li>
357 * <li>else {@link RpcResult} will contain errors and failed status</li>
360 private ListenableFuture<RpcResult<Void>> sendToSwitchFuture(
361 final DataObject input, final String failureInfo) {
362 statisticsCounters.incrementCounter(CounterEventTypes.DS_ENTERED_OFJAVA);
363 return enqueueMessage(new SimpleRpcListener(input, failureInfo));
367 * sends given message to switch, sending result or switch response will be reported via return value
368 * @param input message to send
369 * @param responseClazz type of response
370 * @param failureInfo describes, what type of message caused failure by sending
371 * @return future object, <ul>
372 * <li>if send fails, {@link RpcResult} will contain errors and failed status </li>
373 * <li>else {@link RpcResult} will be stored in responseCache and wait for particular timeout
374 * ({@link ConnectionAdapterImpl#RPC_RESPONSE_EXPIRATION}),
375 * <ul><li>either switch will manage to answer
376 * and then corresponding response message will be set into returned future</li>
377 * <li>or response in cache will expire and returned future will be cancelled</li></ul>
381 private <IN extends OfHeader, OUT extends OfHeader> ListenableFuture<RpcResult<OUT>> sendToSwitchExpectRpcResultFuture(
382 final IN input, final Class<OUT> responseClazz, final String failureInfo) {
383 final RpcResponseKey key = new RpcResponseKey(input.getXid(), responseClazz.getName());
384 final ResponseExpectedRpcListener<OUT> listener =
385 new ResponseExpectedRpcListener<>(input, failureInfo, responseCache, key);
386 statisticsCounters.incrementCounter(CounterEventTypes.DS_ENTERED_OFJAVA);
387 return enqueueMessage(listener);
391 * @param resultFuture
393 * @param errorSeverity
397 private static SettableFuture<Boolean> handleTransportChannelFuture(
398 final ChannelFuture resultFuture) {
400 final SettableFuture<Boolean> transportResult = SettableFuture.create();
402 resultFuture.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
405 public void operationComplete(
406 final io.netty.util.concurrent.Future<? super Void> future)
408 transportResult.set(future.isSuccess());
409 if (!future.isSuccess()) {
410 transportResult.setException(future.cause());
414 return transportResult;
421 private static RpcResponseKey createRpcResponseKey(final OfHeader message) {
422 return new RpcResponseKey(message.getXid(), message.getImplementedInterface().getName());
428 private ResponseExpectedRpcListener<?> findRpcResponse(final RpcResponseKey key) {
429 return responseCache.getIfPresent(key);
433 public void setSystemListener(final SystemNotificationsListener systemListener) {
434 this.systemListener = systemListener;
438 public void checkListeners() {
439 final StringBuilder buffer = new StringBuilder();
440 if (systemListener == null) {
441 buffer.append("SystemListener ");
443 if (messageListener == null) {
444 buffer.append("MessageListener ");
446 if (connectionReadyListener == null) {
447 buffer.append("ConnectionReadyListener ");
450 Preconditions.checkState(buffer.length() == 0, "Missing listeners: %s", buffer.toString());
454 public void fireConnectionReadyNotification() {
455 new Thread(new Runnable() {
458 connectionReadyListener.onConnectionReady();
464 public void setConnectionReadyListener(
465 final ConnectionReadyListener connectionReadyListener) {
466 this.connectionReadyListener = connectionReadyListener;
470 public InetSocketAddress getRemoteAddress() {
471 return (InetSocketAddress) channel.remoteAddress();
475 * Used only for testing purposes
478 public void setResponseCache(final Cache<RpcResponseKey, ResponseExpectedRpcListener<?>> cache) {
479 this.responseCache = cache;
483 public boolean isAutoRead() {
484 return channel.config().isAutoRead();
488 public void setAutoRead(final boolean autoRead) {
489 channel.config().setAutoRead(autoRead);
493 public <T extends OutboundQueueHandler> OutboundQueueHandlerRegistration<T> registerOutboundQueueHandler(
494 final T handler, final int maxQueueDepth, final long maxBarrierNanos) {
495 Preconditions.checkState(outputManager == null, "Manager %s already registered", outputManager);
497 final OutboundQueueManager<T> ret = new OutboundQueueManager<>(this, address, handler, maxQueueDepth, maxBarrierNanos);
499 channel.pipeline().addLast(outputManager);
501 return new OutboundQueueHandlerRegistrationImpl<T>(handler) {
503 protected void removeRegistration() {
504 outputManager.close();
505 channel.pipeline().remove(outputManager);
506 outputManager = null;
511 Channel getChannel() {