Merge "Fix findbugs violations in netconf"
[netconf.git] / netconf / netconf-topology-singleton / src / main / java / org / opendaylight / netconf / topology / singleton / impl / RemoteDeviceConnectorImpl.java
index 39e86a9452fcaa83bf334e5f9333d976f5b817c0..40511bf781367eeffe2823de3a336a3251fe8f51 100644 (file)
@@ -16,6 +16,7 @@ import com.google.common.collect.Lists;
 import com.google.common.util.concurrent.FutureCallback;
 import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.MoreExecutors;
 import io.netty.util.concurrent.EventExecutor;
 import java.math.BigDecimal;
 import java.net.InetSocketAddress;
@@ -26,6 +27,7 @@ import java.util.Map;
 import java.util.Objects;
 import java.util.Optional;
 import javax.annotation.Nullable;
+import org.opendaylight.aaa.encrypt.AAAEncryptionService;
 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
 import org.opendaylight.netconf.api.NetconfMessage;
 import org.opendaylight.netconf.client.NetconfClientSessionListener;
@@ -33,18 +35,20 @@ import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration;
 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder;
 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
-import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.LoginPassword;
+import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.LoginPasswordHandler;
 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
 import org.opendaylight.netconf.sal.connect.netconf.LibraryModulesSchemas;
 import org.opendaylight.netconf.sal.connect.netconf.NetconfDevice;
 import org.opendaylight.netconf.sal.connect.netconf.NetconfDeviceBuilder;
 import org.opendaylight.netconf.sal.connect.netconf.SchemalessNetconfDevice;
+import org.opendaylight.netconf.sal.connect.netconf.auth.DatastoreBackedPublicKeyAuth;
 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
 import org.opendaylight.netconf.sal.connect.netconf.listener.UserPreferences;
 import org.opendaylight.netconf.sal.connect.netconf.sal.KeepaliveSalFacade;
+import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfKeystoreAdapter;
 import org.opendaylight.netconf.sal.connect.netconf.schema.YangLibrarySchemaYangSourceProvider;
 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
 import org.opendaylight.netconf.topology.singleton.api.RemoteDeviceConnector;
@@ -59,6 +63,12 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapability.CapabilityOrigin;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.Credentials;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.KeyAuth;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPw;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPwUnencrypted;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.key.auth.KeyBased;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.login.pw.LoginPassword;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.login.pw.unencrypted.LoginPasswordUnencrypted;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
@@ -78,8 +88,11 @@ public class RemoteDeviceConnectorImpl implements RemoteDeviceConnector {
     private final RemoteDeviceId remoteDeviceId;
     private final DOMMountPointService mountService;
     private final Timeout actorResponseWaitTime;
-
+    private final String privateKeyPath;
+    private final String privateKeyPassphrase;
+    private final AAAEncryptionService encryptionService;
     private NetconfConnectorDTO deviceCommunicatorDTO;
+    private final NetconfKeystoreAdapter keystoreAdapter;
 
     public RemoteDeviceConnectorImpl(final NetconfTopologySetup netconfTopologyDeviceSetup,
                                      final RemoteDeviceId remoteDeviceId, final Timeout actorResponseWaitTime,
@@ -89,6 +102,10 @@ public class RemoteDeviceConnectorImpl implements RemoteDeviceConnector {
         this.remoteDeviceId = remoteDeviceId;
         this.actorResponseWaitTime = actorResponseWaitTime;
         this.mountService = mountService;
+        this.privateKeyPath = netconfTopologyDeviceSetup.getPrivateKeyPath();
+        this.privateKeyPassphrase = netconfTopologyDeviceSetup.getPrivateKeyPassphrase();
+        this.encryptionService = netconfTopologyDeviceSetup.getEncryptionService();
+        keystoreAdapter = new NetconfKeystoreAdapter(netconfTopologyDeviceSetup.getDataBroker());
     }
 
     @Override
@@ -118,9 +135,10 @@ public class RemoteDeviceConnectorImpl implements RemoteDeviceConnector {
             public void onFailure(@Nullable final Throwable throwable) {
                 LOG.error("{}: Connector failed, {}", remoteDeviceId, throwable);
             }
-        });
+        }, MoreExecutors.directExecutor());
     }
 
