2546015548a91409c9ad446280f7d91b3bcd45dc
[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 package org.opendaylight.netconf.topology.singleton.impl;
9
10 import static com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import com.google.common.util.concurrent.MoreExecutors;
18 import java.math.BigDecimal;
19 import java.net.InetSocketAddress;
20 import java.net.URL;
21 import java.util.ArrayList;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Optional;
25 import org.opendaylight.aaa.encrypt.AAAEncryptionService;
26 import org.opendaylight.netconf.api.NetconfMessage;
27 import org.opendaylight.netconf.client.NetconfClientSessionListener;
28 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
29 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration;
30 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder;
31 import org.opendaylight.netconf.nettyutil.ReconnectStrategyFactory;
32 import org.opendaylight.netconf.nettyutil.TimedReconnectStrategyFactory;
33 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
34 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.LoginPasswordHandler;
35 import org.opendaylight.netconf.sal.connect.api.DeviceActionFactory;
36 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
37 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
38 import org.opendaylight.netconf.sal.connect.netconf.LibraryModulesSchemas;
39 import org.opendaylight.netconf.sal.connect.netconf.NetconfDevice;
40 import org.opendaylight.netconf.sal.connect.netconf.NetconfDeviceBuilder;
41 import org.opendaylight.netconf.sal.connect.netconf.SchemalessNetconfDevice;
42 import org.opendaylight.netconf.sal.connect.netconf.auth.DatastoreBackedPublicKeyAuth;
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.sal.NetconfKeystoreAdapter;
49 import org.opendaylight.netconf.sal.connect.netconf.schema.YangLibrarySchemaYangSourceProvider;
50 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
51 import org.opendaylight.netconf.sal.connect.util.SslHandlerFactoryImpl;
52 import org.opendaylight.netconf.topology.singleton.api.RemoteDeviceConnector;
53 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
54 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
55 import org.opendaylight.netconf.topology.spi.NetconfConnectorDTO;
56 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
57 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
58 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
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.parameters.OdlHelloMessageCapabilities;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.parameters.Protocol;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapability.CapabilityOrigin;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.Credentials;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.KeyAuth;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPw;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPwUnencrypted;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.key.auth.KeyBased;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.login.pw.LoginPassword;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.login.pw.unencrypted.LoginPasswordUnencrypted;
70 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
71 import org.opendaylight.yangtools.yang.common.Decimal64;
72 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
73 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
74 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
75 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
76 import org.slf4j.Logger;
77 import org.slf4j.LoggerFactory;
78
79 public class RemoteDeviceConnectorImpl implements RemoteDeviceConnector {
80
81     private static final Logger LOG = LoggerFactory.getLogger(RemoteDeviceConnectorImpl.class);
82
83     // Initializes default constant instances for the case when the default schema repository
84     // directory cache/schema is used.
85
86     private final NetconfTopologySetup netconfTopologyDeviceSetup;
87     private final RemoteDeviceId remoteDeviceId;
88     private final String privateKeyPath;
89     private final String privateKeyPassphrase;
90     private final AAAEncryptionService encryptionService;
91     private final NetconfKeystoreAdapter keystoreAdapter;
92     private final DeviceActionFactory deviceActionFactory;
93
94     // FIXME: this seems to be a builder-like transition between {start,stop}RemoteDeviceConnection. More documentation
95     //        is needed, as to what the lifecycle is here.
96     private NetconfConnectorDTO deviceCommunicatorDTO;
97
98     public RemoteDeviceConnectorImpl(final NetconfTopologySetup netconfTopologyDeviceSetup,
99             final RemoteDeviceId remoteDeviceId, final DeviceActionFactory deviceActionFactory) {
100         this.netconfTopologyDeviceSetup = requireNonNull(netconfTopologyDeviceSetup);
101         this.remoteDeviceId = remoteDeviceId;
102         this.deviceActionFactory = requireNonNull(deviceActionFactory);
103         privateKeyPath = netconfTopologyDeviceSetup.getPrivateKeyPath();
104         privateKeyPassphrase = netconfTopologyDeviceSetup.getPrivateKeyPassphrase();
105         encryptionService = netconfTopologyDeviceSetup.getEncryptionService();
106         keystoreAdapter = new NetconfKeystoreAdapter(netconfTopologyDeviceSetup.getDataBroker());
107     }
108
109     @Override
110     public void startRemoteDeviceConnection(final RemoteDeviceHandler<NetconfSessionPreferences> deviceHandler) {
111
112         final NetconfNode netconfNode = netconfTopologyDeviceSetup.getNode().augmentation(NetconfNode.class);
113         final NodeId nodeId = netconfTopologyDeviceSetup.getNode().getNodeId();
114         requireNonNull(netconfNode.getHost());
115         requireNonNull(netconfNode.getPort());
116
117         deviceCommunicatorDTO = createDeviceCommunicator(nodeId, netconfNode, deviceHandler);
118         final NetconfDeviceCommunicator deviceCommunicator = deviceCommunicatorDTO.getCommunicator();
119         final NetconfClientSessionListener netconfClientSessionListener = deviceCommunicatorDTO.getSessionListener();
120         final NetconfReconnectingClientConfiguration clientConfig =
121                 getClientConfig(netconfClientSessionListener, netconfNode);
122         final ListenableFuture<NetconfDeviceCapabilities> future = deviceCommunicator
123                 .initializeRemoteConnection(netconfTopologyDeviceSetup.getNetconfClientDispatcher(), clientConfig);
124
125         Futures.addCallback(future, new FutureCallback<NetconfDeviceCapabilities>() {
126             @Override
127             public void onSuccess(final NetconfDeviceCapabilities result) {
128                 LOG.debug("{}: Connector started successfully", remoteDeviceId);
129             }
130
131             @Override
132             public void onFailure(final Throwable throwable) {
133                 LOG.error("{}: Connector failed", remoteDeviceId, throwable);
134             }
135         }, MoreExecutors.directExecutor());
136     }
137
138     @SuppressWarnings("checkstyle:IllegalCatch")
139     @Override
140     public void stopRemoteDeviceConnection() {
141         if (deviceCommunicatorDTO != null) {
142             try {
143                 deviceCommunicatorDTO.close();
144             } catch (final Exception e) {
145                 LOG.error("{}: Error at closing device communicator.", remoteDeviceId, e);
146             }
147         }
148     }
149
150     @VisibleForTesting
151     NetconfConnectorDTO createDeviceCommunicator(final NodeId nodeId, final NetconfNode node,
152                                                  final RemoteDeviceHandler<NetconfSessionPreferences> deviceHandler) {
153         //setup default values since default value is not supported in mdsal
154         final long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null
155                 ? NetconfTopologyUtils.DEFAULT_REQUEST_TIMEOUT_MILLIS : node.getDefaultRequestTimeoutMillis().toJava();
156         final long keepaliveDelay = node.getKeepaliveDelay() == null
157                 ? NetconfTopologyUtils.DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay().toJava();
158         final boolean reconnectOnChangedSchema = node.getReconnectOnChangedSchema() == null
159                 ? NetconfTopologyUtils.DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.getReconnectOnChangedSchema();
160
161         RemoteDeviceHandler<NetconfSessionPreferences> salFacade = requireNonNull(deviceHandler);
162         if (keepaliveDelay > 0) {
163             LOG.info("{}: Adding keepalive facade.", remoteDeviceId);
164             salFacade = new KeepaliveSalFacade(remoteDeviceId, salFacade,
165                     netconfTopologyDeviceSetup.getKeepaliveExecutor(), keepaliveDelay,
166                     defaultRequestTimeoutMillis);
167         }
168
169         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = netconfTopologyDeviceSetup.getSchemaResourcesDTO();
170
171         // pre register yang library sources as fallback schemas to schema registry
172         final List<SchemaSourceRegistration<?>> registeredYangLibSources = new ArrayList<>();
173         if (node.getYangLibrary() != null) {
174             final String yangLibURL = node.getYangLibrary().getYangLibraryUrl().getValue();
175             final String yangLibUsername = node.getYangLibrary().getUsername();
176             final String yangLigPassword = node.getYangLibrary().getPassword();
177
178             final LibraryModulesSchemas libraryModulesSchemas;
179             if (yangLibURL != null) {
180                 if (yangLibUsername != null && yangLigPassword != null) {
181                     libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL, yangLibUsername, yangLigPassword);
182                 } else {
183                     libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL);
184                 }
185
186                 for (final Map.Entry<SourceIdentifier, URL> sourceIdentifierURLEntry :
187                         libraryModulesSchemas.getAvailableModels().entrySet()) {
188                     registeredYangLibSources
189                             .add(schemaResourcesDTO.getSchemaRegistry().registerSchemaSource(
190                                     new YangLibrarySchemaYangSourceProvider(remoteDeviceId,
191                                             libraryModulesSchemas.getAvailableModels()),
192                                     PotentialSchemaSource
193                                             .create(sourceIdentifierURLEntry.getKey(), YangTextSchemaSource.class,
194                                                     PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
195                 }
196             }
197         }
198
199         final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> device;
200         if (node.getSchemaless()) {
201             device = new SchemalessNetconfDevice(netconfTopologyDeviceSetup.getBaseSchemas(), remoteDeviceId,
202                 salFacade);
203         } else {
204             device = new NetconfDeviceBuilder()
205                     .setReconnectOnSchemasChange(reconnectOnChangedSchema)
206                     .setSchemaResourcesDTO(schemaResourcesDTO)
207                     .setGlobalProcessingExecutor(netconfTopologyDeviceSetup.getProcessingExecutor())
208                     .setBaseSchemas(netconfTopologyDeviceSetup.getBaseSchemas())
209                     .setId(remoteDeviceId)
210                     .setDeviceActionFactory(deviceActionFactory)
211                     .setSalFacade(salFacade)
212                     .build();
213         }
214
215         final Optional<NetconfSessionPreferences> userCapabilities = getUserCapabilities(node);
216         final int rpcMessageLimit =
217                 node.getConcurrentRpcLimit() == null
218                         ? NetconfTopologyUtils.DEFAULT_CONCURRENT_RPC_LIMIT : node.getConcurrentRpcLimit().toJava();
219
220         if (rpcMessageLimit < 1) {
221             LOG.info("{}: Concurrent rpc limit is smaller than 1, no limit will be enforced.", remoteDeviceId);
222         }
223
224         NetconfDeviceCommunicator netconfDeviceCommunicator = userCapabilities.isPresent()
225             ? new NetconfDeviceCommunicator(remoteDeviceId, device, new UserPreferences(userCapabilities.get(),
226                 node.getYangModuleCapabilities() == null ? false : node.getYangModuleCapabilities().getOverride(),
227                     node.getNonModuleCapabilities() == null ? false : node.getNonModuleCapabilities().getOverride()),
228                 rpcMessageLimit)
229             : new NetconfDeviceCommunicator(remoteDeviceId, device, rpcMessageLimit);
230
231         if (salFacade instanceof KeepaliveSalFacade) {
232             ((KeepaliveSalFacade)salFacade).setListener(netconfDeviceCommunicator);
233         }
234         return new NetconfConnectorDTO(netconfDeviceCommunicator, salFacade, registeredYangLibSources);
235     }
236
237     private static 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         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 static 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().toJava();
279         final long maxConnectionAttempts = node.getMaxConnectionAttempts() == null
280                 ? NetconfTopologyUtils.DEFAULT_MAX_CONNECTION_ATTEMPTS : node.getMaxConnectionAttempts().toJava();
281         final int betweenAttemptsTimeoutMillis = node.getBetweenAttemptsTimeoutMillis() == null
282                 ? NetconfTopologyUtils.DEFAULT_BETWEEN_ATTEMPTS_TIMEOUT_MILLIS
283                 : node.getBetweenAttemptsTimeoutMillis().toJava();
284         final boolean isTcpOnly = node.getTcpOnly() == null
285                 ? NetconfTopologyUtils.DEFAULT_IS_TCP_ONLY : node.getTcpOnly();
286         final Decimal64 sleepFactor = node.getSleepFactor() == null
287                 ? NetconfTopologyUtils.DEFAULT_SLEEP_FACTOR : node.getSleepFactor();
288
289         final InetSocketAddress socketAddress = getSocketAddress(node.getHost(), node.getPort().getValue().toJava());
290
291         final ReconnectStrategyFactory sf =
292             new TimedReconnectStrategyFactory(netconfTopologyDeviceSetup.getEventExecutor(), maxConnectionAttempts,
293                 betweenAttemptsTimeoutMillis, BigDecimal.valueOf(sleepFactor.unscaledValue(), sleepFactor.scale()));
294
295
296         final NetconfReconnectingClientConfigurationBuilder reconnectingClientConfigurationBuilder;
297         final Protocol protocol = node.getProtocol();
298         if (isTcpOnly) {
299             reconnectingClientConfigurationBuilder = NetconfReconnectingClientConfigurationBuilder.create()
300                     .withProtocol(NetconfClientConfiguration.NetconfClientProtocol.TCP)
301                     .withAuthHandler(getHandlerFromCredentials(node.getCredentials()));
302         } else if (protocol == null || protocol.getName() == Protocol.Name.SSH) {
303             reconnectingClientConfigurationBuilder = NetconfReconnectingClientConfigurationBuilder.create()
304                     .withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH)
305                     .withAuthHandler(getHandlerFromCredentials(node.getCredentials()));
306         } else if (protocol.getName() == Protocol.Name.TLS) {
307             reconnectingClientConfigurationBuilder = NetconfReconnectingClientConfigurationBuilder.create()
308                     .withSslHandlerFactory(new SslHandlerFactoryImpl(keystoreAdapter, protocol.getSpecification()))
309                     .withProtocol(NetconfClientConfiguration.NetconfClientProtocol.TLS);
310         } else {
311             throw new IllegalStateException("Unsupported protocol type: " + protocol.getName());
312         }
313
314         final List<Uri> odlHelloCapabilities = getOdlHelloCapabilities(node);
315         if (odlHelloCapabilities != null) {
316             reconnectingClientConfigurationBuilder.withOdlHelloCapabilities(odlHelloCapabilities);
317         }
318
319         return reconnectingClientConfigurationBuilder
320                 .withAddress(socketAddress)
321                 .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
322                 .withReconnectStrategy(sf.createReconnectStrategy())
323                 .withConnectStrategyFactory(sf)
324                 .withSessionListener(listener)
325                 .build();
326     }
327
328     private static List<Uri> getOdlHelloCapabilities(final NetconfNode node) {
329         final OdlHelloMessageCapabilities helloCapabilities = node.getOdlHelloMessageCapabilities();
330         return helloCapabilities != null ? List.copyOf(helloCapabilities.getCapability()) : null;
331     }
332
333     private AuthenticationHandler getHandlerFromCredentials(final Credentials credentials) {
334         if (credentials instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology
335                 .rev150114.netconf.node.credentials.credentials.LoginPassword) {
336             final org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology
337                     .rev150114.netconf.node.credentials.credentials.LoginPassword loginPassword
338                     = (org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology
339                     .rev150114.netconf.node.credentials.credentials.LoginPassword) credentials;
340             return new LoginPasswordHandler(loginPassword.getUsername(), loginPassword.getPassword());
341         }
342         if (credentials instanceof LoginPwUnencrypted) {
343             final LoginPasswordUnencrypted loginPassword =
344                     ((LoginPwUnencrypted) credentials).getLoginPasswordUnencrypted();
345             return new LoginPasswordHandler(loginPassword.getUsername(), loginPassword.getPassword());
346         }
347         if (credentials instanceof LoginPw) {
348             final LoginPassword loginPassword = ((LoginPw) credentials).getLoginPassword();
349             return new LoginPasswordHandler(loginPassword.getUsername(),
350                     encryptionService.decrypt(loginPassword.getPassword()));
351         }
352         if (credentials instanceof KeyAuth) {
353             final KeyBased keyPair = ((KeyAuth) credentials).getKeyBased();
354             return new DatastoreBackedPublicKeyAuth(keyPair.getUsername(), keyPair.getKeyId(),
355                     keystoreAdapter, encryptionService);
356         }
357         throw new IllegalStateException("Unsupported credential type: " + credentials.getClass());
358     }
359 }