Merge changes from topic 'keyauth-refactor'
[netconf.git] / netconf / netconf-topology-singleton / src / main / java / org / opendaylight / netconf / topology / singleton / impl / RemoteDeviceConnectorImpl.java
1 /*
2  * Copyright (c) 2016 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
9 package org.opendaylight.netconf.topology.singleton.impl;
10
11 import akka.actor.ActorRef;
12 import akka.util.Timeout;
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.base.Preconditions;
15 import com.google.common.collect.Lists;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.MoreExecutors;
20 import io.netty.util.concurrent.EventExecutor;
21 import java.math.BigDecimal;
22 import java.net.InetSocketAddress;
23 import java.net.URL;
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Objects;
28 import java.util.Optional;
29 import javax.annotation.Nullable;
30 import org.opendaylight.aaa.encrypt.AAAEncryptionService;
31 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
32 import org.opendaylight.netconf.api.NetconfMessage;
33 import org.opendaylight.netconf.client.NetconfClientSessionListener;
34 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
35 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration;
36 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder;
37 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
38 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.LoginPasswordHandler;
39 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
40 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
41 import org.opendaylight.netconf.sal.connect.netconf.LibraryModulesSchemas;
42 import org.opendaylight.netconf.sal.connect.netconf.NetconfDevice;
43 import org.opendaylight.netconf.sal.connect.netconf.NetconfDeviceBuilder;
44 import org.opendaylight.netconf.sal.connect.netconf.SchemalessNetconfDevice;
45 import org.opendaylight.netconf.sal.connect.netconf.auth.DatastoreBackedPublicKeyAuth;
46 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
47 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
48 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
49 import org.opendaylight.netconf.sal.connect.netconf.listener.UserPreferences;
50 import org.opendaylight.netconf.sal.connect.netconf.sal.KeepaliveSalFacade;
51 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfKeystoreAdapter;
52 import org.opendaylight.netconf.sal.connect.netconf.schema.YangLibrarySchemaYangSourceProvider;
53 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
54 import org.opendaylight.netconf.topology.singleton.api.RemoteDeviceConnector;
55 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfConnectorDTO;
56 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
57 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
58 import org.opendaylight.protocol.framework.ReconnectStrategy;
59 import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
60 import org.opendaylight.protocol.framework.TimedReconnectStrategy;
61 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
62 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapability.CapabilityOrigin;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.Credentials;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.KeyAuth;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPasswordDeprecated;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPw;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPwUnencrypted;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.key.auth.KeyBased;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.login.pw.LoginPassword;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.login.pw.unencrypted.LoginPasswordUnencrypted;
73 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
74 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
75 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
76 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
77 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
80
81 public class RemoteDeviceConnectorImpl implements RemoteDeviceConnector {
82
83     private static final Logger LOG = LoggerFactory.getLogger(RemoteDeviceConnectorImpl.class);
84
85     // Initializes default constant instances for the case when the default schema repository
86     // directory cache/schema is used.
87
88     private final NetconfTopologySetup netconfTopologyDeviceSetup;
89     private final RemoteDeviceId remoteDeviceId;
90     private final DOMMountPointService mountService;
91     private final Timeout actorResponseWaitTime;
92     private final String privateKeyPath;
93     private final String privateKeyPassphrase;
94     private final AAAEncryptionService encryptionService;
95     private NetconfConnectorDTO deviceCommunicatorDTO;
96     private final NetconfKeystoreAdapter keystoreAdapter;
97
98     public RemoteDeviceConnectorImpl(final NetconfTopologySetup netconfTopologyDeviceSetup,
99                                      final RemoteDeviceId remoteDeviceId, final Timeout actorResponseWaitTime,
100                                      final DOMMountPointService mountService) {
101
102         this.netconfTopologyDeviceSetup = Preconditions.checkNotNull(netconfTopologyDeviceSetup);
103         this.remoteDeviceId = remoteDeviceId;
104         this.actorResponseWaitTime = actorResponseWaitTime;
105         this.mountService = mountService;
106         this.privateKeyPath = netconfTopologyDeviceSetup.getPrivateKeyPath();
107         this.privateKeyPassphrase = netconfTopologyDeviceSetup.getPrivateKeyPassphrase();
108         this.encryptionService = netconfTopologyDeviceSetup.getEncryptionService();
109         keystoreAdapter = new NetconfKeystoreAdapter(netconfTopologyDeviceSetup.getDataBroker());
110     }
111
112     @Override
113     public void startRemoteDeviceConnection(final ActorRef deviceContextActorRef) {
114
115         final NetconfNode netconfNode = netconfTopologyDeviceSetup.getNode().getAugmentation(NetconfNode.class);
116         final NodeId nodeId = netconfTopologyDeviceSetup.getNode().getNodeId();
117         Preconditions.checkNotNull(netconfNode.getHost());
118         Preconditions.checkNotNull(netconfNode.getPort());
119         Preconditions.checkNotNull(netconfNode.isTcpOnly());
120
121         this.deviceCommunicatorDTO = createDeviceCommunicator(nodeId, netconfNode, deviceContextActorRef);
122         final NetconfDeviceCommunicator deviceCommunicator = deviceCommunicatorDTO.getCommunicator();
123         final NetconfClientSessionListener netconfClientSessionListener = deviceCommunicatorDTO.getSessionListener();
124         final NetconfReconnectingClientConfiguration clientConfig =
125                 getClientConfig(netconfClientSessionListener, netconfNode);
126         final ListenableFuture<NetconfDeviceCapabilities> future = deviceCommunicator
127                 .initializeRemoteConnection(netconfTopologyDeviceSetup.getNetconfClientDispatcher(), clientConfig);
128
129         Futures.addCallback(future, new FutureCallback<NetconfDeviceCapabilities>() {
130             @Override
131             public void onSuccess(final NetconfDeviceCapabilities result) {
132                 LOG.debug("{}: Connector started successfully", remoteDeviceId);
133             }
134
135             @Override
136             public void onFailure(@Nullable final Throwable throwable) {
137                 LOG.error("{}: Connector failed, {}", remoteDeviceId, throwable);
138             }
139         }, MoreExecutors.directExecutor());
140     }
141
142     @SuppressWarnings("checkstyle:IllegalCatch")
143     @Override
144     public void stopRemoteDeviceConnection() {
145         Preconditions.checkNotNull(deviceCommunicatorDTO, remoteDeviceId + ": Device communicator was not created.");
146         try {
147             deviceCommunicatorDTO.close();
148         } catch (final Exception e) {
149             LOG.error("{}: Error at closing device communicator.", remoteDeviceId, e);
150         }
151     }
152
153     @VisibleForTesting
154     NetconfConnectorDTO createDeviceCommunicator(final NodeId nodeId, final NetconfNode node,
155                                                  final ActorRef deviceContextActorRef) {
156         //setup default values since default value is not supported in mdsal
157         final Long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null
158                 ? NetconfTopologyUtils.DEFAULT_REQUEST_TIMEOUT_MILLIS : node.getDefaultRequestTimeoutMillis();
159         final Long keepaliveDelay = node.getKeepaliveDelay() == null
160                 ? NetconfTopologyUtils.DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay();
161         final Boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null
162                 ? NetconfTopologyUtils.DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.isReconnectOnChangedSchema();
163
164         RemoteDeviceHandler<NetconfSessionPreferences> salFacade = new MasterSalFacade(remoteDeviceId,
165                 netconfTopologyDeviceSetup.getActorSystem(), deviceContextActorRef, actorResponseWaitTime,
166                 mountService, netconfTopologyDeviceSetup.getDataBroker());
167         if (keepaliveDelay > 0) {
168             LOG.info("{}: Adding keepalive facade.", remoteDeviceId);
169             salFacade = new KeepaliveSalFacade(remoteDeviceId, salFacade,
170                     netconfTopologyDeviceSetup.getKeepaliveExecutor().getExecutor(), keepaliveDelay,
171                     defaultRequestTimeoutMillis);
172         }
173
174         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = netconfTopologyDeviceSetup.getSchemaResourcesDTO();
175
176
177         // pre register yang library sources as fallback schemas to schema registry
178         final List<SchemaSourceRegistration<YangTextSchemaSource>> registeredYangLibSources = Lists.newArrayList();
179         if (node.getYangLibrary() != null) {
180             final String yangLibURL = node.getYangLibrary().getYangLibraryUrl().getValue();
181             final String yangLibUsername = node.getYangLibrary().getUsername();
182             final String yangLigPassword = node.getYangLibrary().getPassword();
183
184             final LibraryModulesSchemas libraryModulesSchemas;
185             if (yangLibURL != null) {
186                 if (yangLibUsername != null && yangLigPassword != null) {
187                     libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL, yangLibUsername, yangLigPassword);
188                 } else {
189                     libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL);
190                 }
191
192                 for (final Map.Entry<SourceIdentifier, URL> sourceIdentifierURLEntry :
193                         libraryModulesSchemas.getAvailableModels().entrySet()) {
194                     registeredYangLibSources
195                             .add(schemaResourcesDTO.getSchemaRegistry().registerSchemaSource(
196                                     new YangLibrarySchemaYangSourceProvider(remoteDeviceId,
197                                             libraryModulesSchemas.getAvailableModels()),
198                                     PotentialSchemaSource
199                                             .create(sourceIdentifierURLEntry.getKey(), YangTextSchemaSource.class,
200                                                     PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
201                 }
202             }
203         }
204
205         final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> device;
206         if (node.isSchemaless()) {
207             device = new SchemalessNetconfDevice(remoteDeviceId, salFacade);
208         } else {
209             device = new NetconfDeviceBuilder()
210                     .setReconnectOnSchemasChange(reconnectOnChangedSchema)
211                     .setSchemaResourcesDTO(schemaResourcesDTO)
212                     .setGlobalProcessingExecutor(netconfTopologyDeviceSetup.getProcessingExecutor().getExecutor())
213                     .setId(remoteDeviceId)
214                     .setSalFacade(salFacade)
215                     .build();
216         }
217
218         final Optional<NetconfSessionPreferences> userCapabilities = getUserCapabilities(node);
219         final int rpcMessageLimit =
220                 node.getConcurrentRpcLimit() == null
221                         ? NetconfTopologyUtils.DEFAULT_CONCURRENT_RPC_LIMIT : node.getConcurrentRpcLimit();
222
223         if (rpcMessageLimit < 1) {
224             LOG.info("{}: Concurrent rpc limit is smaller than 1, no limit will be enforced.", remoteDeviceId);
225         }
226
227         return new NetconfConnectorDTO(
228                 userCapabilities.isPresent() ? new NetconfDeviceCommunicator(remoteDeviceId, device,
229                         new UserPreferences(userCapabilities.get(),
230                                 Objects.isNull(node.getYangModuleCapabilities())
231                                         ? false : node.getYangModuleCapabilities().isOverride(),
232                                 Objects.isNull(node.getNonModuleCapabilities())
233                                         ? false : node.getNonModuleCapabilities().isOverride()), rpcMessageLimit)
234                         : new NetconfDeviceCommunicator(remoteDeviceId, device, rpcMessageLimit), salFacade);
235     }
236
237     private Optional<NetconfSessionPreferences> getUserCapabilities(final NetconfNode node) {
238         if (node.getYangModuleCapabilities() == null && node.getNonModuleCapabilities() == null) {
239             return Optional.empty();
240         }
241         final List<String> capabilities = new ArrayList<>();
242
243         if (node.getYangModuleCapabilities() != null) {
244             capabilities.addAll(node.getYangModuleCapabilities().getCapability());
245         }
246
247         //non-module capabilities should not exist in yang module capabilities
248         final NetconfSessionPreferences netconfSessionPreferences = NetconfSessionPreferences.fromStrings(capabilities);
249         Preconditions.checkState(netconfSessionPreferences.getNonModuleCaps().isEmpty(),
250                 "List yang-module-capabilities/capability should contain only module based capabilities. "
251                         + "Non-module capabilities used: " + netconfSessionPreferences.getNonModuleCaps());
252
253         if (node.getNonModuleCapabilities() != null) {
254             capabilities.addAll(node.getNonModuleCapabilities().getCapability());
255         }
256
257         return Optional.of(NetconfSessionPreferences.fromStrings(capabilities, CapabilityOrigin.UserDefined));
258     }
259
260     //TODO: duplicate code
261     private InetSocketAddress getSocketAddress(final Host host, final int port) {
262         if (host.getDomainName() != null) {
263             return new InetSocketAddress(host.getDomainName().getValue(), port);
264         } else {
265             final IpAddress ipAddress = host.getIpAddress();
266             final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() :
267                     ipAddress.getIpv6Address().getValue();
268             return new InetSocketAddress(ip, port);
269         }
270     }
271
272     @VisibleForTesting
273     NetconfReconnectingClientConfiguration getClientConfig(final NetconfClientSessionListener listener,
274                                                            final NetconfNode node) {
275
276         //setup default values since default value is not supported in mdsal
277         final long clientConnectionTimeoutMillis = node.getConnectionTimeoutMillis() == null
278                 ? NetconfTopologyUtils.DEFAULT_CONNECTION_TIMEOUT_MILLIS : node.getConnectionTimeoutMillis();
279         final long maxConnectionAttempts = node.getMaxConnectionAttempts() == null
280                 ? NetconfTopologyUtils.DEFAULT_MAX_CONNECTION_ATTEMPTS : node.getMaxConnectionAttempts();
281         final int betweenAttemptsTimeoutMillis = node.getBetweenAttemptsTimeoutMillis() == null
282                 ? NetconfTopologyUtils.DEFAULT_BETWEEN_ATTEMPTS_TIMEOUT_MILLIS : node.getBetweenAttemptsTimeoutMillis();
283         final BigDecimal sleepFactor = node.getSleepFactor() == null
284                 ? NetconfTopologyUtils.DEFAULT_SLEEP_FACTOR : node.getSleepFactor();
285
286         final InetSocketAddress socketAddress = getSocketAddress(node.getHost(), node.getPort().getValue());
287
288         final ReconnectStrategyFactory sf =
289                 new TimedReconnectStrategyFactory(netconfTopologyDeviceSetup.getEventExecutor(), maxConnectionAttempts,
290                         betweenAttemptsTimeoutMillis, sleepFactor);
291         final ReconnectStrategy strategy = sf.createReconnectStrategy();
292
293         final AuthenticationHandler authHandler = getHandlerFromCredentials(node.getCredentials());
294
295         return NetconfReconnectingClientConfigurationBuilder.create()
296                 .withAddress(socketAddress)
297                 .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
298                 .withReconnectStrategy(strategy)
299                 .withAuthHandler(authHandler)
300                 .withProtocol(node.isTcpOnly()
301                         ? NetconfClientConfiguration.NetconfClientProtocol.TCP
302                         : NetconfClientConfiguration.NetconfClientProtocol.SSH)
303                 .withConnectStrategyFactory(sf)
304                 .withSessionListener(listener)
305                 .build();
306     }
307
308     private AuthenticationHandler getHandlerFromCredentials(final Credentials credentials) {
309         if (credentials instanceof LoginPasswordDeprecated) {
310             final LoginPasswordDeprecated loginPassword = (LoginPasswordDeprecated) credentials;
311             return new LoginPasswordHandler(loginPassword.getUsername(), loginPassword.getPassword());
312         }
313         if (credentials instanceof LoginPwUnencrypted) {
314             final LoginPasswordUnencrypted loginPassword =
315                     ((LoginPwUnencrypted) credentials).getLoginPasswordUnencrypted();
316             return new LoginPasswordHandler(loginPassword.getUsername(), loginPassword.getPassword());
317         }
318         if (credentials instanceof LoginPw) {
319             final LoginPassword loginPassword = ((LoginPw) credentials).getLoginPassword();
320             return new LoginPasswordHandler(loginPassword.getUsername(),
321                     encryptionService.decrypt(loginPassword.getPassword()));
322         }
323         if (credentials instanceof KeyAuth) {
324             final KeyBased keyPair = ((KeyAuth) credentials).getKeyBased();
325             return new DatastoreBackedPublicKeyAuth(keyPair.getUsername(), keyPair.getKeyId(),
326                     keystoreAdapter, encryptionService);
327         }
328         throw new IllegalStateException("Unsupported credential type: " + credentials.getClass());
329     }
330
331     private static final class TimedReconnectStrategyFactory implements ReconnectStrategyFactory {
332         private final Long connectionAttempts;
333         private final EventExecutor executor;
334         private final double sleepFactor;
335         private final int minSleep;
336
337         TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts,
338                                       final int minSleep, final BigDecimal sleepFactor) {
339             if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
340                 connectionAttempts = maxConnectionAttempts;
341             } else {
342                 connectionAttempts = null;
343             }
344
345             this.sleepFactor = sleepFactor.doubleValue();
346             this.executor = executor;
347             this.minSleep = minSleep;
348         }
349
350         @Override
351         public ReconnectStrategy createReconnectStrategy() {
352             final Long maxSleep = null;
353             final Long deadline = null;
354
355             return new TimedReconnectStrategy(executor, minSleep,
356                     minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
357         }
358     }
359 }