1 /* Copyright (C)2013 Pantheon Technologies, s.r.o. All rights reserved. */
3 package org.opendaylight.openflowjava.protocol.impl.connection;
5 import io.netty.channel.Channel;
6 import io.netty.channel.ChannelFuture;
7 import io.netty.util.concurrent.GenericFutureListener;
9 import java.util.Collection;
10 import java.util.Collections;
11 import java.util.List;
12 import java.util.concurrent.Future;
13 import java.util.concurrent.TimeUnit;
15 import org.opendaylight.controller.sal.common.util.RpcErrors;
16 import org.opendaylight.controller.sal.common.util.Rpcs;
17 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput;
18 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput;
19 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoInput;
20 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoOutput;
21 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoReplyInput;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoRequestMessage;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterInput;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessage;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowModInput;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncInput;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncOutput;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigInput;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigOutput;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesInput;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigInput;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigOutput;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GroupModInput;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloInput;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessage;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MeterModInput;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestMessage;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OpenflowProtocolListener;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketOutInput;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortModInput;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestInput;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutput;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetAsyncInput;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetConfigInput;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.TableModInput;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.DisconnectEvent;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SystemNotificationsListener;
55 import org.opendaylight.yangtools.yang.binding.DataObject;
56 import org.opendaylight.yangtools.yang.binding.Notification;
57 import org.opendaylight.yangtools.yang.common.RpcError;
58 import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
59 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
60 import org.opendaylight.yangtools.yang.common.RpcResult;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
64 import com.google.common.cache.Cache;
65 import com.google.common.cache.CacheBuilder;
66 import com.google.common.cache.RemovalListener;
67 import com.google.common.cache.RemovalNotification;
68 import com.google.common.collect.Lists;
69 import com.google.common.util.concurrent.SettableFuture;
73 * @author michal.polkorab
75 public class ConnectionAdapterImpl implements ConnectionFacade {
77 /** after this time, rpc future response objects will be thrown away (in minutes) */
78 public static final int RPC_RESPONSE_EXPIRATION = 1;
80 protected static final Logger LOG = LoggerFactory
81 .getLogger(ConnectionAdapterImpl.class);
83 private static final String APPLICATION_TAG = "OPENFLOW_LIBRARY";
84 private static final String TAG = "OPENFLOW";
85 private Channel channel;
86 private OpenflowProtocolListener messageListener;
87 /** expiring cache for future rpcResponses */
88 protected Cache<RpcResponseKey, SettableFuture<?>> responseCache;
89 private SystemNotificationsListener systemListener;
90 private boolean disconnectOccured = false;
95 public ConnectionAdapterImpl() {
96 responseCache = CacheBuilder.newBuilder()
98 .expireAfterWrite(RPC_RESPONSE_EXPIRATION, TimeUnit.MINUTES)
99 .removalListener(new RemovalListener<RpcResponseKey, SettableFuture<?>>() {
102 public void onRemoval(
103 RemovalNotification<RpcResponseKey, SettableFuture<?>> notification) {
104 SettableFuture<?> future = notification.getValue();
105 if (!future.isDone()) {
106 LOG.warn("rpc response discarded: " + notification.getKey());
111 LOG.info("ConnectionAdapter created");
115 * @param channel the channel to be set - used for communication
117 public void setChannel(Channel channel) {
118 this.channel = channel;
122 public Future<RpcResult<BarrierOutput>> barrier(BarrierInput input) {
123 return sendToSwitchExpectRpcResultFuture(
124 input, BarrierOutput.class, "barrier-input sending failed");
128 public Future<RpcResult<EchoOutput>> echo(EchoInput input) {
129 return sendToSwitchExpectRpcResultFuture(
130 input, EchoOutput.class, "echo-input sending failed");
134 public Future<RpcResult<Void>> echoReply(EchoReplyInput input) {
135 return sendToSwitchFuture(input, "echo-reply sending failed");
139 public Future<RpcResult<Void>> experimenter(ExperimenterInput input) {
140 return sendToSwitchFuture(input, "experimenter sending failed");
144 public Future<RpcResult<Void>> flowMod(FlowModInput input) {
145 return sendToSwitchFuture(input, "flow-mod sending failed");
149 public Future<RpcResult<GetConfigOutput>> getConfig(GetConfigInput input) {
150 return sendToSwitchExpectRpcResultFuture(
151 input, GetConfigOutput.class, "get-config-input sending failed");
155 public Future<RpcResult<GetFeaturesOutput>> getFeatures(
156 GetFeaturesInput input) {
157 return sendToSwitchExpectRpcResultFuture(
158 input, GetFeaturesOutput.class, "get-features-input sending failed");
162 public Future<RpcResult<GetQueueConfigOutput>> getQueueConfig(
163 GetQueueConfigInput input) {
164 return sendToSwitchExpectRpcResultFuture(
165 input, GetQueueConfigOutput.class, "get-queue-config-input sending failed");
169 public Future<RpcResult<Void>> groupMod(GroupModInput input) {
170 return sendToSwitchFuture(input, "group-mod-input sending failed");
174 public Future<RpcResult<Void>> hello(HelloInput input) {
175 return sendToSwitchFuture(input, "hello-input sending failed");
179 public Future<RpcResult<Void>> meterMod(MeterModInput input) {
180 return sendToSwitchFuture(input, "meter-mod-input sending failed");
184 public Future<RpcResult<Void>> packetOut(PacketOutInput input) {
185 return sendToSwitchFuture(input, "packet-out-input sending failed");
189 public Future<RpcResult<Void>> portMod(PortModInput input) {
190 return sendToSwitchFuture(input, "port-mod-input sending failed");
194 public Future<RpcResult<RoleRequestOutput>> roleRequest(
195 RoleRequestInput input) {
196 return sendToSwitchExpectRpcResultFuture(
197 input, RoleRequestOutput.class, "role-request-config-input sending failed");
201 public Future<RpcResult<Void>> setConfig(SetConfigInput input) {
202 return sendToSwitchFuture(input, "set-config-input sending failed");
206 public Future<RpcResult<Void>> tableMod(TableModInput input) {
207 return sendToSwitchFuture(input, "table-mod-input sending failed");
211 public Future<RpcResult<GetAsyncOutput>> getAsync(GetAsyncInput input) {
212 return sendToSwitchExpectRpcResultFuture(
213 input, GetAsyncOutput.class, "get-async-input sending failed");
217 public Future<RpcResult<Void>> setAsync(SetAsyncInput input) {
218 return sendToSwitchFuture(input, "set-async-input sending failed");
222 public Future<Boolean> disconnect() {
223 ChannelFuture disconnectResult = channel.disconnect();
224 responseCache.invalidateAll();
225 disconnectOccured = true;
227 String failureInfo = "switch disconnecting failed";
228 ErrorSeverity errorSeverity = ErrorSeverity.ERROR;
229 String message = "Check the switch connection";
230 return handleTransportChannelFuture(disconnectResult, failureInfo, errorSeverity, message);
234 public boolean isAlive() {
235 return channel.isOpen();
239 public void setMessageListener(OpenflowProtocolListener messageListener) {
240 this.messageListener = messageListener;
244 public void consume(DataObject message) {
245 LOG.debug("Consume msg");
246 if (disconnectOccured ) {
249 if (message instanceof Notification) {
251 if (message instanceof DisconnectEvent) {
252 systemListener.onDisconnectEvent((DisconnectEvent) message);
253 responseCache.invalidateAll();
254 disconnectOccured = true;
257 else if (message instanceof EchoRequestMessage) {
258 messageListener.onEchoRequestMessage((EchoRequestMessage) message);
259 } else if (message instanceof ErrorMessage) {
260 messageListener.onErrorMessage((ErrorMessage) message);
261 } else if (message instanceof ExperimenterMessage) {
262 messageListener.onExperimenterMessage((ExperimenterMessage) message);
263 } else if (message instanceof FlowRemovedMessage) {
264 messageListener.onFlowRemovedMessage((FlowRemovedMessage) message);
265 } else if (message instanceof HelloMessage) {
266 LOG.info("Hello received / branch");
267 messageListener.onHelloMessage((HelloMessage) message);
268 } else if (message instanceof MultipartReplyMessage) {
269 messageListener.onMultipartReplyMessage((MultipartReplyMessage) message);
270 } else if (message instanceof MultipartRequestMessage) {
271 messageListener.onMultipartRequestMessage((MultipartRequestMessage) message);
272 } else if (message instanceof PacketInMessage) {
273 messageListener.onPacketInMessage((PacketInMessage) message);
274 } else if (message instanceof PortStatusMessage) {
275 messageListener.onPortStatusMessage((PortStatusMessage) message);
277 LOG.warn("message listening not supported for type: "+message.getClass());
280 if (message instanceof OfHeader) {
281 LOG.debug("OFheader msg received");
282 RpcResponseKey key = createRpcResponseKey((OfHeader) message);
283 SettableFuture<RpcResult<?>> rpcFuture = findRpcResponse(key);
284 if (rpcFuture != null) {
285 LOG.debug("corresponding rpcFuture found");
286 List<RpcError> errors = Collections.emptyList();
287 rpcFuture.set(Rpcs.getRpcResult(true, message, errors));
288 responseCache.invalidate(key);
290 LOG.warn("received unexpected rpc response: "+key);
293 LOG.warn("message listening not supported for type: "+message.getClass());
299 * sends given message to switch, sending result will be reported via return value
300 * @param input message to send
301 * @param failureInfo describes, what type of message caused failure by sending
302 * @return future object, <ul>
303 * <li>if send successful, {@link RpcResult} without errors and successful
304 * status will be returned, </li>
305 * <li>else {@link RpcResult} will contain errors and failed status</li>
308 private SettableFuture<RpcResult<Void>> sendToSwitchFuture(
309 DataObject input, final String failureInfo) {
310 LOG.debug("going to flush");
311 ChannelFuture resultFuture = channel.writeAndFlush(input);
312 LOG.debug("flushed");
314 ErrorSeverity errorSeverity = ErrorSeverity.ERROR;
315 String errorMessage = "check switch connection";
316 return handleRpcChannelFuture(resultFuture, failureInfo, errorSeverity, errorMessage);
320 * sends given message to switch, sending result or switch response will be reported via return value
321 * @param input message to send
322 * @param responseClazz type of response
323 * @param failureInfo describes, what type of message caused failure by sending
324 * @return future object, <ul>
325 * <li>if send fails, {@link RpcResult} will contain errors and failed status </li>
326 * <li>else {@link RpcResult} will be stored in responseCache and wait for particular timeout
327 * ({@link ConnectionAdapterImpl#RPC_RESPONSE_EXPIRATION}),
328 * <ul><li>either switch will manage to answer
329 * and then corresponding response message will be set into returned future</li>
330 * <li>or response in cache will expire and returned future will be cancelled</li></ul>
334 private <IN extends OfHeader, OUT extends OfHeader> SettableFuture<RpcResult<OUT>> sendToSwitchExpectRpcResultFuture(
335 IN input, Class<OUT> responseClazz, final String failureInfo) {
336 LOG.debug("going to flush");
337 SettableFuture<RpcResult<OUT>> rpcResult = SettableFuture.create();
338 RpcResponseKey key = new RpcResponseKey(input.getXid(), responseClazz);
339 responseCache.put(key, rpcResult);
340 ChannelFuture resultFuture = channel.writeAndFlush(input);
341 LOG.debug("flushed");
343 ErrorSeverity errorSeverity = ErrorSeverity.ERROR;
344 String errorMessage = "check switch connection";
346 return handleRpcChannelFutureWithResponse(resultFuture, failureInfo, errorSeverity,
347 errorMessage, input, responseClazz, rpcResult, key);
351 * @param resultFuture
355 private SettableFuture<RpcResult<Void>> handleRpcChannelFuture(
356 ChannelFuture resultFuture, final String failureInfo,
357 final ErrorSeverity errorSeverity, final String errorMessage) {
359 final SettableFuture<RpcResult<Void>> rpcResult = SettableFuture.create();
360 LOG.debug("handlerpcchannelfuture");
361 resultFuture.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
364 public void operationComplete(
365 io.netty.util.concurrent.Future<? super Void> future)
367 LOG.debug("operation complete");
368 Collection<RpcError> errors = Collections.emptyList();
370 if (future.cause() != null) {
371 LOG.debug("future.cause != null");
372 RpcError rpcError = buildRpcError(failureInfo,
373 errorSeverity, errorMessage, future.cause());
374 errors = Lists.newArrayList(rpcError);
377 rpcResult.set(Rpcs.getRpcResult(
388 * @param resultFuture
390 * @param errorSeverity
391 * @param errorMessage
393 * @param responseClazz
398 private <IN extends OfHeader, OUT extends OfHeader> SettableFuture<RpcResult<OUT>> handleRpcChannelFutureWithResponse(
399 ChannelFuture resultFuture, final String failureInfo,
400 final ErrorSeverity errorSeverity, final String errorMessage,
401 final IN input, Class<OUT> responseClazz, final SettableFuture<RpcResult<OUT>> rpcResult, final RpcResponseKey key) {
402 LOG.debug("handleRpcchanfuture with response");
404 resultFuture.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
407 public void operationComplete(
408 io.netty.util.concurrent.Future<? super Void> future)
411 LOG.debug("operation complete");
412 Collection<RpcError> errors = Collections.emptyList();
413 if (future.cause() != null) {
414 LOG.debug("ChannelFuture.cause != null");
415 RpcError rpcError = buildRpcError(failureInfo,
416 errorSeverity, errorMessage, future.cause());
417 errors = Lists.newArrayList(rpcError);
418 rpcResult.set(Rpcs.getRpcResult(
423 responseCache.invalidate(key);
425 LOG.debug("ChannelFuture.cause == null");
426 if (responseCache.getIfPresent(key) == null) {
427 LOG.debug("responcache: key wasn't present");
436 * @param resultFuture
438 * @param errorSeverity
442 private static SettableFuture<Boolean> handleTransportChannelFuture(
443 ChannelFuture resultFuture, final String failureInfo,
444 final ErrorSeverity errorSeverity, final String message) {
446 final SettableFuture<Boolean> transportResult = SettableFuture.create();
448 resultFuture.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
451 public void operationComplete(
452 io.netty.util.concurrent.Future<? super Void> future)
454 transportResult.set(future.isSuccess());
455 transportResult.setException(future.cause());
458 return transportResult;
465 protected RpcError buildRpcError(String info, ErrorSeverity severity, String message,
467 RpcError error = RpcErrors.getRpcError(APPLICATION_TAG, TAG, info, severity, message,
468 ErrorType.RPC, cause);
476 protected RpcError buildTransportError(String info, ErrorSeverity severity, String message,
478 RpcError error = RpcErrors.getRpcError(APPLICATION_TAG, TAG, info, severity, message,
479 ErrorType.TRANSPORT, cause);
487 private static RpcResponseKey createRpcResponseKey(OfHeader message) {
488 return new RpcResponseKey(message.getXid(), message.getClass());
494 @SuppressWarnings("unchecked")
495 private SettableFuture<RpcResult<?>> findRpcResponse(RpcResponseKey key) {
496 return (SettableFuture<RpcResult<?>>) responseCache.getIfPresent(key);
500 public void setSystemListener(SystemNotificationsListener systemListener) {
501 this.systemListener = systemListener;
505 public void checkListeners() {
506 StringBuffer buffer = new StringBuffer();
507 if (systemListener == null) {
508 buffer.append("SystemListener ");
510 if (messageListener == null) {
511 buffer.append("MessageListener ");
514 if (buffer.length() > 0) {
515 throw new IllegalStateException("Missing listeners: " + buffer.toString());