Merge "XSQL Karaf Command"
[controller.git] / opendaylight / netconf / netconf-ssh / src / main / java / org / opendaylight / controller / netconf / ssh / NetconfSSHServer.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.ssh;
9
10 import com.google.common.base.Preconditions;
11 import java.io.IOException;
12 import java.net.InetSocketAddress;
13 import java.net.ServerSocket;
14 import java.net.Socket;
15 import java.util.concurrent.ExecutorService;
16 import java.util.concurrent.Executors;
17 import java.util.concurrent.atomic.AtomicLong;
18
19 import javax.annotation.concurrent.ThreadSafe;
20
21 import org.opendaylight.controller.netconf.auth.AuthProvider;
22 import org.opendaylight.controller.netconf.ssh.threads.Handshaker;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26 import com.google.common.annotations.VisibleForTesting;
27 import com.google.common.base.Optional;
28
29 import io.netty.channel.EventLoopGroup;
30 import io.netty.channel.local.LocalAddress;
31
32 /**
33  * Thread that accepts client connections. Accepted socket is forwarded to {@link org.opendaylight.controller.netconf.ssh.threads.Handshaker},
34  * which is executed in {@link #handshakeExecutor}.
35  */
36 @ThreadSafe
37 public final class NetconfSSHServer extends Thread implements AutoCloseable {
38
39     private static final Logger logger = LoggerFactory.getLogger(NetconfSSHServer.class);
40     private static final AtomicLong sessionIdCounter = new AtomicLong();
41
42     private final ServerSocket serverSocket;
43     private final LocalAddress localAddress;
44     private final EventLoopGroup bossGroup;
45     private Optional<AuthProvider> authProvider = Optional.absent();
46     private final ExecutorService handshakeExecutor;
47     private final char[] pem;
48     private volatile boolean up;
49
50     private NetconfSSHServer(final int serverPort, final LocalAddress localAddress, final EventLoopGroup bossGroup, final char[] pem) throws IOException {
51         super(NetconfSSHServer.class.getSimpleName());
52         this.bossGroup = bossGroup;
53         this.pem = pem;
54         logger.trace("Creating SSH server socket on port {}", serverPort);
55         this.serverSocket = new ServerSocket(serverPort);
56         if (serverSocket.isBound() == false) {
57             throw new IllegalStateException("Socket can't be bound to requested port :" + serverPort);
58         }
59         logger.trace("Server socket created.");
60         this.localAddress = localAddress;
61         this.up = true;
62         handshakeExecutor = Executors.newFixedThreadPool(10);
63     }
64
65     public static NetconfSSHServer start(final int serverPort, final LocalAddress localAddress, final EventLoopGroup bossGroup, final char[] pemArray) throws IOException {
66         final NetconfSSHServer netconfSSHServer = new NetconfSSHServer(serverPort, localAddress, bossGroup, pemArray);
67         netconfSSHServer.start();
68         return netconfSSHServer;
69     }
70
71     public synchronized AuthProvider getAuthProvider() {
72         Preconditions.checkState(authProvider.isPresent(), "AuthenticationProvider is not set up, cannot authenticate user");
73         return authProvider.get();
74     }
75
76     public synchronized void setAuthProvider(final AuthProvider authProvider) {
77         if(this.authProvider != null) {
78             logger.debug("Changing auth provider to {}", authProvider);
79         }
80         this.authProvider = Optional.fromNullable(authProvider);
81     }
82
83     @Override
84     public void close() throws IOException {
85         up = false;
86         logger.trace("Closing SSH server socket.");
87         serverSocket.close();
88         bossGroup.shutdownGracefully();
89         logger.trace("SSH server socket closed.");
90     }
91
92     @VisibleForTesting
93     public InetSocketAddress getLocalSocketAddress() {
94         return (InetSocketAddress) serverSocket.getLocalSocketAddress();
95     }
96
97     @Override
98     public void run() {
99         while (up) {
100             Socket acceptedSocket = null;
101             try {
102                 acceptedSocket = serverSocket.accept();
103             } catch (final IOException e) {
104                 if (up == false) {
105                     logger.trace("Exiting server thread", e);
106                 } else {
107                     logger.warn("Exception occurred during socket.accept", e);
108                 }
109             }
110             if (acceptedSocket != null) {
111                 try {
112                     final Handshaker task = new Handshaker(acceptedSocket, localAddress, sessionIdCounter.incrementAndGet(), getAuthProvider(), bossGroup, pem);
113                     handshakeExecutor.submit(task);
114                 } catch (final IOException e) {
115                     logger.warn("Cannot set PEMHostKey, closing connection", e);
116                     closeSocket(acceptedSocket);
117                 } catch (final IllegalStateException e) {
118                     logger.warn("Cannot accept connection, closing", e);
119                     closeSocket(acceptedSocket);
120                 }
121             }
122         }
123         logger.debug("Server thread is exiting");
124     }
125
126     private void closeSocket(final Socket acceptedSocket) {
127         try {
128             acceptedSocket.close();
129         } catch (final IOException e) {
130             logger.warn("Ignoring exception while closing socket", e);
131         }
132     }
133
134 }