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.connection;
12 import io.netty.channel.Channel;
13 import io.netty.channel.ChannelFuture;
14 import io.netty.util.concurrent.GenericFutureListener;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.List;
19 import java.util.concurrent.Future;
20 import java.util.concurrent.TimeUnit;
22 import org.opendaylight.controller.sal.common.util.RpcErrors;
23 import org.opendaylight.controller.sal.common.util.Rpcs;
24 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionReadyListener;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoInput;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoOutput;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoReplyInput;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoRequestMessage;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterInput;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessage;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowModInput;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncInput;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncOutput;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigInput;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigOutput;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesInput;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigInput;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigOutput;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GroupModInput;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloInput;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessage;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MeterModInput;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInput;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OpenflowProtocolListener;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketOutInput;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortModInput;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestInput;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutput;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetAsyncInput;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetConfigInput;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.TableModInput;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.DisconnectEvent;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SwitchIdleEvent;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SystemNotificationsListener;
64 import org.opendaylight.yangtools.yang.binding.DataContainer;
65 import org.opendaylight.yangtools.yang.binding.DataObject;
66 import org.opendaylight.yangtools.yang.binding.Notification;
67 import org.opendaylight.yangtools.yang.common.RpcError;
68 import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
69 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
70 import org.opendaylight.yangtools.yang.common.RpcResult;
71 import org.slf4j.Logger;
72 import org.slf4j.LoggerFactory;
74 import com.google.common.cache.Cache;
75 import com.google.common.cache.CacheBuilder;
76 import com.google.common.cache.RemovalListener;
77 import com.google.common.cache.RemovalNotification;
78 import com.google.common.collect.Lists;
79 import com.google.common.util.concurrent.SettableFuture;
82 * Handles messages (notifications + rpcs) and connections
84 * @author michal.polkorab
86 public class ConnectionAdapterImpl implements ConnectionFacade {
88 /** after this time, rpc future response objects will be thrown away (in minutes) */
89 public static final int RPC_RESPONSE_EXPIRATION = 1;
91 protected static final Logger LOG = LoggerFactory
92 .getLogger(ConnectionAdapterImpl.class);
94 private static final String APPLICATION_TAG = "OPENFLOW_LIBRARY";
95 private static final String TAG = "OPENFLOW";
96 private Channel channel;
97 private OpenflowProtocolListener messageListener;
98 /** expiring cache for future rpcResponses */
99 protected Cache<RpcResponseKey, SettableFuture<?>> responseCache;
100 private SystemNotificationsListener systemListener;
101 private boolean disconnectOccured = false;
103 protected ConnectionReadyListener connectionReadyListener;
108 public ConnectionAdapterImpl() {
109 responseCache = CacheBuilder.newBuilder()
111 .expireAfterWrite(RPC_RESPONSE_EXPIRATION, TimeUnit.MINUTES)
112 .removalListener(new ResponseRemovalListener()).build();
113 LOG.debug("ConnectionAdapter created");
117 * @param channel the channel to be set - used for communication
119 public void setChannel(Channel channel) {
120 this.channel = channel;
124 public Future<RpcResult<BarrierOutput>> barrier(BarrierInput input) {
125 return sendToSwitchExpectRpcResultFuture(
126 input, BarrierOutput.class, "barrier-input sending failed");
130 public Future<RpcResult<EchoOutput>> echo(EchoInput input) {
131 return sendToSwitchExpectRpcResultFuture(
132 input, EchoOutput.class, "echo-input sending failed");
136 public Future<RpcResult<Void>> echoReply(EchoReplyInput input) {
137 return sendToSwitchFuture(input, "echo-reply sending failed");
141 public Future<RpcResult<Void>> experimenter(ExperimenterInput input) {
142 return sendToSwitchFuture(input, "experimenter sending failed");
146 public Future<RpcResult<Void>> flowMod(FlowModInput input) {
147 return sendToSwitchFuture(input, "flow-mod sending failed");
151 public Future<RpcResult<GetConfigOutput>> getConfig(GetConfigInput input) {
152 return sendToSwitchExpectRpcResultFuture(
153 input, GetConfigOutput.class, "get-config-input sending failed");
157 public Future<RpcResult<GetFeaturesOutput>> getFeatures(
158 GetFeaturesInput input) {
159 return sendToSwitchExpectRpcResultFuture(
160 input, GetFeaturesOutput.class, "get-features-input sending failed");
164 public Future<RpcResult<GetQueueConfigOutput>> getQueueConfig(
165 GetQueueConfigInput input) {
166 return sendToSwitchExpectRpcResultFuture(
167 input, GetQueueConfigOutput.class, "get-queue-config-input sending failed");
171 public Future<RpcResult<Void>> groupMod(GroupModInput input) {
172 return sendToSwitchFuture(input, "group-mod-input sending failed");
176 public Future<RpcResult<Void>> hello(HelloInput input) {
177 return sendToSwitchFuture(input, "hello-input sending failed");
181 public Future<RpcResult<Void>> meterMod(MeterModInput input) {
182 return sendToSwitchFuture(input, "meter-mod-input sending failed");
186 public Future<RpcResult<Void>> packetOut(PacketOutInput input) {
187 return sendToSwitchFuture(input, "packet-out-input sending failed");
191 public Future<RpcResult<Void>> multipartRequest(MultipartRequestInput input) {
192 return sendToSwitchFuture(input, "multi-part-request sending failed");
196 public Future<RpcResult<Void>> portMod(PortModInput input) {
197 return sendToSwitchFuture(input, "port-mod-input sending failed");
201 public Future<RpcResult<RoleRequestOutput>> roleRequest(
202 RoleRequestInput input) {
203 return sendToSwitchExpectRpcResultFuture(
204 input, RoleRequestOutput.class, "role-request-config-input sending failed");
208 public Future<RpcResult<Void>> setConfig(SetConfigInput input) {
209 return sendToSwitchFuture(input, "set-config-input sending failed");
213 public Future<RpcResult<Void>> tableMod(TableModInput input) {
214 return sendToSwitchFuture(input, "table-mod-input sending failed");
218 public Future<RpcResult<GetAsyncOutput>> getAsync(GetAsyncInput input) {
219 return sendToSwitchExpectRpcResultFuture(
220 input, GetAsyncOutput.class, "get-async-input sending failed");
224 public Future<RpcResult<Void>> setAsync(SetAsyncInput input) {
225 return sendToSwitchFuture(input, "set-async-input sending failed");
229 public Future<Boolean> disconnect() {
230 ChannelFuture disconnectResult = channel.disconnect();
231 responseCache.invalidateAll();
232 disconnectOccured = true;
234 String failureInfo = "switch disconnecting failed";
235 ErrorSeverity errorSeverity = ErrorSeverity.ERROR;
236 String message = "Check the switch connection";
237 return handleTransportChannelFuture(disconnectResult, failureInfo, errorSeverity, message);
241 public boolean isAlive() {
242 return channel.isOpen();
246 public void setMessageListener(OpenflowProtocolListener messageListener) {
247 this.messageListener = messageListener;
251 public void consume(DataObject message) {
252 LOG.debug("ConsumeIntern msg");
253 if (disconnectOccured ) {
256 if (message instanceof Notification) {
258 if (message instanceof DisconnectEvent) {
259 systemListener.onDisconnectEvent((DisconnectEvent) message);
260 responseCache.invalidateAll();
261 disconnectOccured = true;
262 } else if (message instanceof SwitchIdleEvent) {
263 systemListener.onSwitchIdleEvent((SwitchIdleEvent) message);
266 else if (message instanceof EchoRequestMessage) {
267 messageListener.onEchoRequestMessage((EchoRequestMessage) message);
268 } else if (message instanceof ErrorMessage) {
269 messageListener.onErrorMessage((ErrorMessage) message);
270 } else if (message instanceof ExperimenterMessage) {
271 messageListener.onExperimenterMessage((ExperimenterMessage) message);
272 } else if (message instanceof FlowRemovedMessage) {
273 messageListener.onFlowRemovedMessage((FlowRemovedMessage) message);
274 } else if (message instanceof HelloMessage) {
275 LOG.info("Hello received / branch");
276 messageListener.onHelloMessage((HelloMessage) message);
277 } else if (message instanceof MultipartReplyMessage) {
278 messageListener.onMultipartReplyMessage((MultipartReplyMessage) message);
279 } else if (message instanceof PacketInMessage) {
280 messageListener.onPacketInMessage((PacketInMessage) message);
281 } else if (message instanceof PortStatusMessage) {
282 messageListener.onPortStatusMessage((PortStatusMessage) message);
284 LOG.warn("message listening not supported for type: "+message.getClass());
287 if (message instanceof OfHeader) {
288 LOG.debug("OFheader msg received");
289 RpcResponseKey key = createRpcResponseKey((OfHeader) message);
290 final SettableFuture<RpcResult<?>> rpcFuture = findRpcResponse(key);
291 if (rpcFuture != null) {
292 LOG.debug("corresponding rpcFuture found");
293 List<RpcError> errors = Collections.emptyList();
294 LOG.debug("before setting rpcFuture");
295 rpcFuture.set(Rpcs.getRpcResult(true, message, errors));
296 LOG.debug("after setting rpcFuture");
297 responseCache.invalidate(key);
299 LOG.warn("received unexpected rpc response: "+key);
302 LOG.warn("message listening not supported for type: "+message.getClass());
308 * sends given message to switch, sending result will be reported via return value
309 * @param input message to send
310 * @param failureInfo describes, what type of message caused failure by sending
311 * @return future object, <ul>
312 * <li>if send successful, {@link RpcResult} without errors and successful
313 * status will be returned, </li>
314 * <li>else {@link RpcResult} will contain errors and failed status</li>
317 private SettableFuture<RpcResult<Void>> sendToSwitchFuture(
318 DataObject input, final String failureInfo) {
319 LOG.debug("going to flush");
320 ChannelFuture resultFuture = channel.writeAndFlush(input);
321 LOG.debug("flushed");
323 ErrorSeverity errorSeverity = ErrorSeverity.ERROR;
324 String errorMessage = "check switch connection";
325 return handleRpcChannelFuture(resultFuture, failureInfo, errorSeverity, errorMessage);
329 * sends given message to switch, sending result or switch response will be reported via return value
330 * @param input message to send
331 * @param responseClazz type of response
332 * @param failureInfo describes, what type of message caused failure by sending
333 * @return future object, <ul>
334 * <li>if send fails, {@link RpcResult} will contain errors and failed status </li>
335 * <li>else {@link RpcResult} will be stored in responseCache and wait for particular timeout
336 * ({@link ConnectionAdapterImpl#RPC_RESPONSE_EXPIRATION}),
337 * <ul><li>either switch will manage to answer
338 * and then corresponding response message will be set into returned future</li>
339 * <li>or response in cache will expire and returned future will be cancelled</li></ul>
343 private <IN extends OfHeader, OUT extends OfHeader> SettableFuture<RpcResult<OUT>> sendToSwitchExpectRpcResultFuture(
344 IN input, Class<OUT> responseClazz, final String failureInfo) {
345 LOG.debug("going to flush");
346 SettableFuture<RpcResult<OUT>> rpcResult = SettableFuture.create();
347 RpcResponseKey key = new RpcResponseKey(input.getXid(), responseClazz.getName());
348 responseCache.put(key, rpcResult);
349 ChannelFuture resultFuture = channel.writeAndFlush(input);
350 LOG.debug("flushed");
352 ErrorSeverity errorSeverity = ErrorSeverity.ERROR;
353 String errorMessage = "check switch connection";
355 return handleRpcChannelFutureWithResponse(resultFuture, failureInfo, errorSeverity,
356 errorMessage, input, responseClazz, rpcResult, key);
360 * @param resultFuture
364 private SettableFuture<RpcResult<Void>> handleRpcChannelFuture(
365 ChannelFuture resultFuture, final String failureInfo,
366 final ErrorSeverity errorSeverity, final String errorMessage) {
368 final SettableFuture<RpcResult<Void>> rpcResult = SettableFuture.create();
369 LOG.debug("handlerpcchannelfuture");
370 resultFuture.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
373 public void operationComplete(
374 io.netty.util.concurrent.Future<? super Void> future)
376 LOG.debug("operation complete");
377 Collection<RpcError> errors = Collections.emptyList();
379 if (future.cause() != null) {
380 LOG.debug("future.cause != null");
381 RpcError rpcError = buildRpcError(failureInfo,
382 errorSeverity, errorMessage, future.cause());
383 errors = Lists.newArrayList(rpcError);
386 rpcResult.set(Rpcs.getRpcResult(
397 * @param resultFuture
399 * @param errorSeverity
400 * @param errorMessage
402 * @param responseClazz
403 * @param key of rpcResponse
406 private <IN extends OfHeader, OUT extends OfHeader> SettableFuture<RpcResult<OUT>> handleRpcChannelFutureWithResponse(
407 ChannelFuture resultFuture, final String failureInfo,
408 final ErrorSeverity errorSeverity, final String errorMessage,
409 final IN input, Class<OUT> responseClazz, final SettableFuture<RpcResult<OUT>> rpcResult, final RpcResponseKey key) {
410 LOG.debug("handleRpcchanfuture with response");
412 resultFuture.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
415 public void operationComplete(
416 io.netty.util.concurrent.Future<? super Void> future)
419 LOG.debug("operation complete");
420 Collection<RpcError> errors = Collections.emptyList();
421 if (future.cause() != null) {
422 LOG.debug("ChannelFuture.cause != null");
423 RpcError rpcError = buildRpcError(failureInfo,
424 errorSeverity, errorMessage, future.cause());
425 errors = Lists.newArrayList(rpcError);
426 rpcResult.set(Rpcs.getRpcResult(
431 responseCache.invalidate(key);
433 LOG.debug("ChannelFuture.cause == null");
434 if (responseCache.getIfPresent(key) == null) {
435 LOG.debug("responcache: key wasn't present");
444 * @param resultFuture
446 * @param errorSeverity
450 private static SettableFuture<Boolean> handleTransportChannelFuture(
451 ChannelFuture resultFuture, final String failureInfo,
452 final ErrorSeverity errorSeverity, final String message) {
454 final SettableFuture<Boolean> transportResult = SettableFuture.create();
456 resultFuture.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
459 public void operationComplete(
460 io.netty.util.concurrent.Future<? super Void> future)
462 transportResult.set(future.isSuccess());
463 if (!future.isSuccess()) {
464 transportResult.setException(future.cause());
468 return transportResult;
475 protected RpcError buildRpcError(String info, ErrorSeverity severity, String message,
477 RpcError error = RpcErrors.getRpcError(APPLICATION_TAG, TAG, info, severity, message,
478 ErrorType.RPC, cause);
486 protected RpcError buildTransportError(String info, ErrorSeverity severity, String message,
488 RpcError error = RpcErrors.getRpcError(APPLICATION_TAG, TAG, info, severity, message,
489 ErrorType.TRANSPORT, cause);
497 private static RpcResponseKey createRpcResponseKey(OfHeader message) {
498 return new RpcResponseKey(message.getXid(), message.getImplementedInterface().getName());
504 @SuppressWarnings("unchecked")
505 private SettableFuture<RpcResult<?>> findRpcResponse(RpcResponseKey key) {
506 return (SettableFuture<RpcResult<?>>) responseCache.getIfPresent(key);
510 public void setSystemListener(SystemNotificationsListener systemListener) {
511 this.systemListener = systemListener;
515 public void checkListeners() {
516 StringBuffer buffer = new StringBuffer();
517 if (systemListener == null) {
518 buffer.append("SystemListener ");
520 if (messageListener == null) {
521 buffer.append("MessageListener ");
523 if (connectionReadyListener == null) {
524 buffer.append("ConnectionReadyListener ");
527 if (buffer.length() > 0) {
528 throw new IllegalStateException("Missing listeners: " + buffer.toString());
532 static class ResponseRemovalListener implements RemovalListener<RpcResponseKey, SettableFuture<?>> {
534 public void onRemoval(
535 RemovalNotification<RpcResponseKey, SettableFuture<?>> notification) {
536 SettableFuture<?> future = notification.getValue();
537 if (!future.isDone()) {
538 LOG.warn("rpc response discarded: " + notification.getKey());
545 * Class is used ONLY for exiting msgQueue processing thread
546 * @author michal.polkorab
548 static class ExitingDataObject implements DataObject {
550 public Class<? extends DataContainer> getImplementedInterface() {
556 public void fireConnectionReadyNotification() {
557 new Thread(new Runnable() {
560 connectionReadyListener.onConnectionReady();
567 public void setConnectionReadyListener(
568 ConnectionReadyListener connectionReadyListener) {
569 this.connectionReadyListener = connectionReadyListener;