Merge "Bug 8153: Enforce check-style rules for netconf - netconf-notification-impl"
[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.channel.ChannelFutureListener;
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.Matcher;
25 import java.util.regex.Pattern;
26 import org.opendaylight.netconf.api.NetconfMessage;
27 import org.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader;
28 import org.opendaylight.netconf.api.monitoring.NetconfManagementSession;
29 import org.opendaylight.netconf.nettyutil.AbstractNetconfSession;
30 import org.opendaylight.netconf.nettyutil.handler.NetconfMessageToXMLEncoder;
31 import org.opendaylight.netconf.nettyutil.handler.NetconfXMLToMessageDecoder;
32 import org.opendaylight.netconf.notifications.NetconfNotification;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6Address;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.extension.rev131210.NetconfTcp;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.extension.rev131210.Session1;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.extension.rev131210.Session1Builder;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfSsh;
41 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.Transport;
42 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.sessions.Session;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.sessions.SessionBuilder;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.sessions.SessionKey;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.ZeroBasedCounter32;
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(new ChannelFutureListener() {
101                 @Override
102                 public void operationComplete(final ChannelFuture future) throws Exception {
103                     close();
104                 }
105             });
106         }
107         return channelFuture;
108     }
109
110     public void onIncommingRpcSuccess() {
111         inRpcSuccess++;
112     }
113
114     public void onIncommingRpcFail() {
115         inRpcFail++;
116     }
117
118     public void onOutgoingRpcError() {
119         outRpcError++;
120     }
121
122     @Override
123     public Session toManagementSession() {
124         SessionBuilder builder = new SessionBuilder();
125
126         builder.setSessionId(getSessionId());
127         IpAddress address;
128         InetAddress address1 = InetAddresses.forString(header.getAddress());
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         Preconditions.checkState(DateAndTime.PATTERN_CONSTANTS.size() == 1);
137         String formattedDateTime = DATE_FORMATTER.format(loginTime);
138
139         Matcher matcher = DATE_TIME_PATTERN.matcher(formattedDateTime);
140         Preconditions.checkState(matcher.matches(), "Formatted datetime %s does not match pattern %s",
141                 formattedDateTime, DATE_TIME_PATTERN);
142         builder.setLoginTime(new DateAndTime(formattedDateTime));
143
144         builder.setInBadRpcs(new ZeroBasedCounter32(inRpcFail));
145         builder.setInRpcs(new ZeroBasedCounter32(inRpcSuccess));
146         builder.setOutRpcErrors(new ZeroBasedCounter32(outRpcError));
147
148         builder.setUsername(header.getUserName());
149         builder.setTransport(getTransportForString(header.getTransport()));
150
151         builder.setOutNotifications(new ZeroBasedCounter32(outNotification));
152
153         builder.setKey(new SessionKey(getSessionId()));
154
155         Session1Builder builder1 = new Session1Builder();
156         builder1.setSessionIdentifier(header.getSessionIdentifier());
157         builder.addAugmentation(Session1.class, builder1.build());
158
159         return builder.build();
160     }
161
162     private static Class<? extends Transport> getTransportForString(final String transport) {
163         switch (transport) {
164             case "ssh":
165                 return NetconfSsh.class;
166             case "tcp":
167                 return NetconfTcp.class;
168             default:
169                 throw new IllegalArgumentException("Unknown transport type " + transport);
170         }
171     }
172
173     @Override
174     protected NetconfServerSession thisInstance() {
175         return this;
176     }
177
178     @Override
179     protected void addExiHandlers(final ByteToMessageDecoder decoder,
180                                   final MessageToByteEncoder<NetconfMessage> encoder) {
181         replaceMessageDecoder(decoder);
182         replaceMessageEncoderAfterNextMessage(encoder);
183     }
184
185     @Override
186     public void stopExiCommunication() {
187         replaceMessageDecoder(new NetconfXMLToMessageDecoder());
188         replaceMessageEncoderAfterNextMessage(new NetconfMessageToXMLEncoder());
189     }
190 }