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