BUG-1422 Introduce Call-Home functionality for the NETCONF Topology.
[netconf.git] / netconf / callhome-protocol / src / main / java / org / opendaylight / netconf / callhome / protocol / CallHomeSessionContext.java
1 /*
2  * Copyright (c) 2016 Brocade Communication Systems 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.callhome.protocol;
10
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Throwables;
13 import io.netty.channel.EventLoopGroup;
14 import io.netty.util.concurrent.GlobalEventExecutor;
15 import io.netty.util.concurrent.Promise;
16 import java.io.IOException;
17 import java.net.InetSocketAddress;
18 import java.net.SocketAddress;
19 import java.security.PublicKey;
20 import java.util.concurrent.ConcurrentHashMap;
21 import java.util.concurrent.ConcurrentMap;
22 import javax.annotation.Nullable;
23 import javax.annotation.concurrent.GuardedBy;
24 import org.apache.sshd.ClientChannel;
25 import org.apache.sshd.ClientSession;
26 import org.apache.sshd.client.future.AuthFuture;
27 import org.apache.sshd.client.future.OpenFuture;
28 import org.apache.sshd.client.session.ClientSessionImpl;
29 import org.apache.sshd.common.Session;
30 import org.apache.sshd.common.future.SshFutureListener;
31 import org.opendaylight.netconf.client.NetconfClientSession;
32 import org.opendaylight.netconf.client.NetconfClientSessionListener;
33 import org.opendaylight.netconf.client.NetconfClientSessionNegotiatorFactory;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 class CallHomeSessionContext implements CallHomeProtocolSessionContext {
38
39     private static final Logger LOG = LoggerFactory.getLogger(CallHomeSessionContext.class);
40     static final Session.AttributeKey<CallHomeSessionContext> SESSION_KEY = new Session.AttributeKey<>();
41
42     private static final String NETCONF = "netconf";
43
44     private final ClientSessionImpl sshSession;
45     private final CallHomeAuthorization authorization;
46     private final Factory factory;
47
48     private volatile MinaSshNettyChannel nettyChannel = null;
49     private volatile boolean activated;
50
51     private InetSocketAddress remoteAddress;
52     private PublicKey serverKey;
53
54     CallHomeSessionContext(ClientSession sshSession, CallHomeAuthorization authorization, SocketAddress remoteAddress,
55             Factory factory) {
56         this.authorization = Preconditions.checkNotNull(authorization, "authorization");
57         Preconditions.checkArgument(this.authorization.isServerAllowed(), "Server was not allowed.");
58         Preconditions.checkArgument(sshSession instanceof ClientSessionImpl,
59                 "sshSession must implement ClientSessionImpl");
60         this.factory = Preconditions.checkNotNull(factory, "factory");
61         this.sshSession = (ClientSessionImpl) sshSession;
62         this.sshSession.setAttribute(SESSION_KEY, this);
63         this.remoteAddress = (InetSocketAddress) this.sshSession.getIoSession().getRemoteAddress();
64         this.serverKey = this.sshSession.getKex().getServerKey();
65     }
66
67     static CallHomeSessionContext getFrom(ClientSession sshSession) {
68         return sshSession.getAttribute(SESSION_KEY);
69     }
70
71     AuthFuture authorize() throws IOException {
72         authorization.applyTo(sshSession);
73         return sshSession.auth();
74     }
75
76     void openNetconfChannel() {
77         LOG.debug("Opening NETCONF Subsystem on {}", sshSession);
78         try {
79             final ClientChannel netconfChannel = sshSession.createSubsystemChannel(NETCONF);
80             netconfChannel.setStreaming(ClientChannel.Streaming.Async);
81             netconfChannel.open().addListener(newSshFutureListener(netconfChannel));
82         } catch (IOException e) {
83             throw Throwables.propagate(e);
84         }
85     }
86
87     SshFutureListener<OpenFuture> newSshFutureListener(final ClientChannel netconfChannel) {
88         return future -> 
89         {
90             if (future.isOpened()) {
91                 netconfChannelOpened(netconfChannel);
92             } else {
93                 channelOpenFailed(future.getException());
94             }
95         };
96     }
97
98     private void channelOpenFailed(Throwable e) {
99         LOG.error("Unable to open netconf subsystem, disconnecting.", e);
100         sshSession.close(false);
101     }
102
103     private void netconfChannelOpened(ClientChannel netconfChannel) {
104         nettyChannel = newMinaSshNettyChannel(netconfChannel);
105         factory.getChannelOpenListener().onNetconfSubsystemOpened(CallHomeSessionContext.this,
106             listener -> doActivate(listener));
107     }
108
109     @GuardedBy("this")
110     private synchronized Promise<NetconfClientSession> doActivate(NetconfClientSessionListener listener) {
111         if(activated) {
112             return newSessionPromise().setFailure(new IllegalStateException("Session already activated."));
113         }
114         activated = true;
115         LOG.info("Activating Netconf channel for {} with {}", getRemoteAddress(), listener);
116         Promise<NetconfClientSession> activationPromise = newSessionPromise();
117         factory.getChannelInitializer(listener).initialize(nettyChannel, activationPromise);
118         factory.getNettyGroup().register(nettyChannel).awaitUninterruptibly(500);
119         return activationPromise;
120     }
121
122     protected MinaSshNettyChannel newMinaSshNettyChannel(ClientChannel netconfChannel) {
123         return new MinaSshNettyChannel(this, sshSession, netconfChannel);
124     }
125
126     private Promise<NetconfClientSession> newSessionPromise() {
127         return GlobalEventExecutor.INSTANCE.newPromise();
128     }
129
130     @Override
131     public PublicKey getRemoteServerKey() {
132         return serverKey;
133     }
134
135     @Override
136     public String getRemoteServerVersion() {
137         return sshSession.getServerVersion();
138     }
139
140     @Override
141     public InetSocketAddress getRemoteAddress() {
142         return remoteAddress;
143     }
144
145     @Override
146     public String getSessionName() {
147         return authorization.getSessionName();
148     }
149
150     void removeSelf() {
151         factory.remove(this);
152     }
153
154     static class Factory {
155
156         private final EventLoopGroup nettyGroup;
157         private final NetconfClientSessionNegotiatorFactory negotiatorFactory;
158         private final CallHomeNetconfSubsystemListener subsystemListener;
159         private final ConcurrentMap<String, CallHomeSessionContext> sessions = new ConcurrentHashMap<>();
160
161         Factory(EventLoopGroup nettyGroup, NetconfClientSessionNegotiatorFactory negotiatorFactory,
162                 CallHomeNetconfSubsystemListener subsystemListener) {
163             this.nettyGroup = Preconditions.checkNotNull(nettyGroup, "nettyGroup");
164             this.negotiatorFactory = Preconditions.checkNotNull(negotiatorFactory, "negotiatorFactory");
165             this.subsystemListener = Preconditions.checkNotNull(subsystemListener);
166         }
167
168         void remove(CallHomeSessionContext session) {
169             sessions.remove(session.getSessionName(), session);
170         }
171
172         ReverseSshChannelInitializer getChannelInitializer(NetconfClientSessionListener listener) {
173             return ReverseSshChannelInitializer.create(negotiatorFactory, listener);
174         }
175
176         CallHomeNetconfSubsystemListener getChannelOpenListener() {
177             return this.subsystemListener;
178         }
179
180         @Nullable
181         CallHomeSessionContext createIfNotExists(ClientSession sshSession, CallHomeAuthorization authorization,
182                 SocketAddress remoteAddress) {
183             CallHomeSessionContext session = new CallHomeSessionContext(sshSession, authorization, remoteAddress, this);
184             CallHomeSessionContext preexisting = sessions.putIfAbsent(session.getSessionName(), session);
185             // If preexisting is null - session does not exist, so we can safely create new one, otherwise we return
186             // null and incoming connection will be rejected.
187             return preexisting == null ? session : null;
188         }
189
190         EventLoopGroup getNettyGroup() {
191             return nettyGroup;
192         }
193
194     }
195
196 }