Ditch use of SystemNotificationsListener
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / connection / listener / SystemNotificationsListenerImpl.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 package org.opendaylight.openflowplugin.impl.connection.listener;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.annotations.VisibleForTesting;
13 import java.net.InetSocketAddress;
14 import java.util.Date;
15 import java.util.Objects;
16 import java.util.concurrent.Executor;
17 import java.util.concurrent.Future;
18 import java.util.concurrent.TimeUnit;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.opendaylight.mdsal.binding.api.NotificationPublishService;
22 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter.SystemListener;
23 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
24 import org.opendaylight.openflowplugin.api.openflow.device.Xid;
25 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil;
26 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.node.ssl.connection.error.service.rev190723.SslErrorBuilder;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.node.ssl.connection.error.service.rev190723.SslErrorType;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.node.ssl.connection.error.service.rev190723.ssl.error.SwitchCertificateBuilder;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoInputBuilder;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoOutput;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.DisconnectEvent;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SslConnectionError;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SwitchIdleEvent;
36 import org.opendaylight.yangtools.yang.common.RpcError;
37 import org.opendaylight.yangtools.yang.common.RpcResult;
38 import org.opendaylight.yangtools.yang.common.Uint16;
39 import org.opendaylight.yangtools.yang.common.Uint32;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 public class SystemNotificationsListenerImpl implements SystemListener {
44     private static final Logger LOG = LoggerFactory.getLogger(SystemNotificationsListenerImpl.class);
45     private static final Logger OF_EVENT_LOG = LoggerFactory.getLogger("OfEventLog");
46     private static final Xid ECHO_XID = new Xid(Uint32.ZERO);
47
48     private final ConnectionContext connectionContext;
49     @VisibleForTesting
50     static final long MAX_ECHO_REPLY_TIMEOUT = 2000;
51     private final long echoReplyTimeout;
52     private final Executor executor;
53     private final NotificationPublishService notificationPublishService;
54
55     public SystemNotificationsListenerImpl(@NonNull final ConnectionContext connectionContext,
56             final long echoReplyTimeout, final @NonNull Executor executor,
57             @NonNull final NotificationPublishService notificationPublishService) {
58         this.connectionContext = requireNonNull(connectionContext);
59         this.echoReplyTimeout = echoReplyTimeout;
60         this.executor = requireNonNull(executor);
61         this.notificationPublishService = requireNonNull(notificationPublishService);
62     }
63
64     @Override
65     public void onSslConnectionError(final SslConnectionError sslConnectionError) {
66         final var switchCert = sslConnectionError.getSwitchCertificate();
67         notificationPublishService.offerNotification(new SslErrorBuilder()
68             .setType(SslErrorType.SslConFailed)
69             .setCode(Uint16.valueOf(SslErrorType.SslConFailed.getIntValue()))
70             .setNodeIpAddress(remoteAddress())
71             .setData(sslConnectionError.getInfo())
72             .setSwitchCertificate(switchCert == null ? null : new SwitchCertificateBuilder(switchCert).build())
73             .build());
74     }
75
76     @Override
77     public void onSwitchIdle(final SwitchIdleEvent switchIdle) {
78         executor.execute(this::executeOnSwitchIdleEvent);
79     }
80
81     @Override
82     public void onDisconnect(final DisconnectEvent notification) {
83         OF_EVENT_LOG.debug("Disconnect, Node: {}", connectionContext.getSafeNodeIdForLOG());
84         LOG.info("ConnectionEvent: Connection closed by device, Device:{}, NodeId:{}",
85                 connectionContext.getConnectionAdapter().getRemoteAddress(), connectionContext.getSafeNodeIdForLOG());
86         connectionContext.onConnectionClosed();
87     }
88
89     @SuppressWarnings("checkstyle:IllegalCatch")
90     private void executeOnSwitchIdleEvent() {
91         boolean shouldBeDisconnected = true;
92
93         final InetSocketAddress remoteAddress = connectionContext.getConnectionAdapter().getRemoteAddress();
94
95         if (ConnectionContext.CONNECTION_STATE.WORKING.equals(connectionContext.getConnectionState())) {
96             FeaturesReply features = connectionContext.getFeatures();
97             LOG.debug("Switch Idle state occurred, node={}|auxId={}", remoteAddress, features.getAuxiliaryId());
98             OF_EVENT_LOG.debug("Switch idle state, Node: {}", features.getDatapathId());
99             connectionContext.changeStateToTimeouting();
100             EchoInputBuilder builder = new EchoInputBuilder();
101             builder.setVersion(features.getVersion());
102             builder.setXid(ECHO_XID.getValue());
103
104             Future<RpcResult<EchoOutput>> echoReplyFuture =
105                     connectionContext.getConnectionAdapter().echo(builder.build());
106
107             try {
108                 RpcResult<EchoOutput> echoReplyValue = echoReplyFuture.get(echoReplyTimeout, TimeUnit.MILLISECONDS);
109                 if (echoReplyValue.isSuccessful()
110                         && Objects.equals(echoReplyValue.getResult().getXid(), ECHO_XID.getValue())) {
111                     connectionContext.changeStateToWorking();
112                     shouldBeDisconnected = false;
113                 } else {
114                     logErrors(remoteAddress, echoReplyValue);
115                 }
116             } catch (Exception e) {
117                 if (LOG.isWarnEnabled()) {
118                     LOG.warn("Exception while  waiting for echoReply from [{}] in TIMEOUTING state: {}",
119                             remoteAddress, e.getMessage());
120                 }
121
122                 if (LOG.isTraceEnabled()) {
123                     LOG.trace("Exception while  waiting for echoReply from [{}] in TIMEOUTING state",
124                             remoteAddress, e);
125                 }
126
127             }
128         }
129         if (shouldBeDisconnected) {
130             if (LOG.isInfoEnabled()) {
131                 LOG.info("ConnectionEvent:Closing connection as device is idle. Echo sent at {}. Device:{}, NodeId:{}",
132                         new Date(System.currentTimeMillis() - echoReplyTimeout),
133                         remoteAddress, connectionContext.getSafeNodeIdForLOG());
134             }
135
136             connectionContext.closeConnection(true);
137         }
138     }
139
140     private static void logErrors(final InetSocketAddress remoteAddress, final RpcResult<EchoOutput> echoReplyValue) {
141         for (RpcError replyError : echoReplyValue.getErrors()) {
142             Throwable cause = replyError.getCause();
143             if (LOG.isWarnEnabled()) {
144                 LOG.warn("Received EchoReply from [{}] in TIMEOUTING state, Error:{}",
145                         remoteAddress, cause.getMessage());
146             }
147
148             if (LOG.isTraceEnabled()) {
149                 LOG.trace("Received EchoReply from [{}] in TIMEOUTING state", remoteAddress, cause);
150             }
151         }
152     }
153
154     private @Nullable IpAddress remoteAddress() {
155         final var connectionAdapter = connectionContext.getConnectionAdapter();
156         if (connectionAdapter != null) {
157             final var remoteAddress = connectionAdapter.getRemoteAddress();
158             if (remoteAddress != null) {
159                 final var inetAddress = remoteAddress.getAddress();
160                 if (inetAddress != null) {
161                     return IetfInetUtil.ipAddressFor(inetAddress.getHostAddress());
162                 }
163             }
164         }
165         return null;
166     }
167 }