Merge changes from topic 'BUG-4117'
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / connection / ConnectionContextImpl.java
1 /**
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.openflowplugin.impl.connection;
10
11 import java.math.BigInteger;
12 import java.net.InetSocketAddress;
13 import java.util.concurrent.Callable;
14 import java.util.concurrent.ExecutionException;
15 import java.util.concurrent.Executors;
16 import java.util.concurrent.Future;
17 import java.util.concurrent.TimeUnit;
18 import java.util.concurrent.TimeoutException;
19
20 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
21 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
22 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandlerRegistration;
23 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
24 import org.opendaylight.openflowplugin.api.openflow.connection.HandshakeContext;
25 import org.opendaylight.openflowplugin.api.openflow.connection.OutboundQueueProvider;
26 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceDisconnectedHandler;
27 import org.opendaylight.openflowplugin.impl.statistics.ofpspecific.SessionStatistics;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 /**
34  *
35  */
36 public class ConnectionContextImpl implements ConnectionContext {
37
38     private final ConnectionAdapter connectionAdapter;
39     private volatile CONNECTION_STATE connectionState;
40     private FeaturesReply featuresReply;
41     private NodeId nodeId;
42     private DeviceDisconnectedHandler deviceDisconnectedHandler;
43     private static final Logger LOG = LoggerFactory.getLogger(ConnectionContextImpl.class);
44     private OutboundQueueProvider outboundQueueProvider;
45     private OutboundQueueHandlerRegistration<OutboundQueueProvider> outboundQueueHandlerRegistration;
46     private HandshakeContext handshakeContext;
47
48     /**
49      * @param connectionAdapter
50      */
51     public ConnectionContextImpl(final ConnectionAdapter connectionAdapter) {
52         this.connectionAdapter = connectionAdapter;
53     }
54
55     @Override
56     public ConnectionAdapter getConnectionAdapter() {
57         return connectionAdapter;
58     }
59
60     @Override
61     public OutboundQueue getOutboundQueueProvider() {
62         return this.outboundQueueProvider;
63     }
64
65     @Override
66     public void setOutboundQueueProvider(final OutboundQueueProvider outboundQueueProvider) {
67         this.outboundQueueProvider = outboundQueueProvider;
68     }
69
70     @Override
71     public CONNECTION_STATE getConnectionState() {
72         return connectionState;
73     }
74
75     @Override
76     public NodeId getNodeId() {
77         return nodeId;
78     }
79
80     @Override
81     public void setNodeId(final NodeId nodeId) {
82         this.nodeId = nodeId;
83     }
84
85     @Override
86     public FeaturesReply getFeatures() {
87         return featuresReply;
88     }
89
90     @Override
91     public void setDeviceDisconnectedHandler(final DeviceDisconnectedHandler deviceDisconnectedHandler) {
92         this.deviceDisconnectedHandler = deviceDisconnectedHandler;
93     }
94
95     @Override
96     public void setFeatures(final FeaturesReply featuresReply) {
97         this.featuresReply = featuresReply;
98     }
99
100     @Override
101     public void closeConnection(final boolean propagate) {
102         if (null == nodeId){
103             SessionStatistics.countEvent(connectionAdapter.getRemoteAddress().toString(), SessionStatistics.ConnectionStatus.CONNECTION_DISCONNECTED_BY_OFP);
104         } else {
105             SessionStatistics.countEvent(nodeId.toString(), SessionStatistics.ConnectionStatus.CONNECTION_DISCONNECTED_BY_OFP);
106         }
107         final BigInteger datapathId = featuresReply != null ? featuresReply.getDatapathId() : BigInteger.ZERO;
108         LOG.debug("Actively closing connection: {}, datapathId:{}.",
109                 connectionAdapter.getRemoteAddress(), datapathId);
110         connectionState = ConnectionContext.CONNECTION_STATE.RIP;
111
112         Future<Void> future = Executors.newSingleThreadExecutor().submit(new Callable<Void>() {
113             @Override
114             public Void call() throws Exception {
115                 unregisterOutboundQueue();
116                 return null;
117             }
118         });
119         try {
120             LOG.debug("Waiting 1s for unregistering outbound queue.");
121             future.get(1, TimeUnit.SECONDS);
122             LOG.info("Unregistering outbound queue successful.");
123         } catch (InterruptedException e) {
124             LOG.warn("Unregistering outbound queue was interrupted for node {}", nodeId);
125         } catch (ExecutionException e) {
126             LOG.warn("Unregistering outbound queue throws exception for node {}", nodeId, e);
127         } catch (TimeoutException e) {
128             LOG.warn("Unregistering outbound queue took longer than 1 seconds for node {}", nodeId);
129         }
130
131         closeHandshakeContext();
132
133         if (getConnectionAdapter().isAlive()) {
134             getConnectionAdapter().disconnect();
135         }
136
137         if (propagate) {
138             LOG.debug("Propagating device disconnect for node {}", nodeId);
139             propagateDeviceDisconnectedEvent();
140         } else {
141             LOG.debug("Close connection without propagating for node {}", nodeId);
142         }
143     }
144
145     private void closeHandshakeContext() {
146         LOG.debug("Trying closing handshake context for node {}", nodeId);
147         if (handshakeContext != null) {
148             try {
149                 handshakeContext.close();
150             } catch (Exception e) {
151                 LOG.error("handshake context closing failed:{} ", e);
152             } finally {
153                 handshakeContext = null;
154             }
155         }
156     }
157
158     @Override
159     public void onConnectionClosed() {
160         if (null == nodeId){
161             SessionStatistics.countEvent(connectionAdapter.getRemoteAddress().toString(), SessionStatistics.ConnectionStatus.CONNECTION_DISCONNECTED_BY_DEVICE);
162         } else {
163             SessionStatistics.countEvent(nodeId.toString(), SessionStatistics.ConnectionStatus.CONNECTION_DISCONNECTED_BY_DEVICE);
164         }
165         connectionState = ConnectionContext.CONNECTION_STATE.RIP;
166
167         final InetSocketAddress remoteAddress = connectionAdapter.getRemoteAddress();
168         final Short auxiliaryId;
169         if (null != getFeatures() && null != getFeatures().getAuxiliaryId()) {
170             auxiliaryId = getFeatures().getAuxiliaryId();
171         } else {
172             auxiliaryId = 0;
173         }
174
175         LOG.debug("disconnecting: node={}|auxId={}|connection state = {}",
176                 remoteAddress,
177                 auxiliaryId,
178                 getConnectionState());
179
180         unregisterOutboundQueue();
181         closeHandshakeContext();
182         propagateDeviceDisconnectedEvent();
183     }
184
185     private void propagateDeviceDisconnectedEvent() {
186         if (null != deviceDisconnectedHandler) {
187             final BigInteger datapathId = featuresReply != null ? featuresReply.getDatapathId() : BigInteger.ZERO;
188             LOG.debug("Propagating connection closed event: {}, datapathId:{}.",
189                     connectionAdapter.getRemoteAddress(), datapathId);
190             deviceDisconnectedHandler.onDeviceDisconnected(this);
191         }
192     }
193
194     @Override
195     public void setOutboundQueueHandleRegistration(OutboundQueueHandlerRegistration<OutboundQueueProvider> outboundQueueHandlerRegistration) {
196         this.outboundQueueHandlerRegistration = outboundQueueHandlerRegistration;
197     }
198
199     private void unregisterOutboundQueue() {
200         LOG.debug("Trying unregister outbound queue handler registration for node {}", nodeId);
201         if (outboundQueueHandlerRegistration != null) {
202             outboundQueueHandlerRegistration.close();
203             outboundQueueHandlerRegistration = null;
204         }
205     }
206
207     @Override
208     public synchronized void changeStateToHandshaking() {
209         connectionState = CONNECTION_STATE.HANDSHAKING;
210     }
211
212     @Override
213     public synchronized void changeStateToTimeouting() {
214         connectionState = CONNECTION_STATE.TIMEOUTING;
215     }
216
217     @Override
218     public synchronized void changeStateToWorking() {
219         connectionState = CONNECTION_STATE.WORKING;
220     }
221
222     @Override
223     public void setHandshakeContext(HandshakeContext handshakeContext) {
224         this.handshakeContext = handshakeContext;
225     }
226 }