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