+    @SuppressWarnings("checkstyle:IllegalCatch")
     @Override
     public void stopRemoteDeviceConnection() {
         Preconditions.checkNotNull(deviceCommunicatorDTO, remoteDeviceId + ": Device communicator was not created.");
@@ -135,11 +153,11 @@ public class RemoteDeviceConnectorImpl implements RemoteDeviceConnector {
     NetconfConnectorDTO createDeviceCommunicator(final NodeId nodeId, final NetconfNode node,
                                                  final ActorRef deviceContextActorRef) {
         //setup default values since default value is not supported in mdsal
-        final Long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null
+        final long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null
                 ? NetconfTopologyUtils.DEFAULT_REQUEST_TIMEOUT_MILLIS : node.getDefaultRequestTimeoutMillis();
-        final Long keepaliveDelay = node.getKeepaliveDelay() == null
+        final long keepaliveDelay = node.getKeepaliveDelay() == null
                 ? NetconfTopologyUtils.DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay();
-        final Boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null
+        final boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null
                 ? NetconfTopologyUtils.DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.isReconnectOnChangedSchema();
 
         RemoteDeviceHandler<NetconfSessionPreferences> salFacade = new MasterSalFacade(remoteDeviceId,
@@ -227,9 +245,9 @@ public class RemoteDeviceConnectorImpl implements RemoteDeviceConnector {
 
         //non-module capabilities should not exist in yang module capabilities
         final NetconfSessionPreferences netconfSessionPreferences = NetconfSessionPreferences.fromStrings(capabilities);
-        Preconditions.checkState(netconfSessionPreferences.getNonModuleCaps().isEmpty(), "List yang-module-capabilities/capability " +
-                "should contain only module based capabilities. Non-module capabilities used: " +
-                netconfSessionPreferences.getNonModuleCaps());
+        Preconditions.checkState(netconfSessionPreferences.getNonModuleCaps().isEmpty(),
+                "List yang-module-capabilities/capability should contain only module based capabilities. "
+                        + "Non-module capabilities used: " + netconfSessionPreferences.getNonModuleCaps());
 
         if (node.getNonModuleCapabilities() != null) {
             capabilities.addAll(node.getNonModuleCapabilities().getCapability());
@@ -271,15 +289,7 @@ public class RemoteDeviceConnectorImpl implements RemoteDeviceConnector {
                         betweenAttemptsTimeoutMillis, sleepFactor);
         final ReconnectStrategy strategy = sf.createReconnectStrategy();
 
-        final AuthenticationHandler authHandler;
-        final Credentials credentials = node.getCredentials();
-        if (credentials instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword) {
-            authHandler = new LoginPassword(
-                    ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword) credentials).getUsername(),
-                    ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword) credentials).getPassword());
-        } else {
-            throw new IllegalStateException(remoteDeviceId + ": Only login/password authentication is supported");
-        }
+        final AuthenticationHandler authHandler = getHandlerFromCredentials(node.getCredentials());
 
         return NetconfReconnectingClientConfigurationBuilder.create()
                 .withAddress(socketAddress)
@@ -294,6 +304,33 @@ public class RemoteDeviceConnectorImpl implements RemoteDeviceConnector {
                 .build();
     }
 
+    private AuthenticationHandler getHandlerFromCredentials(final Credentials credentials) {
+        if (credentials instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology
+                .rev150114.netconf.node.credentials.credentials.LoginPassword) {
+            final org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology
+                    .rev150114.netconf.node.credentials.credentials.LoginPassword loginPassword
+                    = (org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology
+                    .rev150114.netconf.node.credentials.credentials.LoginPassword) credentials;
+            return new LoginPasswordHandler(loginPassword.getUsername(), loginPassword.getPassword());
+        }
+        if (credentials instanceof LoginPwUnencrypted) {
+            final LoginPasswordUnencrypted loginPassword =
+                    ((LoginPwUnencrypted) credentials).getLoginPasswordUnencrypted();
+            return new LoginPasswordHandler(loginPassword.getUsername(), loginPassword.getPassword());
+        }
+        if (credentials instanceof LoginPw) {
+            final LoginPassword loginPassword = ((LoginPw) credentials).getLoginPassword();
+            return new LoginPasswordHandler(loginPassword.getUsername(),
+                    encryptionService.decrypt(loginPassword.getPassword()));
+        }
+        if (credentials instanceof KeyAuth) {
+            final KeyBased keyPair = ((KeyAuth) credentials).getKeyBased();
+            return new DatastoreBackedPublicKeyAuth(keyPair.getUsername(), keyPair.getKeyId(),
+                    keystoreAdapter, encryptionService);
+        }
+        throw new IllegalStateException("Unsupported credential type: " + credentials.getClass());
+    }
+
     private static final class TimedReconnectStrategyFactory implements ReconnectStrategyFactory {
         private final Long connectionAttempts;
         private final EventExecutor executor;
@@ -315,11 +352,8 @@ public class RemoteDeviceConnectorImpl implements RemoteDeviceConnector {
 
         @Override
         public ReconnectStrategy createReconnectStrategy() {
-            final Long maxSleep = null;
-            final Long deadline = null;
-
             return new TimedReconnectStrategy(executor, minSleep,
-                    minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
+                    minSleep, sleepFactor, null /*maxSleep*/, connectionAttempts, null /*deadline*/);
         }
     }
 }