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