Remove commons-io dependency in netconf-ssh
[controller.git] / opendaylight / netconf / netconf-ssh / src / main / java / org / opendaylight / controller / netconf / ssh / osgi / NetconfSSHActivator.java
index 5b8803001ca9a33f71d2cacab990f03891a6891e..fa87b73fad2b10bc977f0d88134c1fe21f5fb676 100644 (file)
  */
 package org.opendaylight.controller.netconf.ssh.osgi;
 
+import static com.google.common.base.Preconditions.checkState;
+
 import com.google.common.base.Optional;
-import org.apache.commons.io.IOUtils;
-import org.opendaylight.controller.netconf.ssh.NetconfSSHServer;
-import org.opendaylight.controller.netconf.ssh.authentication.AuthProvider;
-import org.opendaylight.controller.netconf.ssh.authentication.PEMGenerator;
+import com.google.common.base.Strings;
+import io.netty.channel.local.LocalAddress;
+import io.netty.channel.nio.NioEventLoopGroup;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ThreadFactory;
+import org.apache.sshd.common.util.ThreadUtils;
+import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
+import org.opendaylight.controller.netconf.ssh.SshProxyServer;
+import org.opendaylight.controller.netconf.ssh.SshProxyServerConfigurationBuilder;
 import org.opendaylight.controller.netconf.util.osgi.NetconfConfigUtil;
-import org.opendaylight.controller.usermanager.IUserManager;
+import org.opendaylight.controller.netconf.util.osgi.NetconfConfigUtil.InfixProp;
 import org.osgi.framework.BundleActivator;
 import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.util.tracker.ServiceTracker;
