19601fcdca2be75f467c55c2039b8328bd4bb87f
[netconf.git] / netconf / netconf-impl / src / main / java / org / opendaylight / netconf / impl / NetconfServerSession.java
1 /*
2  * Copyright (c) 2013 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.netconf.impl;
9
10 import static com.google.common.base.Preconditions.checkState;
11 import static com.google.common.base.Verify.verify;
12
13 import com.google.common.net.InetAddresses;
14 import io.netty.channel.Channel;
15 import io.netty.channel.ChannelFuture;
16 import io.netty.handler.codec.ByteToMessageDecoder;
17 import io.netty.handler.codec.MessageToByteEncoder;
18 import java.net.Inet4Address;
19 import java.net.InetAddress;
20 import java.time.Instant;
21 import java.time.ZoneId;
22 import java.time.ZonedDateTime;
23 import java.time.format.DateTimeFormatter;
24 import java.util.regex.Pattern;
25 import org.opendaylight.netconf.api.NetconfMessage;
26 import org.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader;
27 import org.opendaylight.netconf.api.monitoring.NetconfManagementSession;
28 import org.opendaylight.netconf.nettyutil.AbstractNetconfSession;
29 import org.opendaylight.netconf.nettyutil.handler.NetconfMessageToXMLEncoder;
30 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToMessageDecoder;
31 import org.opendaylight.netconf.notifications.NetconfNotification;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6Address;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.extension.rev131210.NetconfTcp;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.extension.rev131210.Session1Builder;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfSsh;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.Transport;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.sessions.Session;
41 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.sessions.SessionBuilder;
42 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.sessions.SessionKey;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.ZeroBasedCounter32;
45 import org.opendaylight.yangtools.yang.common.Uint32;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 public final class NetconfServerSession extends AbstractNetconfSession<NetconfServerSession,
50         NetconfServerSessionListener> implements NetconfManagementSession {
51
52     private static final Logger LOG = LoggerFactory.getLogger(NetconfServerSession.class);
53     private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
54
55     private static final String DATE_TIME_PATTERN_STRING;
56
57     static {
58         verify(DateAndTime.PATTERN_CONSTANTS.size() == 1);
59         DATE_TIME_PATTERN_STRING = DateAndTime.PATTERN_CONSTANTS.get(0);
60     }
61
62     private static final Pattern DATE_TIME_PATTERN = Pattern.compile(DATE_TIME_PATTERN_STRING);
63
64     private final NetconfHelloMessageAdditionalHeader header;
65     private final NetconfServerSessionListener sessionListener;
66
67     private ZonedDateTime loginTime;
68     private long inRpcSuccess;
69     private long inRpcFail;
70     private long outRpcError;
71     private long outNotification;
72     private volatile boolean delayedClose;
73
74     public NetconfServerSession(final NetconfServerSessionListener sessionListener, final Channel channel,
75                                 final long sessionId, final NetconfHelloMessageAdditionalHeader header) {
76         super(sessionListener, channel, sessionId);
77         this.header = header;
78         this.sessionListener = sessionListener;
79         LOG.debug("Session {} created", this);
80     }
81
82     @Override
83     protected void sessionUp() {
84         checkState(loginTime == null, "Session is already up");
85         loginTime = Instant.now().atZone(ZoneId.systemDefault());
86         super.sessionUp();
87     }
88
89     /**
90      * Close this session after next message is sent.
91      * Suitable for close rpc that needs to send ok response before the session is closed.
92      */
93     public void delayedClose() {
94         delayedClose = true;
95     }
96
97     @Override
98     public ChannelFuture sendMessage(final NetconfMessage netconfMessage) {
99         final ChannelFuture channelFuture = super.sendMessage(netconfMessage);
100         if (netconfMessage instanceof NetconfNotification) {
101             outNotification++;
102             sessionListener.onNotification(this, (NetconfNotification) netconfMessage);
103         }
104         // delayed close was set, close after the message was sent
105         if (delayedClose) {
106             channelFuture.addListener(future -> close());
107         }
108         return channelFuture;
109     }
110
111     public void onIncommingRpcSuccess() {
112         inRpcSuccess++;
113     }
114
115     public void onIncommingRpcFail() {
116         inRpcFail++;
117     }
118
119     public void onOutgoingRpcError() {
120         outRpcError++;
121     }
122
123     @Override
124     public Session toManagementSession() {
125         final SessionBuilder builder = new SessionBuilder()
126                 .withKey(new SessionKey(Uint32.valueOf(getSessionId())));
127         final InetAddress address1 = InetAddresses.forString(header.getAddress());
128         final IpAddress address;
129         if (address1 instanceof Inet4Address) {
130             address = new IpAddress(new Ipv4Address(header.getAddress()));
131         } else {
132             address = new IpAddress(new Ipv6Address(header.getAddress()));
133         }
134         builder.setSourceHost(new Host(address));
135
136         final String formattedDateTime = DATE_FORMATTER.format(loginTime);
137         checkState(DATE_TIME_PATTERN.matcher(formattedDateTime).matches(),
138             "Formatted datetime %s does not match pattern %s", formattedDateTime, DATE_TIME_PATTERN);
139
140         return builder
141                 .setLoginTime(new DateAndTime(formattedDateTime))
142                 .setInBadRpcs(new ZeroBasedCounter32(Uint32.valueOf(inRpcFail)))
143                 .setInRpcs(new ZeroBasedCounter32(Uint32.valueOf(inRpcSuccess)))
144                 .setOutRpcErrors(new ZeroBasedCounter32(Uint32.valueOf(outRpcError)))
145                 .setUsername(header.getUserName())
146                 .setTransport(getTransportForString(header.getTransport()))
147                 .setOutNotifications(new ZeroBasedCounter32(Uint32.valueOf(outNotification)))
148                 .addAugmentation(new Session1Builder().setSessionIdentifier(header.getSessionIdentifier()).build())
149                 .build();
150     }
151
152     private static Transport getTransportForString(final String transport) {
153         return switch (transport) {
154             case "ssh" -> NetconfSsh.VALUE;
155             case "tcp" -> NetconfTcp.VALUE;
156             default -> throw new IllegalArgumentException("Unknown transport type " + transport);
157         };
158     }
159
160     @Override
161     protected NetconfServerSession thisInstance() {
162         return this;
163     }
164
165     @Override
166     protected void addExiHandlers(final ByteToMessageDecoder decoder,
167                                   final MessageToByteEncoder<NetconfMessage> encoder) {
168         replaceMessageDecoder(decoder);
169         replaceMessageEncoderAfterNextMessage(encoder);
170     }
171
172     @Override
173     public void stopExiCommunication() {
174         replaceMessageDecoder(new NetconfXMLToMessageDecoder());
175         replaceMessageEncoderAfterNextMessage(new NetconfMessageToXMLEncoder());
176     }
177 }