Merge "BUG-624 make netconf tcp address optional in config.ini with default value...
[controller.git] / opendaylight / netconf / netconf-ssh / src / main / java / org / opendaylight / controller / netconf / ssh / osgi / NetconfSSHActivator.java
index 5b8803001ca9a33f71d2cacab990f03891a6891e..d74308cfadbae8e658e58f9b189d93baaea83c2e 100644 (file)
@@ -7,7 +7,13 @@
  */
 package org.opendaylight.controller.netconf.ssh.osgi;
 
-import com.google.common.base.Optional;
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import org.apache.commons.io.FilenameUtils;
 import org.apache.commons.io.IOUtils;
 import org.opendaylight.controller.netconf.ssh.NetconfSSHServer;
 import org.opendaylight.controller.netconf.ssh.authentication.AuthProvider;
@@ -22,15 +28,10 @@ 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;
-
 /**
  * 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
+ * and listens 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.
@@ -41,29 +42,28 @@ 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) {
+        public IUserManager addingService(final ServiceReference<IUserManager> reference) {
             logger.trace("Service {} added, let there be SSH bridge.", reference);
             iUserManager =  context.getService(reference);
             try {
                 onUserManagerFound(iUserManager);
-            } catch (Exception e) {
+            } catch (final Exception e) {
                 logger.trace("Can't start SSH server due to {}",e);
             }
             return iUserManager;
         }
         @Override
-        public void modifiedService(ServiceReference<IUserManager> reference, IUserManager service) {
+        public void modifiedService(final ServiceReference<IUserManager> reference, final IUserManager service) {
             logger.trace("Replacing modified service {} in netconf SSH.", reference);
             server.addUserManagerService(service);
         }
         @Override
-        public void removedService(ServiceReference<IUserManager> reference, IUserManager service) {
+        public void removedService(final ServiceReference<IUserManager> reference, final IUserManager service) {
             logger.trace("Removing service {} from netconf SSH. " +
                     "SSH won't authenticate users until IUserManager service will be started.", reference);
             removeUserManagerService();
@@ -72,7 +72,7 @@ public class NetconfSSHActivator implements BundleActivator{
 
 
     @Override
-    public void start(BundleContext context)  {
+    public void start(final BundleContext context) {
         this.context = context;
         listenForManagerService();
     }
@@ -84,55 +84,49 @@ public class NetconfSSHActivator implements BundleActivator{
             logger.trace("Netconf SSH bridge is down ...");
         }
     }
-    private void startSSHServer() throws IllegalStateException, IOException {
+    private void startSSHServer() throws IOException {
+        checkNotNull(this.iUserManager, "No user manager service available.");
         logger.trace("Starting netconf SSH  bridge.");
-        Optional<InetSocketAddress> sshSocketAddressOptional = NetconfConfigUtil.extractSSHNetconfAddress(context, EXCEPTION_MESSAGE);
-        InetSocketAddress tcpSocketAddress = NetconfConfigUtil.extractTCPNetconfAddress(context,
-                EXCEPTION_MESSAGE, true);
+        final InetSocketAddress sshSocketAddress = NetconfConfigUtil.extractSSHNetconfAddress(context,
+                NetconfConfigUtil.DEFAULT_NETCONF_SSH_ADDRESS);
+        final InetSocketAddress tcpSocketAddress = NetconfConfigUtil.extractTCPNetconfClientAddress(context,
+               NetconfConfigUtil.DEFAULT_NETCONF_TCP_ADDRESS);
 
-        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.");
-            }
+        String path =  FilenameUtils.separatorsToSystem(NetconfConfigUtil.getPrivateKeyPath(context));
 
-            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;
+        if (path.isEmpty()) {
+            throw new IllegalStateException("Missing netconf.ssh.pk.path key in configuration file.");
+        }
+
+        final File privateKeyFile = new File(path);
+        final String privateKeyPEMString;
+        if (privateKeyFile.exists() == false) {
+            // generate & save to file
             try {
-                authProvider = new AuthProvider(iUserManager, privateKeyPEMString);
+                privateKeyPEMString = PEMGenerator.generateTo(privateKeyFile);
             } catch (Exception e) {
-                logger.error("Error instantiating AuthProvider {}",e);
+                logger.error("Exception occurred while generating PEM string {}", e);
+                throw new IllegalStateException("Error generating RSA key from file " + path);
             }
-            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.");
+            // read from file
+            try (FileInputStream fis = new FileInputStream(path)) {
+                privateKeyPEMString = IOUtils.toString(fis);
+            } catch (final IOException e) {
+                logger.error("Error reading RSA key from file '{}'", path);
+                throw new IOException("Error reading RSA key from file " + path, e);
+            }
         }
+        final AuthProvider authProvider = new AuthProvider(iUserManager, privateKeyPEMString);
+        this.server = NetconfSSHServer.start(sshSocketAddress.getPort(), tcpSocketAddress, authProvider);
+
+        final Thread serverThread = new Thread(server, "netconf SSH server thread");
+        serverThread.setDaemon(true);
+        serverThread.start();
+        logger.trace("Netconf SSH  bridge up and running.");
     }
-    private void onUserManagerFound(IUserManager userManager) throws IOException {
+
+    private void onUserManagerFound(final IUserManager userManager) throws Exception{
         if (server!=null && server.isUp()){
            server.addUserManagerService(userManager);
         } else {
@@ -143,7 +137,7 @@ public class NetconfSSHActivator implements BundleActivator{
         this.server.removeUserManagerService();
     }
     private void listenForManagerService(){
-        ServiceTracker<IUserManager, IUserManager> listenerTracker = new ServiceTracker<>(context, IUserManager.class,customizer);
+        final ServiceTracker<IUserManager, IUserManager> listenerTracker = new ServiceTracker<>(context, IUserManager.class,customizer);
         listenerTracker.open();
     }
 }