Bug 5596 Created lifecycle service
[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 com.google.common.base.Preconditions;
12 import java.math.BigInteger;
13 import java.net.InetSocketAddress;
14 import java.util.concurrent.Callable;
15 import java.util.concurrent.ExecutionException;
16 import java.util.concurrent.Executors;
17 import java.util.concurrent.Future;
18 import java.util.concurrent.TimeUnit;
19 import java.util.concurrent.TimeoutException;
20 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
21 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
22 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
23 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandlerRegistration;
24 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
25 import org.opendaylight.openflowplugin.api.openflow.connection.HandshakeContext;
26 import org.opendaylight.openflowplugin.api.openflow.connection.OutboundQueueProvider;
27 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
28 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceDisconnectedHandler;
29 import org.opendaylight.openflowplugin.impl.statistics.ofpspecific.SessionStatistics;
30 import org.opendaylight.openflowplugin.impl.util.DeviceStateUtil;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
35 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 /**
40  *
41  */
42 public class ConnectionContextImpl implements ConnectionContext {
43
44     private final ConnectionAdapter connectionAdapter;
45     private volatile CONNECTION_STATE connectionState;
46     private FeaturesReply featuresReply;
47     private NodeId nodeId;
48     private DeviceDisconnectedHandler deviceDisconnectedHandler;
49     private static final Logger LOG = LoggerFactory.getLogger(ConnectionContextImpl.class);
50     private OutboundQueueProvider outboundQueueProvider;
51     private OutboundQueueHandlerRegistration<OutboundQueueProvider> outboundQueueHandlerRegistration;
52     private HandshakeContext handshakeContext;
53     private DeviceInfo deviceInfo;
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             future.get(1, TimeUnit.SECONDS);
128             LOG.info("Unregister outbound queue successful.");
129         } catch (InterruptedException | TimeoutException | ExecutionException e) {
130             LOG.warn("Unregister outbound queue throws exception for node {} ", nodeId);
131             LOG.trace("Unregister outbound queue throws exception for node {} ", nodeId, e);
132         }
133
134         closeHandshakeContext();
135
136         if (getConnectionAdapter().isAlive()) {
137             getConnectionAdapter().disconnect();
138         }
139
140         if (propagate) {
141             LOG.debug("Propagating device disconnect for node {}", nodeId);
142             propagateDeviceDisconnectedEvent();
143         } else {
144             LOG.debug("Close connection without propagating for node {}", nodeId);
145         }
146     }
147
148     private void closeHandshakeContext() {
149         LOG.debug("Trying closing handshake context for node {}", nodeId);
150         if (handshakeContext != null) {
151             try {
152                 handshakeContext.close();
153             } catch (Exception e) {
154                 LOG.error("handshake context closing failed:{} ", e);
155             } finally {
156                 handshakeContext = null;
157             }
158         }
159     }
160
161     @Override
162     public void onConnectionClosed() {
163         if (null == nodeId){
164             SessionStatistics.countEvent(connectionAdapter.getRemoteAddress().toString(), SessionStatistics.ConnectionStatus.CONNECTION_DISCONNECTED_BY_DEVICE);
165         } else {
166             SessionStatistics.countEvent(nodeId.toString(), SessionStatistics.ConnectionStatus.CONNECTION_DISCONNECTED_BY_DEVICE);
167         }
168         connectionState = ConnectionContext.CONNECTION_STATE.RIP;
169
170         final InetSocketAddress remoteAddress = connectionAdapter.getRemoteAddress();
171         final Short auxiliaryId;
172         if (null != getFeatures() && null != getFeatures().getAuxiliaryId()) {
173             auxiliaryId = getFeatures().getAuxiliaryId();
174         } else {
175             auxiliaryId = 0;
176         }
177
178         LOG.debug("disconnecting: node={}|auxId={}|connection state = {}",
179                 remoteAddress,
180                 auxiliaryId,
181                 getConnectionState());
182
183         unregisterOutboundQueue();
184         closeHandshakeContext();
185         propagateDeviceDisconnectedEvent();
186     }
187
188     private void propagateDeviceDisconnectedEvent() {
189         if (null != deviceDisconnectedHandler) {
190             final BigInteger datapathId = featuresReply != null ? featuresReply.getDatapathId() : BigInteger.ZERO;
191             LOG.debug("Propagating connection closed event: {}, datapathId:{}.",
192                     connectionAdapter.getRemoteAddress(), datapathId);
193             deviceDisconnectedHandler.onDeviceDisconnected(this);
194         }
195     }
196
197     @Override
198     public void setOutboundQueueHandleRegistration(OutboundQueueHandlerRegistration<OutboundQueueProvider> outboundQueueHandlerRegistration) {
199         this.outboundQueueHandlerRegistration = outboundQueueHandlerRegistration;
200     }
201
202     private void unregisterOutboundQueue() {
203         LOG.debug("Trying unregister outbound queue handler registration for node {}", nodeId);
204         if (outboundQueueHandlerRegistration != null) {
205             outboundQueueHandlerRegistration.close();
206             outboundQueueHandlerRegistration = null;
207         }
208     }
209
210     @Override
211     public synchronized void changeStateToHandshaking() {
212         connectionState = CONNECTION_STATE.HANDSHAKING;
213     }
214
215     @Override
216     public synchronized void changeStateToTimeouting() {
217         connectionState = CONNECTION_STATE.TIMEOUTING;
218     }
219
220     @Override
221     public synchronized void changeStateToWorking() {
222         connectionState = CONNECTION_STATE.WORKING;
223     }
224
225     @Override
226     public DeviceInfo getDeviceInfo() {
227         return this.deviceInfo;
228     }
229
230     @Override
231     public void handshakeSuccessful() {
232         Preconditions.checkNotNull(nodeId, "Cannot create DeviceInfo if 'NodeId' is not set!");
233         Preconditions.checkNotNull(featuresReply, "Cannot create DeviceInfo if 'features' is not set!");
234         this.deviceInfo = new DeviceInfoImpl(
235                 nodeId,
236                 DeviceStateUtil.createNodeInstanceIdentifier(nodeId),
237                 featuresReply.getVersion(),
238                 featuresReply.getDatapathId());
239     }
240
241     @Override
242     public void setHandshakeContext(HandshakeContext handshakeContext) {
243         this.handshakeContext = handshakeContext;
244     }
245
246
247     private class DeviceInfoImpl implements DeviceInfo {
248
249         final private NodeId nodeId;
250         final private KeyedInstanceIdentifier<Node, NodeKey> nodeII;
251         final private Short version;
252         final private BigInteger datapathId;
253         final private ServiceGroupIdentifier serviceGroupIdentifier;
254
255         DeviceInfoImpl(
256                 final NodeId nodeId,
257                 final KeyedInstanceIdentifier<Node, NodeKey> nodeII,
258                 final Short version,
259                 final BigInteger datapathId) {
260             this.nodeId = nodeId;
261             this.nodeII = nodeII;
262             this.version = version;
263             this.datapathId = datapathId;
264             this.serviceGroupIdentifier = ServiceGroupIdentifier.create(this.nodeId.getValue());
265         }
266
267         @Override
268         public NodeId getNodeId() {
269             return nodeId;
270         }
271
272         @Override
273         public KeyedInstanceIdentifier<Node, NodeKey> getNodeInstanceIdentifier() {
274             return nodeII;
275         }
276
277         @Override
278         public Short getVersion() {
279             return version;
280         }
281
282         @Override
283         public BigInteger getDatapathId() {
284             return datapathId;
285         }
286
287         @Override
288         public ServiceGroupIdentifier getServiceIdentifier() {
289             return this.serviceGroupIdentifier;
290         }
291
292         @Override
293         public boolean equals(Object o) {
294             if (this == o) {
295                 return true;
296             }
297
298             if (o == null || getClass() != o.getClass()) {
299                 return false;
300             }
301
302             DeviceInfoImpl that = (DeviceInfoImpl) o;
303
304             return  (nodeId.equals(that.nodeId) &&
305                     nodeII.equals(that.nodeII) &&
306                     version.equals(that.version) &&
307                     datapathId.equals(that.datapathId));
308
309         }
310
311         @Override
312         public int hashCode() {
313             int result = nodeId.hashCode();
314             result = 31 * result + nodeII.hashCode();
315             result = 31 * result + version.hashCode();
316             result = 31 * result + datapathId.hashCode();
317             return result;
318         }
319     }
320 }