BUG-2459: reuse EXI Reader
[controller.git] / opendaylight / netconf / netconf-netty-util / src / main / java / org / opendaylight / controller / netconf / nettyutil / AbstractNetconfSession.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.controller.netconf.nettyutil;
9
10 import io.netty.channel.Channel;
11 import io.netty.channel.ChannelFuture;
12 import io.netty.channel.ChannelHandler;
13 import io.netty.handler.codec.ByteToMessageDecoder;
14 import io.netty.handler.codec.MessageToByteEncoder;
15 import java.io.IOException;
16 import org.opendaylight.controller.netconf.api.NetconfExiSession;
17 import org.opendaylight.controller.netconf.api.NetconfMessage;
18 import org.opendaylight.controller.netconf.api.NetconfSession;
19 import org.opendaylight.controller.netconf.api.NetconfSessionListener;
20 import org.opendaylight.controller.netconf.api.NetconfTerminationReason;
21 import org.opendaylight.controller.netconf.nettyutil.handler.NetconfEXICodec;
22 import org.opendaylight.controller.netconf.nettyutil.handler.NetconfEXIToMessageDecoder;
23 import org.opendaylight.controller.netconf.nettyutil.handler.NetconfMessageToEXIEncoder;
24 import org.opendaylight.controller.netconf.nettyutil.handler.exi.EXIParameters;
25 import org.opendaylight.controller.netconf.util.xml.XmlElement;
26 import org.opendaylight.protocol.framework.AbstractProtocolSession;
27 import org.openexi.proc.common.EXIOptionsException;
28 import org.openexi.sax.TransmogrifierException;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 public abstract class AbstractNetconfSession<S extends NetconfSession, L extends NetconfSessionListener<S>> extends AbstractProtocolSession<NetconfMessage> implements NetconfSession, NetconfExiSession {
33     private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfSession.class);
34     private final L sessionListener;
35     private final long sessionId;
36     private boolean up = false;
37
38     private ChannelHandler delayedEncoder;
39
40     private final Channel channel;
41
42     protected AbstractNetconfSession(final L sessionListener, final Channel channel, final long sessionId) {
43         this.sessionListener = sessionListener;
44         this.channel = channel;
45         this.sessionId = sessionId;
46         LOG.debug("Session {} created", sessionId);
47     }
48
49     protected abstract S thisInstance();
50
51     @Override
52     public void close() {
53         channel.close();
54         up = false;
55         sessionListener.onSessionTerminated(thisInstance(), new NetconfTerminationReason("Session closed"));
56     }
57
58     @Override
59     protected void handleMessage(final NetconfMessage netconfMessage) {
60         LOG.debug("handling incoming message");
61         sessionListener.onMessage(thisInstance(), netconfMessage);
62     }
63
64     @Override
65     public ChannelFuture sendMessage(final NetconfMessage netconfMessage) {
66         final ChannelFuture future = channel.writeAndFlush(netconfMessage);
67         if (delayedEncoder != null) {
68             replaceMessageEncoder(delayedEncoder);
69             delayedEncoder = null;
70         }
71
72         return future;
73     }
74
75     @Override
76     protected void endOfInput() {
77         LOG.debug("Session {} end of input detected while session was in state {}", toString(), isUp() ? "up"
78                 : "initialized");
79         if (isUp()) {
80             this.sessionListener.onSessionDown(thisInstance(), new IOException("End of input detected. Close the session."));
81         }
82     }
83
84     @Override
85     protected void sessionUp() {
86         LOG.debug("Session {} up", toString());
87         sessionListener.onSessionUp(thisInstance());
88         this.up = true;
89     }
90
91     @Override
92     public String toString() {
93         final StringBuffer sb = new StringBuffer(getClass().getSimpleName() + "{");
94         sb.append("sessionId=").append(sessionId);
95         sb.append(", channel=").append(channel);
96         sb.append('}');
97         return sb.toString();
98     }
99
100     protected final void replaceMessageDecoder(final ChannelHandler handler) {
101         replaceChannelHandler(AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, handler);
102     }
103
104     protected final void replaceMessageEncoder(final ChannelHandler handler) {
105         replaceChannelHandler(AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER, handler);
106     }
107
108     protected final void replaceMessageEncoderAfterNextMessage(final ChannelHandler handler) {
109         this.delayedEncoder = handler;
110     }
111
112     protected final void replaceChannelHandler(final String handlerName, final ChannelHandler handler) {
113         channel.pipeline().replace(handlerName, handlerName, handler);
114     }
115
116     @Override
117     public final void startExiCommunication(final NetconfMessage startExiMessage) {
118         final EXIParameters exiParams;
119         try {
120             exiParams = EXIParameters.fromXmlElement(XmlElement.fromDomDocument(startExiMessage.getDocument()));
121         } catch (final EXIOptionsException e) {
122             LOG.warn("Unable to parse EXI parameters from {} on session {}", startExiMessage, this, e);
123             throw new IllegalArgumentException("Cannot parse options", e);
124         }
125
126         final NetconfEXICodec exiCodec = new NetconfEXICodec(exiParams.getOptions());
127         final NetconfMessageToEXIEncoder exiEncoder;
128         try {
129             exiEncoder = NetconfMessageToEXIEncoder.create(exiCodec);
130         } catch (EXIOptionsException | TransmogrifierException e) {
131             LOG.warn("Failed to instantiate EXI encoder for {} on session {}", exiCodec, this, e);
132             throw new IllegalStateException("Cannot instantiate encoder for options", e);
133         }
134
135         final NetconfEXIToMessageDecoder exiDecoder;
136         try {
137             exiDecoder = NetconfEXIToMessageDecoder.create(exiCodec);
138         } catch (EXIOptionsException e) {
139             LOG.warn("Failed to instantiate EXI decodeer for {} on session {}", exiCodec, this, e);
140             throw new IllegalStateException("Cannot instantiate encoder for options", e);
141         }
142
143         addExiHandlers(exiDecoder, exiEncoder);
144         LOG.debug("Session {} EXI handlers added to pipeline", this);
145     }
146
147     /**
148      * Add a set encoder/decoder tuple into the channel pipeline as appropriate.
149      *
150      * @param decoder EXI decoder
151      * @param encoder EXI encoder
152      */
153     protected abstract void addExiHandlers(ByteToMessageDecoder decoder, MessageToByteEncoder<NetconfMessage> encoder);
154
155     public final boolean isUp() {
156         return up;
157     }
158
159     public final long getSessionId() {
160         return sessionId;
161     }
162 }