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