Remove netconf-topology-singleton's NetconfConnectorDTO
[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.model.repo.api.SourceIdentifier;
72 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
73 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
74 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
77
78 public class RemoteDeviceConnectorImpl implements RemoteDeviceConnector {
79
80     private static final Logger LOG = LoggerFactory.getLogger(RemoteDeviceConnectorImpl.class);
81
82     // Initializes default constant instances for the case when the default schema repository
83     // directory cache/schema is used.
84
85     private final NetconfTopologySetup netconfTopologyDeviceSetup;
86     private final RemoteDeviceId remoteDeviceId;
87     private final String privateKeyPath;
88     private final String privateKeyPassphrase;
89     private final AAAEncryptionService encryptionService;
90     private final NetconfKeystoreAdapter keystoreAdapter;
91     private final DeviceActionFactory deviceActionFactory;
92
93     // FIXME: this seems to be a builder-like transition between {start,stop}RemoteDeviceConnection. More documentation
94     //        is needed, as to what the lifecycle is here.
95     private NetconfConnectorDTO deviceCommunicatorDTO;
96
97     public RemoteDeviceConnectorImpl(final NetconfTopologySetup netconfTopologyDeviceSetup,
98             final RemoteDeviceId remoteDeviceId, final DeviceActionFactory deviceActionFactory) {
99         this.netconfTopologyDeviceSetup = requireNonNull(netconfTopologyDeviceSetup);
100         this.remoteDeviceId = remoteDeviceId;
101         this.deviceActionFactory = requireNonNull(deviceActionFactory);
102         this.privateKeyPath = netconfTopologyDeviceSetup.getPrivateKeyPath();
103         this.privateKeyPassphrase = netconfTopologyDeviceSetup.getPrivateKeyPassphrase();
104         this.encryptionService = netconfTopologyDeviceSetup.getEncryptionService();
105         keystoreAdapter = new NetconfKeystoreAdapter(netconfTopologyDeviceSetup.getDataBroker());
106     }
107
108     @Override
109     public void startRemoteDeviceConnection(final RemoteDeviceHandler<NetconfSessionPreferences> deviceHandler) {
110
111         final NetconfNode netconfNode = netconfTopologyDeviceSetup.getNode().augmentation(NetconfNode.class);
112         final NodeId nodeId = netconfTopologyDeviceSetup.getNode().getNodeId();
113         requireNonNull(netconfNode.getHost());
114         requireNonNull(netconfNode.getPort());
115
116         this.deviceCommunicatorDTO = createDeviceCommunicator(nodeId, netconfNode, deviceHandler);
117         final NetconfDeviceCommunicator deviceCommunicator = deviceCommunicatorDTO.getCommunicator();
118         final NetconfClientSessionListener netconfClientSessionListener = deviceCommunicatorDTO.getSessionListener();
119         final NetconfReconnectingClientConfiguration clientConfig =
120                 getClientConfig(netconfClientSessionListener, netconfNode);
121         final ListenableFuture<NetconfDeviceCapabilities> future = deviceCommunicator
122                 .initializeRemoteConnection(netconfTopologyDeviceSetup.getNetconfClientDispatcher(), clientConfig);
123
124         Futures.addCallback(future, new FutureCallback<NetconfDeviceCapabilities>() {
125             @Override
126             public void onSuccess(final NetconfDeviceCapabilities result) {
127                 LOG.debug("{}: Connector started successfully", remoteDeviceId);
128             }
129
130             @Override
131             public void onFailure(final Throwable throwable) {
132                 LOG.error("{}: Connector failed", remoteDeviceId, throwable);
133             }
134         }, MoreExecutors.directExecutor());
135     }
136
137     @SuppressWarnings("checkstyle:IllegalCatch")
138     @Override
139     public void stopRemoteDeviceConnection() {
140         if (deviceCommunicatorDTO != null) {
141             try {
142                 deviceCommunicatorDTO.close();
143             } catch (final Exception e) {
144                 LOG.error("{}: Error at closing device communicator.", remoteDeviceId, e);
145             }
146         }
147     }
148
149     @VisibleForTesting
150     NetconfConnectorDTO createDeviceCommunicator(final NodeId nodeId, final NetconfNode node,
151                                                  final RemoteDeviceHandler<NetconfSessionPreferences> deviceHandler) {
152         //setup default values since default value is not supported in mdsal
153         final long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null
154                 ? NetconfTopologyUtils.DEFAULT_REQUEST_TIMEOUT_MILLIS : node.getDefaultRequestTimeoutMillis().toJava();
155         final long keepaliveDelay = node.getKeepaliveDelay() == null
156                 ? NetconfTopologyUtils.DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay().toJava();
157         final boolean reconnectOnChangedSchema = node.getReconnectOnChangedSchema() == null
158                 ? NetconfTopologyUtils.DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.getReconnectOnChangedSchema();
159
160         RemoteDeviceHandler<NetconfSessionPreferences> salFacade = requireNonNull(deviceHandler);
161         if (keepaliveDelay > 0) {
162             LOG.info("{}: Adding keepalive facade.", remoteDeviceId);
163             salFacade = new KeepaliveSalFacade(remoteDeviceId, salFacade,
164                     netconfTopologyDeviceSetup.getKeepaliveExecutor(), keepaliveDelay,
165                     defaultRequestTimeoutMillis);
166         }
167
168         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = netconfTopologyDeviceSetup.getSchemaResourcesDTO();
169
170         // pre register yang library sources as fallback schemas to schema registry
171         final List<SchemaSourceRegistration<?>> registeredYangLibSources = new ArrayList<>();
172         if (node.getYangLibrary() != null) {
173             final String yangLibURL = node.getYangLibrary().getYangLibraryUrl().getValue();
174             final String yangLibUsername = node.getYangLibrary().getUsername();
175             final String yangLigPassword = node.getYangLibrary().getPassword();
176
177             final LibraryModulesSchemas libraryModulesSchemas;
178             if (yangLibURL != null) {
179                 if (yangLibUsername != null && yangLigPassword != null) {
180                     libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL, yangLibUsername, yangLigPassword);
181                 } else {
182                     libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL);
183                 }
184
185                 for (final Map.Entry<SourceIdentifier, URL> sourceIdentifierURLEntry :
186                         libraryModulesSchemas.getAvailableModels().entrySet()) {
187                     registeredYangLibSources
188                             .add(schemaResourcesDTO.getSchemaRegistry().registerSchemaSource(
189                                     new YangLibrarySchemaYangSourceProvider(remoteDeviceId,
190                                             libraryModulesSchemas.getAvailableModels()),
191                                     PotentialSchemaSource
192                                             .create(sourceIdentifierURLEntry.getKey(), YangTextSchemaSource.class,
193                                                     PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
194                 }
195             }
196         }
197
198         final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> device;
199         if (node.getSchemaless()) {
200             device = new SchemalessNetconfDevice(netconfTopologyDeviceSetup.getBaseSchemas(), remoteDeviceId,
201                 salFacade);
202         } else {
203             device = new NetconfDeviceBuilder()
204                     .setReconnectOnSchemasChange(reconnectOnChangedSchema)
205                     .setSchemaResourcesDTO(schemaResourcesDTO)
206                     .setGlobalProcessingExecutor(netconfTopologyDeviceSetup.getProcessingExecutor())
207                     .setBaseSchemas(netconfTopologyDeviceSetup.getBaseSchemas())
208                     .setId(remoteDeviceId)
209                     .setDeviceActionFactory(deviceActionFactory)
210                     .setSalFacade(salFacade)
211                     .build();
212         }
213
214         final Optional<NetconfSessionPreferences> userCapabilities = getUserCapabilities(node);
215         final int rpcMessageLimit =
216                 node.getConcurrentRpcLimit() == null
217                         ? NetconfTopologyUtils.DEFAULT_CONCURRENT_RPC_LIMIT : node.getConcurrentRpcLimit().toJava();
218
219         if (rpcMessageLimit < 1) {
220             LOG.info("{}: Concurrent rpc limit is smaller than 1, no limit will be enforced.", remoteDeviceId);
221         }
222
223         NetconfDeviceCommunicator netconfDeviceCommunicator = userCapabilities.isPresent()
224             ? new NetconfDeviceCommunicator(remoteDeviceId, device, new UserPreferences(userCapabilities.get(),
225                 node.getYangModuleCapabilities() == null ? false : node.getYangModuleCapabilities().getOverride(),
226                     node.getNonModuleCapabilities() == null ? false : node.getNonModuleCapabilities().getOverride()),
227                 rpcMessageLimit)
228             : new NetconfDeviceCommunicator(remoteDeviceId, device, rpcMessageLimit);
229
230         if (salFacade instanceof KeepaliveSalFacade) {
231             ((KeepaliveSalFacade)salFacade).setListener(netconfDeviceCommunicator);
232         }
233         return new NetconfConnectorDTO(netconfDeviceCommunicator, salFacade, registeredYangLibSources);
234     }
235
236     private static Optional<NetconfSessionPreferences> getUserCapabilities(final NetconfNode node) {
237         if (node.getYangModuleCapabilities() == null && node.getNonModuleCapabilities() == null) {
238             return Optional.empty();
239         }
240         final List<String> capabilities = new ArrayList<>();
241
242         if (node.getYangModuleCapabilities() != null) {
243             capabilities.addAll(node.getYangModuleCapabilities().getCapability());
244         }
245
246         //non-module capabilities should not exist in yang module capabilities
247         final NetconfSessionPreferences netconfSessionPreferences = NetconfSessionPreferences.fromStrings(capabilities);
248         checkState(netconfSessionPreferences.getNonModuleCaps().isEmpty(),
249                 "List yang-module-capabilities/capability should contain only module based capabilities. "
250                         + "Non-module capabilities used: " + netconfSessionPreferences.getNonModuleCaps());
251
252         if (node.getNonModuleCapabilities() != null) {
253             capabilities.addAll(node.getNonModuleCapabilities().getCapability());
254         }
255
256         return Optional.of(NetconfSessionPreferences.fromStrings(capabilities, CapabilityOrigin.UserDefined));
257     }
258
259     //TODO: duplicate code
260     private static InetSocketAddress getSocketAddress(final Host host, final int port) {
261         if (host.getDomainName() != null) {
262             return new InetSocketAddress(host.getDomainName().getValue(), port);
263         } else {
264             final IpAddress ipAddress = host.getIpAddress();
265             final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() :
266                     ipAddress.getIpv6Address().getValue();
267             return new InetSocketAddress(ip, port);
268         }
269     }
270
271     @VisibleForTesting
272     NetconfReconnectingClientConfiguration getClientConfig(final NetconfClientSessionListener listener,
273                                                            final NetconfNode node) {
274
275         //setup default values since default value is not supported in mdsal
276         final long clientConnectionTimeoutMillis = node.getConnectionTimeoutMillis() == null
277                 ? NetconfTopologyUtils.DEFAULT_CONNECTION_TIMEOUT_MILLIS : node.getConnectionTimeoutMillis().toJava();
278         final long maxConnectionAttempts = node.getMaxConnectionAttempts() == null
279                 ? NetconfTopologyUtils.DEFAULT_MAX_CONNECTION_ATTEMPTS : node.getMaxConnectionAttempts().toJava();
280         final int betweenAttemptsTimeoutMillis = node.getBetweenAttemptsTimeoutMillis() == null
281                 ? NetconfTopologyUtils.DEFAULT_BETWEEN_ATTEMPTS_TIMEOUT_MILLIS
282                 : node.getBetweenAttemptsTimeoutMillis().toJava();
283         final boolean isTcpOnly = node.getTcpOnly() == null
284                 ? NetconfTopologyUtils.DEFAULT_IS_TCP_ONLY : node.getTcpOnly();
285         final BigDecimal sleepFactor = node.getSleepFactor() == null
286                 ? NetconfTopologyUtils.DEFAULT_SLEEP_FACTOR : node.getSleepFactor();
287
288         final InetSocketAddress socketAddress = getSocketAddress(node.getHost(), node.getPort().getValue().toJava());
289
290         final ReconnectStrategyFactory sf =
291                 new TimedReconnectStrategyFactory(netconfTopologyDeviceSetup.getEventExecutor(), maxConnectionAttempts,
292                         betweenAttemptsTimeoutMillis, sleepFactor);
293
294
295         final NetconfReconnectingClientConfigurationBuilder reconnectingClientConfigurationBuilder;
296         final Protocol protocol = node.getProtocol();
297         if (isTcpOnly) {
298             reconnectingClientConfigurationBuilder = NetconfReconnectingClientConfigurationBuilder.create()
299                     .withProtocol(NetconfClientConfiguration.NetconfClientProtocol.TCP)
300                     .withAuthHandler(getHandlerFromCredentials(node.getCredentials()));
301         } else if (protocol == null || protocol.getName() == Protocol.Name.SSH) {
302             reconnectingClientConfigurationBuilder = NetconfReconnectingClientConfigurationBuilder.create()
303                     .withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH)
304                     .withAuthHandler(getHandlerFromCredentials(node.getCredentials()));
305         } else if (protocol.getName() == Protocol.Name.TLS) {
306             reconnectingClientConfigurationBuilder = NetconfReconnectingClientConfigurationBuilder.create()
307                     .withSslHandlerFactory(new SslHandlerFactoryImpl(keystoreAdapter, protocol.getSpecification()))
308                     .withProtocol(NetconfClientConfiguration.NetconfClientProtocol.TLS);
309         } else {
310             throw new IllegalStateException("Unsupported protocol type: " + protocol.getName());
311         }
312
313         final List<Uri> odlHelloCapabilities = getOdlHelloCapabilities(node);
314         if (odlHelloCapabilities != null) {
315             reconnectingClientConfigurationBuilder.withOdlHelloCapabilities(odlHelloCapabilities);
316         }
317
318         return reconnectingClientConfigurationBuilder
319                 .withAddress(socketAddress)
320                 .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
321                 .withReconnectStrategy(sf.createReconnectStrategy())
322                 .withConnectStrategyFactory(sf)
323                 .withSessionListener(listener)
324                 .build();
325     }
326
327     private static List<Uri> getOdlHelloCapabilities(final NetconfNode node) {
328         final OdlHelloMessageCapabilities helloCapabilities = node.getOdlHelloMessageCapabilities();
329         return helloCapabilities != null ? helloCapabilities.getCapability() : null;
330     }
331
332     private AuthenticationHandler getHandlerFromCredentials(final Credentials credentials) {
333         if (credentials instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology
334                 .rev150114.netconf.node.credentials.credentials.LoginPassword) {
335             final org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology
336                     .rev150114.netconf.node.credentials.credentials.LoginPassword loginPassword
337                     = (org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology
338                     .rev150114.netconf.node.credentials.credentials.LoginPassword) credentials;
339             return new LoginPasswordHandler(loginPassword.getUsername(), loginPassword.getPassword());
340         }
341         if (credentials instanceof LoginPwUnencrypted) {
342             final LoginPasswordUnencrypted loginPassword =
343                     ((LoginPwUnencrypted) credentials).getLoginPasswordUnencrypted();
344             return new LoginPasswordHandler(loginPassword.getUsername(), loginPassword.getPassword());
345         }
346         if (credentials instanceof LoginPw) {
347             final LoginPassword loginPassword = ((LoginPw) credentials).getLoginPassword();
348             return new LoginPasswordHandler(loginPassword.getUsername(),
349                     encryptionService.decrypt(loginPassword.getPassword()));
350         }
351         if (credentials instanceof KeyAuth) {
352             final KeyBased keyPair = ((KeyAuth) credentials).getKeyBased();
353             return new DatastoreBackedPublicKeyAuth(keyPair.getUsername(), keyPair.getKeyId(),
354                     keystoreAdapter, encryptionService);
355         }
356         throw new IllegalStateException("Unsupported credential type: " + credentials.getClass());
357     }
358 }