-import org.osgi.util.tracker.ServiceTrackerCustomizer;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.net.InetSocketAddress;
+public class NetconfSSHActivator implements BundleActivator {
+    private static final Logger LOG = LoggerFactory.getLogger(NetconfSSHActivator.class);
 
-/**
- * Activator for netconf SSH bundle which creates SSH bridge between netconf client and netconf server. Activator
- * starts SSH Server in its own thread. This thread is closed when activator calls stop() method. Server opens socket
- * and listen for client connections. Each client connection creation is handled in separate
- * {@link org.opendaylight.controller.netconf.ssh.threads.SocketThread} thread.
- * This thread creates two additional threads {@link org.opendaylight.controller.netconf.ssh.threads.IOThread}
- * forwarding data from/to client.IOThread closes servers session and server connection when it gets -1 on input stream.
- * {@link org.opendaylight.controller.netconf.ssh.threads.IOThread}'s run method waits for -1 on input stream to finish.
- * All threads are daemons.
- **/
-public class NetconfSSHActivator implements BundleActivator{
-
-    private NetconfSSHServer server;
-    private static final Logger logger =  LoggerFactory.getLogger(NetconfSSHActivator.class);
-    private static final String EXCEPTION_MESSAGE = "Netconf ssh bridge is not available.";
-    private IUserManager iUserManager;
-    private BundleContext context = null;
-
-    private ServiceTrackerCustomizer<IUserManager, IUserManager> customizer = new ServiceTrackerCustomizer<IUserManager, IUserManager>(){
-        @Override
-        public IUserManager addingService(ServiceReference<IUserManager> reference) {
-            logger.trace("Service {} added, let there be SSH bridge.", reference);
-            iUserManager =  context.getService(reference);
-            try {
-                onUserManagerFound(iUserManager);
-            } catch (Exception e) {
-                logger.trace("Can't start SSH server due to {}",e);
-            }
-            return iUserManager;
-        }
-        @Override
-        public void modifiedService(ServiceReference<IUserManager> reference, IUserManager service) {
-            logger.trace("Replacing modified service {} in netconf SSH.", reference);
-            server.addUserManagerService(service);
-        }
-        @Override
-        public void removedService(ServiceReference<IUserManager> reference, IUserManager service) {
-            logger.trace("Removing service {} from netconf SSH. " +
-                    "SSH won't authenticate users until IUserManager service will be started.", reference);
-            removeUserManagerService();
-        }
-    };
+    private static final java.lang.String ALGORITHM = "RSA";
+    private static final int KEY_SIZE = 4096;
+    public static final int POOL_SIZE = 8;
+    private static final int DEFAULT_IDLE_TIMEOUT = Integer.MAX_VALUE;
+
+    private ScheduledExecutorService minaTimerExecutor;
+    private NioEventLoopGroup clientGroup;
+    private ExecutorService nioExecutor;
+    private AuthProviderTracker authProviderTracker;
 
+    private SshProxyServer server;
 
     @Override
-    public void start(BundleContext context)  {
-        this.context = context;
-        listenForManagerService();
+    public void start(final BundleContext bundleContext) throws IOException {
+        minaTimerExecutor = Executors.newScheduledThreadPool(POOL_SIZE, new ThreadFactory() {
+            @Override
+            public Thread newThread(final Runnable r) {
+                return new Thread(r, "netconf-ssh-server-mina-timers");
+            }
+        });
+        clientGroup = new NioEventLoopGroup();
+        nioExecutor = ThreadUtils.newFixedThreadPool("netconf-ssh-server-nio-group", POOL_SIZE);
+        server = startSSHServer(bundleContext);
     }
 
     @Override
-    public void stop(BundleContext context) throws IOException {
-        if (server != null){
-            server.stop();
-            logger.trace("Netconf SSH bridge is down ...");
+    public void stop(final BundleContext context) throws IOException {
+        if (server != null) {
+            server.close();
         }
-    }
-    private void startSSHServer() throws IllegalStateException, IOException {
-        logger.trace("Starting netconf SSH  bridge.");
-        Optional<InetSocketAddress> sshSocketAddressOptional = NetconfConfigUtil.extractSSHNetconfAddress(context, EXCEPTION_MESSAGE);
-        InetSocketAddress tcpSocketAddress = NetconfConfigUtil.extractTCPNetconfAddress(context,
-                EXCEPTION_MESSAGE, true);
-
-        if (sshSocketAddressOptional.isPresent()){
-            String path = NetconfConfigUtil.getPrivateKeyPath(context);
-            path = path.replace("\\", "/");  // FIXME: shouldn't this convert lines to system dependent path separator?
-            if (path.equals("")){
-                throw new IllegalStateException("Missing netconf.ssh.pk.path key in configuration file.");
-            }
 
-            File privateKeyFile = new File(path);
-            String privateKeyPEMString = null;
-            if (privateKeyFile.exists() == false) {
-                // generate & save to file
-                try {
-                    privateKeyPEMString = PEMGenerator.generateTo(privateKeyFile);
-                } catch (Exception e) {
-                    logger.error("Exception occured while generating PEM string {}",e);
-                }
-            } else {
-                // read from file
-                try (FileInputStream fis = new FileInputStream(path)) {
-                    privateKeyPEMString = IOUtils.toString(fis);
-                } catch (IOException e) {
-                    logger.error("Error reading RSA key from file '{}'", path);
-                    throw new IllegalStateException("Error reading RSA key from file " + path);
-                }
-            }
-            AuthProvider authProvider = null;
-            try {
-                authProvider = new AuthProvider(iUserManager, privateKeyPEMString);
-            } catch (Exception e) {
-                logger.error("Error instantiating AuthProvider {}",e);
-            }
-            this.server = NetconfSSHServer.start(sshSocketAddressOptional.get().getPort(),tcpSocketAddress,authProvider);
-
-            Thread serverThread = new  Thread(server,"netconf SSH server thread");
-            serverThread.setDaemon(true);
-            serverThread.start();
-            logger.trace("Netconf SSH  bridge up and running.");
-        } else {
-            logger.trace("No valid connection configuration for SSH bridge found.");
-            throw new IllegalStateException("No valid connection configuration for SSH bridge found.");
+        if(authProviderTracker != null) {
+            authProviderTracker.stop();
         }
-    }
-    private void onUserManagerFound(IUserManager userManager) throws IOException {
-        if (server!=null && server.isUp()){
-           server.addUserManagerService(userManager);
-        } else {
-           startSSHServer();
+
+        if(nioExecutor!=null) {
+            nioExecutor.shutdownNow();
+        }
+
+        if(clientGroup != null) {
+            clientGroup.shutdownGracefully();
+        }
+
+        if(minaTimerExecutor != null) {
+            minaTimerExecutor.shutdownNow();
         }
     }
-    private void removeUserManagerService(){
-        this.server.removeUserManagerService();
-    }
-    private void listenForManagerService(){
-        ServiceTracker<IUserManager, IUserManager> listenerTracker = new ServiceTracker<>(context, IUserManager.class,customizer);
-        listenerTracker.open();
+
+    private SshProxyServer startSSHServer(final BundleContext bundleContext) throws IOException {
+        final Optional<InetSocketAddress> maybeSshSocketAddress = NetconfConfigUtil.extractNetconfServerAddress(bundleContext, InfixProp.ssh);
+
+        if (!maybeSshSocketAddress.isPresent()) {
+            LOG.trace("SSH bridge not configured");
+            return null;
+        }
+
+        final InetSocketAddress sshSocketAddress = maybeSshSocketAddress.get();
+        LOG.trace("Starting netconf SSH bridge at {}", sshSocketAddress);
+
+        final LocalAddress localAddress = NetconfConfigUtil.getNetconfLocalAddress();
+
+        authProviderTracker = new AuthProviderTracker(bundleContext);
+
+        final String path = NetconfConfigUtil.getPrivateKeyPath(bundleContext);
+
+        checkState(!Strings.isNullOrEmpty(path), "Path to ssh private key is blank. Reconfigure %s",
+                NetconfConfigUtil.getPrivateKeyKey());
+
+        final SshProxyServer sshProxyServer = new SshProxyServer(minaTimerExecutor, clientGroup, nioExecutor);
+        sshProxyServer.bind(
+                new SshProxyServerConfigurationBuilder()
+                        .setBindingAddress(sshSocketAddress)
+                        .setLocalAddress(localAddress)
+                        .setAuthenticator(authProviderTracker)
+                        .setKeyPairProvider(new PEMGeneratorHostKeyProvider(path, ALGORITHM, KEY_SIZE))
+                        .setIdleTimeout(DEFAULT_IDLE_TIMEOUT)
+                        .createSshProxyServerConfiguration());
+        return sshProxyServer;
     }
+
 }