2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.openflowplugin.impl.connection;
11 import com.google.common.base.MoreObjects;
12 import com.google.common.base.Preconditions;
13 import java.math.BigInteger;
14 import java.util.ArrayList;
15 import java.util.Collections;
16 import java.util.List;
17 import java.util.Objects;
18 import java.util.Optional;
19 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
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.opendaylight.inventory.rev130819.NodeId;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
35 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
42 public class ConnectionContextImpl implements ConnectionContext {
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 private List<PortStatusMessage> portStatusMessages = new ArrayList<>();
57 * @param connectionAdapter
59 public ConnectionContextImpl(final ConnectionAdapter connectionAdapter) {
60 this.connectionAdapter = connectionAdapter;
64 public ConnectionAdapter getConnectionAdapter() {
65 return connectionAdapter;
69 public OutboundQueue getOutboundQueueProvider() {
70 return this.outboundQueueProvider;
74 public void setOutboundQueueProvider(final OutboundQueueProvider outboundQueueProvider) {
75 this.outboundQueueProvider = outboundQueueProvider;
76 ((DeviceInfoImpl)this.deviceInfo).setOutboundQueueProvider(this.outboundQueueProvider);
80 public CONNECTION_STATE getConnectionState() {
81 return connectionState;
85 public NodeId getNodeId() {
90 public void setNodeId(final NodeId nodeId) {
95 public FeaturesReply getFeatures() {
100 public void setDeviceDisconnectedHandler(final DeviceDisconnectedHandler deviceDisconnectedHandler) {
101 this.deviceDisconnectedHandler = deviceDisconnectedHandler;
105 public void setFeatures(final FeaturesReply featuresReply) {
106 this.featuresReply = featuresReply;
110 public void closeConnection(final boolean propagate) {
111 disconnectDevice(propagate, true);
114 private void closeHandshakeContext() {
115 LOG.debug("Trying closing handshake context for node {}", getSafeNodeIdForLOG());
116 if (handshakeContext != null) {
118 handshakeContext.close();
119 } catch (Exception e) {
120 LOG.error("handshake context closing failed:{} ", e);
122 handshakeContext = null;
128 public void onConnectionClosed() {
129 disconnectDevice(true, false);
132 private void disconnectDevice(final boolean propagate,
133 final boolean forced) {
134 final String device = Objects.nonNull(nodeId) ? nodeId.getValue() : getConnectionAdapter().getRemoteAddress().toString();
135 final short auxiliaryId = Optional
136 .ofNullable(getFeatures())
137 .flatMap(features -> Optional
138 .ofNullable(features.getAuxiliaryId()))
141 if (connectionState == CONNECTION_STATE.RIP) {
142 LOG.debug("Connection for device {} with auxiliary ID {} is already {}, so skipping closing.",
143 device, auxiliaryId, getConnectionState());
147 SessionStatistics.countEvent(device, forced
148 ? SessionStatistics.ConnectionStatus.CONNECTION_DISCONNECTED_BY_OFP
149 : SessionStatistics.ConnectionStatus.CONNECTION_DISCONNECTED_BY_DEVICE);
151 connectionState = ConnectionContext.CONNECTION_STATE.RIP;
153 LOG.debug("{}: device={} | auxiliaryId={} | connectionState={}",
154 forced ? "Actively closing connection" : "Disconnecting",
157 getConnectionState());
159 portStatusMessages.clear();
160 unregisterOutboundQueue();
161 closeHandshakeContext();
163 if (forced && getConnectionAdapter().isAlive()) {
164 getConnectionAdapter().disconnect();
168 propagateDeviceDisconnectedEvent();
172 private void propagateDeviceDisconnectedEvent() {
173 if (Objects.nonNull(deviceDisconnectedHandler)) {
174 final BigInteger datapathId = featuresReply != null ? featuresReply.getDatapathId() : BigInteger.ZERO;
175 if (LOG.isDebugEnabled()) {
176 LOG.debug("Propagating connection closed event: {}, datapathId:{}.",
177 connectionAdapter.getRemoteAddress(), datapathId);
179 deviceDisconnectedHandler.onDeviceDisconnected(this);
184 * This method returns safe nodeId for logging
185 * @return string value od nodeId or string "null"
188 public String getSafeNodeIdForLOG() {
189 return Objects.nonNull(nodeId) ? nodeId.getValue() : "null";
193 public void setOutboundQueueHandleRegistration(OutboundQueueHandlerRegistration<OutboundQueueProvider> outboundQueueHandlerRegistration) {
194 this.outboundQueueHandlerRegistration = outboundQueueHandlerRegistration;
197 private void unregisterOutboundQueue() {
198 if (LOG.isDebugEnabled()) {
199 LOG.debug("Trying unregister outbound queue handler registration for node {}", nodeId);
201 if (outboundQueueHandlerRegistration != null) {
202 outboundQueueHandlerRegistration.close();
203 outboundQueueHandlerRegistration = null;
208 public synchronized void changeStateToHandshaking() {
209 connectionState = CONNECTION_STATE.HANDSHAKING;
213 public synchronized void changeStateToTimeouting() {
214 connectionState = CONNECTION_STATE.TIMEOUTING;
218 public synchronized void changeStateToWorking() {
219 connectionState = CONNECTION_STATE.WORKING;
223 public void handlePortStatusMessage(final PortStatusMessage portStatusMessage) {
224 LOG.info("Received early port status message for node {} with reason {} and state {}",
226 portStatusMessage.getReason(),
227 MoreObjects.firstNonNull(portStatusMessage.getState(), portStatusMessage.getStateV10()));
229 LOG.debug("Early port status message body is {}", portStatusMessage);
230 portStatusMessages.add(portStatusMessage);
234 public List<PortStatusMessage> retrieveAndClearPortStatusMessages() {
235 final List<PortStatusMessage> immutablePortStatusMessages = Collections.unmodifiableList(portStatusMessages);
236 portStatusMessages.clear();
237 return immutablePortStatusMessages;
241 public DeviceInfo getDeviceInfo() {
242 return this.deviceInfo;
246 public void handshakeSuccessful() {
247 Preconditions.checkNotNull(nodeId, "Cannot create DeviceInfo if 'NodeId' is not set!");
248 Preconditions.checkNotNull(featuresReply, "Cannot create DeviceInfo if 'features' is not set!");
249 this.deviceInfo = new DeviceInfoImpl(
251 DeviceStateUtil.createNodeInstanceIdentifier(nodeId),
252 featuresReply.getVersion(),
253 featuresReply.getDatapathId(),
254 outboundQueueProvider);
258 public void setHandshakeContext(HandshakeContext handshakeContext) {
259 this.handshakeContext = handshakeContext;
263 public boolean equals(Object o) {
268 if (o == null || getClass() != o.getClass()) {
272 ConnectionContextImpl that = (ConnectionContextImpl) o;
274 if (!connectionAdapter.equals(that.connectionAdapter)) {
278 if (featuresReply != null ? !featuresReply.equals(that.featuresReply) : that.featuresReply != null) {
282 return nodeId != null ? nodeId.equals(that.nodeId) : that.nodeId == null;
287 public int hashCode() {
288 int result = connectionAdapter.hashCode();
289 result = 31 * result + (featuresReply != null ? featuresReply.hashCode() : 0);
290 result = 31 * result + (nodeId != null ? nodeId.hashCode() : 0);
294 private class DeviceInfoImpl implements DeviceInfo {
296 private final NodeId nodeId;
297 private final KeyedInstanceIdentifier<Node, NodeKey> nodeII;
298 private final Short version;
299 private final BigInteger datapathId;
300 private final ServiceGroupIdentifier serviceGroupIdentifier;
301 private OutboundQueue outboundQueueProvider;
305 final KeyedInstanceIdentifier<Node, NodeKey> nodeII,
307 final BigInteger datapathId,
308 final OutboundQueue outboundQueueProvider) {
309 this.nodeId = nodeId;
310 this.nodeII = nodeII;
311 this.version = version;
312 this.datapathId = datapathId;
313 this.outboundQueueProvider = outboundQueueProvider;
314 this.serviceGroupIdentifier = ServiceGroupIdentifier.create(this.nodeId.getValue());
318 public NodeId getNodeId() {
323 public KeyedInstanceIdentifier<Node, NodeKey> getNodeInstanceIdentifier() {
328 public short getVersion() {
333 public BigInteger getDatapathId() {
338 public ServiceGroupIdentifier getServiceIdentifier() {
339 return this.serviceGroupIdentifier;
343 public boolean equals(Object o) {
348 if (o == null || getClass() != o.getClass()) {
352 DeviceInfoImpl that = (DeviceInfoImpl) o;
354 return (nodeId.equals(that.nodeId) &&
355 nodeII.equals(that.nodeII) &&
356 version.equals(that.version) &&
357 datapathId.equals(that.datapathId));
362 public int hashCode() {
363 int result = nodeId.hashCode();
364 result = 31 * result + nodeII.hashCode();
365 result = 31 * result + version.hashCode();
366 result = 31 * result + datapathId.hashCode();
371 public String toString() {
372 return getLOGValue();
375 public void setOutboundQueueProvider(final OutboundQueue outboundQueueProvider) {
376 this.outboundQueueProvider = outboundQueueProvider;
380 public Long reserveXidForDeviceMessage() {
381 return outboundQueueProvider.reserveEntry();