blob: 2ed3fd2a79da93815fbdac92e1add10bbcb1d964 [file] [log] [blame]
tom0eb04ca2014-08-25 14:34:51 -07001/**
2* Copyright 2011, Big Switch Networks, Inc.
3* Originally created by David Erickson, Stanford University
4*
5* Licensed under the Apache License, Version 2.0 (the "License"); you may
6* not use this file except in compliance with the License. You may obtain
7* a copy of the License at
8*
9* http://www.apache.org/licenses/LICENSE-2.0
10*
11* Unless required by applicable law or agreed to in writing, software
12* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14* License for the specific language governing permissions and limitations
15* under the License.
16**/
17
18package net.onrc.onos.of.ctl.internal;
19
20import java.util.concurrent.TimeUnit;
21
22import org.jboss.netty.channel.ChannelHandlerContext;
23import org.jboss.netty.channel.ChannelStateEvent;
24import org.jboss.netty.channel.Channels;
25import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
26import org.jboss.netty.util.Timeout;
27import org.jboss.netty.util.Timer;
28import org.jboss.netty.util.TimerTask;
29
30/**
31 * Trigger a timeout if a switch fails to complete handshake soon enough.
32 */
33public class HandshakeTimeoutHandler
34 extends SimpleChannelUpstreamHandler {
35 static final HandshakeTimeoutException EXCEPTION =
36 new HandshakeTimeoutException();
37
38 final OFChannelHandler channelHandler;
39 final Timer timer;
40 final long timeoutNanos;
41 volatile Timeout timeout;
42
43 public HandshakeTimeoutHandler(OFChannelHandler channelHandler,
44 Timer timer,
45 long timeoutSeconds) {
46 super();
47 this.channelHandler = channelHandler;
48 this.timer = timer;
49 this.timeoutNanos = TimeUnit.SECONDS.toNanos(timeoutSeconds);
50
51 }
52
53 @Override
54 public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e)
55 throws Exception {
56 if (timeoutNanos > 0) {
57 timeout = timer.newTimeout(new HandshakeTimeoutTask(ctx),
58 timeoutNanos, TimeUnit.NANOSECONDS);
59 }
60 ctx.sendUpstream(e);
61 }
62
63 @Override
64 public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
65 throws Exception {
66 if (timeout != null) {
67 timeout.cancel();
68 timeout = null;
69 }
70 }
71
72 private final class HandshakeTimeoutTask implements TimerTask {
73
74 private final ChannelHandlerContext ctx;
75
76 HandshakeTimeoutTask(ChannelHandlerContext ctx) {
77 this.ctx = ctx;
78 }
79
80 @Override
81 public void run(Timeout t) throws Exception {
82 if (t.isCancelled()) {
83 return;
84 }
85
86 if (!ctx.getChannel().isOpen()) {
87 return;
88 }
89 if (!channelHandler.isHandshakeComplete()) {
90 Channels.fireExceptionCaught(ctx, EXCEPTION);
91 }
92 }
93 }
94}