Merge "Device Info API"
[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.DeviceInfo;
27 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceDisconnectedHandler;
28 import org.opendaylight.openflowplugin.impl.statistics.ofpspecific.SessionStatistics;
29 import org.opendaylight.openflowplugin.impl.util.DeviceStateUtil;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IetfInetUtil;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
36 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 /**
41  *
42  */
43 public class ConnectionContextImpl implements ConnectionContext {
44
45     private final ConnectionAdapter connectionAdapter;
46     private volatile CONNECTION_STATE connectionState;
47     private FeaturesReply featuresReply;
48     private NodeId nodeId;
49     private DeviceDisconnectedHandler deviceDisconnectedHandler;
50     private static final Logger LOG = LoggerFactory.getLogger(ConnectionContextImpl.class);
51     private OutboundQueueProvider outboundQueueProvider;
52     private OutboundQueueHandlerRegistration<OutboundQueueProvider> outboundQueueHandlerRegistration;
53     private HandshakeContext handshakeContext;
54
55     /**
56      * @param connectionAdapter
57      */
58     public ConnectionContextImpl(final ConnectionAdapter connectionAdapter) {
59         this.connectionAdapter = connectionAdapter;
60     }
61
62     @Override
63     public ConnectionAdapter getConnectionAdapter() {
64         return connectionAdapter;
65     }
66
67     @Override
68     public OutboundQueue getOutboundQueueProvider() {
69         return this.outboundQueueProvider;
70     }
71
72     @Override
73     public void setOutboundQueueProvider(final OutboundQueueProvider outboundQueueProvider) {
74         this.outboundQueueProvider = outboundQueueProvider;
75     }
76
77     @Override
78     public CONNECTION_STATE getConnectionState() {
79         return connectionState;
80     }
81
82     @Override
83     public NodeId getNodeId() {
84         return nodeId;
85     }
86
87     @Override
88     public void setNodeId(final NodeId nodeId) {
89         this.nodeId = nodeId;
90     }
91
92     @Override
93     public FeaturesReply getFeatures() {
94         return featuresReply;
95     }
96
97     @Override
98     public void setDeviceDisconnectedHandler(final DeviceDisconnectedHandler deviceDisconnectedHandler) {
99         this.deviceDisconnectedHandler = deviceDisconnectedHandler;
100     }
101
102     @Override
103     public void setFeatures(final FeaturesReply featuresReply) {
104         this.featuresReply = featuresReply;
105     }
106
107     @Override
108     public void closeConnection(final boolean propagate) {
109         if (null == nodeId){
110             SessionStatistics.countEvent(connectionAdapter.getRemoteAddress().toString(), SessionStatistics.ConnectionStatus.CONNECTION_DISCONNECTED_BY_OFP);
111         } else {
112             SessionStatistics.countEvent(nodeId.toString(), SessionStatistics.ConnectionStatus.CONNECTION_DISCONNECTED_BY_OFP);
113         }
114         final BigInteger datapathId = featuresReply != null ? featuresReply.getDatapathId() : BigInteger.ZERO;
115         LOG.debug("Actively closing connection: {}, datapathId:{}.",
116                 connectionAdapter.getRemoteAddress(), datapathId);
117         connectionState = ConnectionContext.CONNECTION_STATE.RIP;
118
119         Future<Void> future = Executors.newSingleThreadExecutor().submit(new Callable<Void>() {
120             @Override
121             public Void call() throws Exception {
122                 unregisterOutboundQueue();
123                 return null;
124             }
125         });
126         try {
127             LOG.debug("Waiting 1s for unregistering outbound queue.");
128             future.get(1, TimeUnit.SECONDS);
129             LOG.info("Unregistering outbound queue successful.");
130         } catch (InterruptedException e) {
131             LOG.warn("Unregistering outbound queue was interrupted for node {}", nodeId);
132         } catch (ExecutionException e) {
133             LOG.warn("Unregistering outbound queue throws exception for node {}", nodeId, e);
134         } catch (TimeoutException e) {
135             LOG.warn("Unregistering outbound queue took longer than 1 seconds for node {}", nodeId);
136         }
137
138         closeHandshakeContext();
139
140         if (getConnectionAdapter().isAlive()) {
141             getConnectionAdapter().disconnect();
142         }
143
144         if (propagate) {
145             LOG.debug("Propagating device disconnect for node {}", nodeId);
146             propagateDeviceDisconnectedEvent();
147         } else {
148             LOG.debug("Close connection without propagating for node {}", nodeId);
149         }
150     }
151
152     private void closeHandshakeContext() {
153         LOG.debug("Trying closing handshake context for node {}", nodeId);
154         if (handshakeContext != null) {
155             try {
156                 handshakeContext.close();
157             } catch (Exception e) {
158                 LOG.error("handshake context closing failed:{} ", e);
159             } finally {
160                 handshakeContext = null;
161             }
162         }
163     }
164
165     @Override
166     public void onConnectionClosed() {
167         if (null == nodeId){
168             SessionStatistics.countEvent(connectionAdapter.getRemoteAddress().toString(), SessionStatistics.ConnectionStatus.CONNECTION_DISCONNECTED_BY_DEVICE);
169         } else {
170             SessionStatistics.countEvent(nodeId.toString(), SessionStatistics.ConnectionStatus.CONNECTION_DISCONNECTED_BY_DEVICE);
171         }
172         connectionState = ConnectionContext.CONNECTION_STATE.RIP;
173
174         final InetSocketAddress remoteAddress = connectionAdapter.getRemoteAddress();
175         final Short auxiliaryId;
176         if (null != getFeatures() && null != getFeatures().getAuxiliaryId()) {
177             auxiliaryId = getFeatures().getAuxiliaryId();
178         } else {
179             auxiliaryId = 0;
180         }
181
182         LOG.debug("disconnecting: node={}|auxId={}|connection state = {}",
183                 remoteAddress,
184                 auxiliaryId,
185                 getConnectionState());
186
187         unregisterOutboundQueue();
188         closeHandshakeContext();
189         propagateDeviceDisconnectedEvent();
190     }
191
192     private void propagateDeviceDisconnectedEvent() {
193         if (null != deviceDisconnectedHandler) {
194             final BigInteger datapathId = featuresReply != null ? featuresReply.getDatapathId() : BigInteger.ZERO;
195             LOG.debug("Propagating connection closed event: {}, datapathId:{}.",
196                     connectionAdapter.getRemoteAddress(), datapathId);
197             deviceDisconnectedHandler.onDeviceDisconnected(this);
198         }
199     }
200
201     @Override
202     public void setOutboundQueueHandleRegistration(OutboundQueueHandlerRegistration<OutboundQueueProvider> outboundQueueHandlerRegistration) {
203         this.outboundQueueHandlerRegistration = outboundQueueHandlerRegistration;
204     }
205
206     private void unregisterOutboundQueue() {
207         LOG.debug("Trying unregister outbound queue handler registration for node {}", nodeId);
208         if (outboundQueueHandlerRegistration != null) {
209             outboundQueueHandlerRegistration.close();
210             outboundQueueHandlerRegistration = null;
211         }
212     }
213
214     @Override
215     public synchronized void changeStateToHandshaking() {
216         connectionState = CONNECTION_STATE.HANDSHAKING;
217     }
218
219     @Override
220     public synchronized void changeStateToTimeouting() {
221         connectionState = CONNECTION_STATE.TIMEOUTING;
222     }
223
224     @Override
225     public synchronized void changeStateToWorking() {
226         connectionState = CONNECTION_STATE.WORKING;
227     }
228
229     @Override
230     public DeviceInfo gainDeviceInfo() {
231         return new DeviceInfoImpl(
232                 nodeId,
233                 DeviceStateUtil.createNodeInstanceIdentifier(nodeId),
234                 featuresReply.getVersion(),
235                 featuresReply.getDatapathId(),
236                 IetfInetUtil.INSTANCE.ipAddressFor(connectionAdapter.getRemoteAddress().getAddress()));
237     }
238
239     @Override
240     public void setHandshakeContext(HandshakeContext handshakeContext) {
241         this.handshakeContext = handshakeContext;
242     }
243
244
245     private class DeviceInfoImpl implements DeviceInfo {
246
247         final private NodeId nodeId;
248         final private KeyedInstanceIdentifier<Node, NodeKey> nodeII;
249         final private Short version;
250         final private BigInteger datapathId;
251         final private IpAddress ipAddress;
252         private boolean valid;
253         private boolean sync;
254
255         DeviceInfoImpl(
256                 final NodeId nodeId,
257                 final KeyedInstanceIdentifier<Node, NodeKey> nodeII,
258                 final Short version,
259                 final BigInteger datapathId,
260                 final IpAddress ipAddress) {
261             this.nodeId = nodeId;
262             this.nodeII = nodeII;
263             this.version = version;
264             this.datapathId = datapathId;
265             this.ipAddress = ipAddress;
266             this.valid = false;
267             this.sync = false;
268         }
269
270         @Override
271         public NodeId getNodeId() {
272             return nodeId;
273         }
274
275         @Override
276         public KeyedInstanceIdentifier<Node, NodeKey> getNodeInstanceIdentifier() {
277             return nodeII;
278         }
279
280         @Override
281         public Short getVersion() {
282             return version;
283         }
284
285         @Override
286         public BigInteger getDatapathId() {
287             return datapathId;
288         }
289
290         @Override
291         public IpAddress getIpAddress() {
292             return null;
293         }
294
295         @Override
296         public boolean equals(Object o) {
297             if (this == o) return true;
298             if (o == null || getClass() != o.getClass()) return false;
299
300             DeviceInfoImpl that = (DeviceInfoImpl) o;
301
302             if (!nodeId.equals(that.nodeId)) return false;
303             if (!nodeII.equals(that.nodeII)) return false;
304             if (!version.equals(that.version)) return false;
305             if (!datapathId.equals(that.datapathId)) return false;
306             return ipAddress.equals(that.ipAddress);
307
308         }
309
310         @Override
311         public int hashCode() {
312             int result = nodeId.hashCode();
313             result = 31 * result + nodeII.hashCode();
314             result = 31 * result + version.hashCode();
315             result = 31 * result + datapathId.hashCode();
316             result = 31 * result + ipAddress.hashCode();
317             return result;
318         }
319     }
320 }