Initial implementation of netconf monitoring module according to http://tools.ietf...
[controller.git] / opendaylight / netconf / netconf-util / src / main / java / org / opendaylight / controller / netconf / util / AbstractNetconfSessionNegotiator.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.controller.netconf.util;
10
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13
14 import io.netty.channel.Channel;
15 import io.netty.handler.ssl.SslHandler;
16 import io.netty.util.Timeout;
17 import io.netty.util.Timer;
18 import io.netty.util.TimerTask;
19 import io.netty.util.concurrent.Future;
20 import io.netty.util.concurrent.GenericFutureListener;
21 import io.netty.util.concurrent.Promise;
22
23 import org.opendaylight.controller.netconf.api.NetconfSession;
24 import org.opendaylight.controller.netconf.api.NetconfMessage;
25 import org.opendaylight.controller.netconf.api.NetconfSessionPreferences;
26 import org.opendaylight.controller.netconf.util.handler.FramingMechanismHandlerFactory;
27 import org.opendaylight.controller.netconf.util.handler.NetconfMessageAggregator;
28 import org.opendaylight.controller.netconf.util.handler.NetconfMessageChunkDecoder;
29 import org.opendaylight.controller.netconf.util.messages.FramingMechanism;
30 import org.opendaylight.controller.netconf.util.xml.XmlElement;
31 import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
32 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
33 import org.opendaylight.protocol.framework.AbstractSessionNegotiator;
34 import org.opendaylight.protocol.framework.SessionListener;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.w3c.dom.Document;
38 import org.w3c.dom.NodeList;
39
40 import java.util.concurrent.TimeUnit;
41
42 public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionPreferences, S extends NetconfSession>
43         extends AbstractSessionNegotiator<NetconfMessage, S> {
44
45     // TODO what time ?
46     private static final long INITIAL_HOLDTIMER = 1;
47     private static final Logger logger = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
48
49     protected final P sessionPreferences;
50
51     private final SessionListener sessionListener;
52
53     /**
54      * Possible states for Finite State Machine
55      */
56     private enum State {
57         IDLE, OPEN_WAIT, FAILED, ESTABLISHED
58     }
59
60     private State state = State.IDLE;
61     private final Timer timer;
62
63     protected AbstractNetconfSessionNegotiator(P sessionPreferences, Promise<S> promise, Channel channel, Timer timer,
64             SessionListener sessionListener) {
65         super(promise, channel);
66         this.sessionPreferences = sessionPreferences;
67         this.timer = timer;
68         this.sessionListener = sessionListener;
69     }
70
71     @Override
72     protected void startNegotiation() throws Exception {
73         final Optional<SslHandler> sslHandler = getSslHandler(channel);
74         if (sslHandler.isPresent()) {
75             Future<Channel> future = sslHandler.get().handshakeFuture();
76             future.addListener(new GenericFutureListener<Future<? super Channel>>() {
77                 @Override
78                 public void operationComplete(Future<? super Channel> future) throws Exception {
79                     Preconditions.checkState(future.isSuccess(), "Ssl handshake was not successful");
80                     logger.debug("Ssl handshake complete");
81                     start();
82                 }
83             });
84         } else
85             start();
86     }
87
88     private static Optional<SslHandler> getSslHandler(Channel channel) {
89         final SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
90         return sslHandler == null ? Optional.<SslHandler> absent() : Optional.of(sslHandler);
91     }
92
93     private void start() {
94         final NetconfMessage helloMessage = this.sessionPreferences.getHelloMessage();
95         logger.debug("Session negotiation started with hello message {}", XmlUtil.toString(helloMessage.getDocument()));
96
97         sendMessage(helloMessage);
98         changeState(State.OPEN_WAIT);
99
100         this.timer.newTimeout(new TimerTask() {
101             @Override
102             public void run(final Timeout timeout) throws Exception {
103                 synchronized (this) {
104                     if (state != State.ESTABLISHED) {
105                         final IllegalStateException cause = new IllegalStateException(
106                                 "Session was not established after " + timeout);
107                         negotiationFailed(cause);
108                         changeState(State.FAILED);
109                     }
110                 }
111             }
112         }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
113     }
114
115     private void sendMessage(NetconfMessage message) {
116         this.channel.writeAndFlush(message);
117     }
118
119     @Override
120     protected void handleMessage(NetconfMessage netconfMessage) {
121         final Document doc = netconfMessage.getDocument();
122
123         if (isHelloMessage(doc)) {
124             if (containsBase11Capability(doc)
125                     && containsBase11Capability(sessionPreferences.getHelloMessage().getDocument())) {
126                 channel.pipeline().replace("frameEncoder", "frameEncoder",
127                         FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK));
128                 channel.pipeline().replace("aggregator", "aggregator",
129                         new NetconfMessageAggregator(FramingMechanism.CHUNK));
130                 channel.pipeline().addAfter("aggregator", "chunkDecoder", new NetconfMessageChunkDecoder());
131             }
132             changeState(State.ESTABLISHED);
133             S session = getSession(sessionListener, channel, netconfMessage);
134             negotiationSuccessful(session);
135         } else {
136             final IllegalStateException cause = new IllegalStateException(
137                     "Received message was not hello as expected, but was " + XmlUtil.toString(doc));
138             logger.warn("Negotiation of netconf session failed", cause);
139             negotiationFailed(cause);
140         }
141     }
142
143     protected abstract S getSession(SessionListener sessionListener, Channel channel, NetconfMessage message);
144
145     private boolean isHelloMessage(Document doc) {
146         try {
147             XmlElement.fromDomElementWithExpected(doc.getDocumentElement(), "hello",
148                     XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
149
150         } catch (IllegalArgumentException | IllegalStateException e) {
151             return false;
152         }
153         return true;
154     }
155
156     private void changeState(final State newState) {
157         logger.debug("Changing state from : {} to : {}", state, newState);
158         Preconditions.checkState(isStateChangePermitted(state, newState), "Cannot change state from %s to %s", state,
159                 newState);
160         this.state = newState;
161     }
162
163     private boolean containsBase11Capability(final Document doc) {
164         final NodeList nList = doc.getElementsByTagName("capability");
165         for (int i = 0; i < nList.getLength(); i++) {
166             if (nList.item(i).getTextContent().contains("base:1.1")) {
167                 return true;
168             }
169         }
170         return false;
171     }
172
173     private static boolean isStateChangePermitted(State state, State newState) {
174         if (state == State.IDLE && newState == State.OPEN_WAIT)
175             return true;
176         if (state == State.OPEN_WAIT && newState == State.ESTABLISHED)
177             return true;
178         if (state == State.OPEN_WAIT && newState == State.FAILED)
179             return true;
180
181         return false;
182     }
183 }