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