Split up NetconfKeystoreAdapter
[netconf.git] / apps / 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 java.util.Objects.requireNonNull;
11
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.util.concurrent.FutureCallback;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import com.google.common.util.concurrent.MoreExecutors;
17 import java.math.BigDecimal;
18 import java.net.InetSocketAddress;
19 import java.util.ArrayList;
20 import java.util.List;
21 import org.opendaylight.aaa.encrypt.AAAEncryptionService;
22 import org.opendaylight.netconf.client.NetconfClientSessionListener;
23 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
24 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration;
25 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder;
26 import org.opendaylight.netconf.client.mdsal.DatastoreBackedPublicKeyAuth;
27 import org.opendaylight.netconf.client.mdsal.LibraryModulesSchemas;
28 import org.opendaylight.netconf.client.mdsal.LibrarySchemaSourceProvider;
29 import org.opendaylight.netconf.client.mdsal.NetconfDevice;
30 import org.opendaylight.netconf.client.mdsal.NetconfDeviceBuilder;
31 import org.opendaylight.netconf.client.mdsal.SchemalessNetconfDevice;
32 import org.opendaylight.netconf.client.mdsal.api.CredentialProvider;
33 import org.opendaylight.netconf.client.mdsal.api.DeviceActionFactory;
34 import org.opendaylight.netconf.client.mdsal.api.KeyStoreProvider;
35 import org.opendaylight.netconf.client.mdsal.api.RemoteDevice;
36 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceHandler;
37 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceId;
38 import org.opendaylight.netconf.nettyutil.ReconnectStrategyFactory;
39 import org.opendaylight.netconf.nettyutil.TimedReconnectStrategyFactory;
40 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
41 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.LoginPasswordHandler;
42 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
43 import org.opendaylight.netconf.sal.connect.netconf.sal.KeepaliveSalFacade;
44 import org.opendaylight.netconf.sal.connect.util.SslHandlerFactoryImpl;
45 import org.opendaylight.netconf.topology.singleton.api.RemoteDeviceConnector;
46 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
47 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
48 import org.opendaylight.netconf.topology.spi.NetconfConnectorDTO;
49 import org.opendaylight.netconf.topology.spi.NetconfNodeUtils;
50 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev230430.connection.parameters.OdlHelloMessageCapabilities;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev230430.connection.parameters.Protocol.Name;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev230430.credentials.Credentials;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev230430.credentials.credentials.KeyAuth;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev230430.credentials.credentials.LoginPw;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev230430.credentials.credentials.LoginPwUnencrypted;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev221225.NetconfNode;
58 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
59 import org.opendaylight.yangtools.yang.common.Decimal64;
60 import org.opendaylight.yangtools.yang.common.Empty;
61 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
62 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
63 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
66
67 public class RemoteDeviceConnectorImpl implements RemoteDeviceConnector {
68     private static final Logger LOG = LoggerFactory.getLogger(RemoteDeviceConnectorImpl.class);
69
70     // Initializes default constant instances for the case when the default schema repository
71     // directory cache/schema is used.
72
73     private final NetconfTopologySetup netconfTopologyDeviceSetup;
74     private final RemoteDeviceId remoteDeviceId;
75     private final AAAEncryptionService encryptionService;
76     private final CredentialProvider credentialProvider;
77     private final KeyStoreProvider keyStoreProvider;
78     private final DeviceActionFactory deviceActionFactory;
79
80     // FIXME: this seems to be a builder-like transition between {start,stop}RemoteDeviceConnection. More documentation
81     //        is needed, as to what the lifecycle is here.
82     private NetconfConnectorDTO deviceCommunicatorDTO;
83
84     public RemoteDeviceConnectorImpl(final NetconfTopologySetup netconfTopologyDeviceSetup,
85             final RemoteDeviceId remoteDeviceId, final DeviceActionFactory deviceActionFactory) {
86         this.netconfTopologyDeviceSetup = requireNonNull(netconfTopologyDeviceSetup);
87         this.remoteDeviceId = remoteDeviceId;
88         this.deviceActionFactory = requireNonNull(deviceActionFactory);
89         encryptionService = netconfTopologyDeviceSetup.getEncryptionService();
90         credentialProvider = netconfTopologyDeviceSetup.getCredentialProvider();
91         keyStoreProvider = netconfTopologyDeviceSetup.getKeyStoreProvider();
92     }
93
94     @Override
95     public void startRemoteDeviceConnection(final RemoteDeviceHandler deviceHandler) {
96
97         final NetconfNode netconfNode = netconfTopologyDeviceSetup.getNode().augmentation(NetconfNode.class);
98         final NodeId nodeId = netconfTopologyDeviceSetup.getNode().getNodeId();
99         requireNonNull(netconfNode.getHost());
100         requireNonNull(netconfNode.getPort());
101
102         deviceCommunicatorDTO = createDeviceCommunicator(nodeId, netconfNode, deviceHandler);
103         final NetconfDeviceCommunicator deviceCommunicator = deviceCommunicatorDTO.getCommunicator();
104         final NetconfClientSessionListener netconfClientSessionListener = deviceCommunicatorDTO.getSessionListener();
105         final NetconfReconnectingClientConfiguration clientConfig =
106                 getClientConfig(netconfClientSessionListener, netconfNode);
107         final ListenableFuture<Empty> future = deviceCommunicator
108                 .initializeRemoteConnection(netconfTopologyDeviceSetup.getNetconfClientDispatcher(), clientConfig);
109
110         Futures.addCallback(future, new FutureCallback<>() {
111             @Override
112             public void onSuccess(final Empty result) {
113                 LOG.debug("{}: Connector started successfully", remoteDeviceId);
114             }
115
116             @Override
117             public void onFailure(final Throwable throwable) {
118                 LOG.error("{}: Connector failed", remoteDeviceId, throwable);
119             }
120         }, MoreExecutors.directExecutor());
121     }
122
123     @SuppressWarnings("checkstyle:IllegalCatch")
124     @Override
125     public void stopRemoteDeviceConnection() {
126         if (deviceCommunicatorDTO != null) {
127             try {
128                 deviceCommunicatorDTO.close();
129             } catch (final Exception e) {
130                 LOG.error("{}: Error at closing device communicator.", remoteDeviceId, e);
131             }
132         }
133     }
134
135     @VisibleForTesting
136     NetconfConnectorDTO createDeviceCommunicator(final NodeId nodeId, final NetconfNode node,
137             final RemoteDeviceHandler deviceHandler) {
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().toJava();
141         final long keepaliveDelay = node.getKeepaliveDelay() == null
142                 ? NetconfTopologyUtils.DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay().toJava();
143         final boolean reconnectOnChangedSchema = node.getReconnectOnChangedSchema() == null
144                 ? NetconfTopologyUtils.DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.getReconnectOnChangedSchema();
145
146         RemoteDeviceHandler salFacade = requireNonNull(deviceHandler);
147         if (keepaliveDelay > 0) {
148             LOG.info("{}: Adding keepalive facade.", remoteDeviceId);
149             salFacade = new KeepaliveSalFacade(remoteDeviceId, salFacade,
150                     netconfTopologyDeviceSetup.getKeepaliveExecutor(), keepaliveDelay,
151                     defaultRequestTimeoutMillis);
152         }
153
154         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = netconfTopologyDeviceSetup.getSchemaResourcesDTO();
155
156         // pre register yang library sources as fallback schemas to schema registry
157         final List<SchemaSourceRegistration<?>> registeredYangLibSources = new ArrayList<>();
158         if (node.getYangLibrary() != null) {
159             final String yangLibURL = node.getYangLibrary().getYangLibraryUrl().getValue();
160             final String yangLibUsername = node.getYangLibrary().getUsername();
161             final String yangLigPassword = node.getYangLibrary().getPassword();
162
163             final LibraryModulesSchemas libraryModulesSchemas;
164             if (yangLibURL != null) {
165                 if (yangLibUsername != null && yangLigPassword != null) {
166                     libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL, yangLibUsername, yangLigPassword);
167                 } else {
168                     libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL);
169                 }
170
171                 for (var sourceIdentifierURLEntry : libraryModulesSchemas.getAvailableModels().entrySet()) {
172                     registeredYangLibSources.add(schemaResourcesDTO.getSchemaRegistry().registerSchemaSource(
173                         new LibrarySchemaSourceProvider(remoteDeviceId, libraryModulesSchemas.getAvailableModels()),
174                         PotentialSchemaSource.create(sourceIdentifierURLEntry.getKey(), YangTextSchemaSource.class,
175                             PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
176                 }
177             }
178         }
179
180         final RemoteDevice<NetconfDeviceCommunicator> device;
181         if (node.getSchemaless()) {
182             device = new SchemalessNetconfDevice(netconfTopologyDeviceSetup.getBaseSchemas(), remoteDeviceId,
183                 salFacade);
184         } else {
185             device = new NetconfDeviceBuilder()
186                     .setReconnectOnSchemasChange(reconnectOnChangedSchema)
187                     .setSchemaResourcesDTO(schemaResourcesDTO)
188                     .setGlobalProcessingExecutor(netconfTopologyDeviceSetup.getProcessingExecutor())
189                     .setBaseSchemas(netconfTopologyDeviceSetup.getBaseSchemas())
190                     .setId(remoteDeviceId)
191                     .setDeviceActionFactory(deviceActionFactory)
192                     .setSalFacade(salFacade)
193                     .build();
194         }
195
196         final int rpcMessageLimit = node.getConcurrentRpcLimit() == null
197             ? NetconfTopologyUtils.DEFAULT_CONCURRENT_RPC_LIMIT : node.getConcurrentRpcLimit().toJava();
198
199         if (rpcMessageLimit < 1) {
200             LOG.info("{}: Concurrent rpc limit is smaller than 1, no limit will be enforced.", remoteDeviceId);
201         }
202
203         final var netconfDeviceCommunicator = new NetconfDeviceCommunicator(remoteDeviceId, device, rpcMessageLimit,
204             NetconfNodeUtils.extractUserCapabilities(node));
205
206         if (salFacade instanceof KeepaliveSalFacade) {
207             ((KeepaliveSalFacade)salFacade).setListener(netconfDeviceCommunicator);
208         }
209         return new NetconfConnectorDTO(netconfDeviceCommunicator, salFacade, registeredYangLibSources);
210     }
211
212     @VisibleForTesting
213     NetconfReconnectingClientConfiguration getClientConfig(final NetconfClientSessionListener listener,
214                                                            final NetconfNode node) {
215
216         //setup default values since default value is not supported in mdsal
217         final long clientConnectionTimeoutMillis = node.getConnectionTimeoutMillis() == null
218                 ? NetconfTopologyUtils.DEFAULT_CONNECTION_TIMEOUT_MILLIS : node.getConnectionTimeoutMillis().toJava();
219         final long maxConnectionAttempts = node.getMaxConnectionAttempts() == null
220                 ? NetconfTopologyUtils.DEFAULT_MAX_CONNECTION_ATTEMPTS : node.getMaxConnectionAttempts().toJava();
221         final int betweenAttemptsTimeoutMillis = node.getBetweenAttemptsTimeoutMillis() == null
222                 ? NetconfTopologyUtils.DEFAULT_BETWEEN_ATTEMPTS_TIMEOUT_MILLIS
223                 : node.getBetweenAttemptsTimeoutMillis().toJava();
224         final boolean isTcpOnly = node.getTcpOnly() == null
225                 ? NetconfTopologyUtils.DEFAULT_IS_TCP_ONLY : node.getTcpOnly();
226         final Decimal64 sleepFactor = node.getSleepFactor() == null
227                 ? NetconfTopologyUtils.DEFAULT_SLEEP_FACTOR : node.getSleepFactor();
228
229         final InetSocketAddress socketAddress = NetconfNodeUtils.toInetSocketAddress(node);
230
231         final ReconnectStrategyFactory sf =
232             new TimedReconnectStrategyFactory(netconfTopologyDeviceSetup.getEventExecutor(), maxConnectionAttempts,
233                 betweenAttemptsTimeoutMillis, BigDecimal.valueOf(sleepFactor.unscaledValue(), sleepFactor.scale()));
234
235
236         final NetconfReconnectingClientConfigurationBuilder reconnectingClientConfigurationBuilder;
237         final var protocol = node.getProtocol();
238         if (isTcpOnly) {
239             reconnectingClientConfigurationBuilder = NetconfReconnectingClientConfigurationBuilder.create()
240                     .withProtocol(NetconfClientConfiguration.NetconfClientProtocol.TCP)
241                     .withAuthHandler(getHandlerFromCredentials(node.getCredentials()));
242         } else if (protocol == null || protocol.getName() == Name.SSH) {
243             reconnectingClientConfigurationBuilder = NetconfReconnectingClientConfigurationBuilder.create()
244                     .withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH)
245                     .withAuthHandler(getHandlerFromCredentials(node.getCredentials()));
246         } else if (protocol.getName() == Name.TLS) {
247             reconnectingClientConfigurationBuilder = NetconfReconnectingClientConfigurationBuilder.create()
248                     .withSslHandlerFactory(new SslHandlerFactoryImpl(keyStoreProvider, protocol.getSpecification()))
249                     .withProtocol(NetconfClientConfiguration.NetconfClientProtocol.TLS);
250         } else {
251             throw new IllegalStateException("Unsupported protocol type: " + protocol.getName());
252         }
253
254         final List<Uri> odlHelloCapabilities = getOdlHelloCapabilities(node);
255         if (odlHelloCapabilities != null) {
256             reconnectingClientConfigurationBuilder.withOdlHelloCapabilities(odlHelloCapabilities);
257         }
258
259         return reconnectingClientConfigurationBuilder
260                 .withAddress(socketAddress)
261                 .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
262                 .withReconnectStrategy(sf.createReconnectStrategy())
263                 .withConnectStrategyFactory(sf)
264                 .withSessionListener(listener)
265                 .build();
266     }
267
268     private static List<Uri> getOdlHelloCapabilities(final NetconfNode node) {
269         final OdlHelloMessageCapabilities helloCapabilities = node.getOdlHelloMessageCapabilities();
270         return helloCapabilities != null ? List.copyOf(helloCapabilities.getCapability()) : null;
271     }
272
273     private AuthenticationHandler getHandlerFromCredentials(final Credentials credentials) {
274         if (credentials
275                 instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev230430
276                     .credentials.credentials.LoginPassword loginPassword) {
277             return new LoginPasswordHandler(loginPassword.getUsername(), loginPassword.getPassword());
278         }
279         if (credentials instanceof LoginPwUnencrypted unencrypted) {
280             final var loginPassword = unencrypted.getLoginPasswordUnencrypted();
281             return new LoginPasswordHandler(loginPassword.getUsername(), loginPassword.getPassword());
282         }
283         if (credentials instanceof LoginPw loginPw) {
284             final var loginPassword = loginPw.getLoginPassword();
285             return new LoginPasswordHandler(loginPassword.getUsername(),
286                     encryptionService.decrypt(loginPassword.getPassword()));
287         }
288         if (credentials instanceof KeyAuth keyAuth) {
289             final var keyPair = keyAuth.getKeyBased();
290             return new DatastoreBackedPublicKeyAuth(keyPair.getUsername(), keyPair.getKeyId(),
291                     credentialProvider, encryptionService);
292         }
293         throw new IllegalStateException("Unsupported credential type: " + credentials.getClass());
294     }
295 }