Convert to using requireNonNull()
[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.collect.Lists;
15 import com.google.common.util.concurrent.FutureCallback;
16 import com.google.common.util.concurrent.Futures;
17 import com.google.common.util.concurrent.ListenableFuture;
18 import com.google.common.util.concurrent.MoreExecutors;
19 import java.math.BigDecimal;
20 import java.net.InetSocketAddress;
21 import java.net.URL;
22 import java.util.ArrayList;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Optional;
26 import org.opendaylight.aaa.encrypt.AAAEncryptionService;
27 import org.opendaylight.netconf.api.NetconfMessage;
28 import org.opendaylight.netconf.client.NetconfClientSessionListener;
29 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
30 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration;
31 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder;
32 import org.opendaylight.netconf.nettyutil.ReconnectStrategyFactory;
33 import org.opendaylight.netconf.nettyutil.TimedReconnectStrategyFactory;
34 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
35 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.LoginPasswordHandler;
36 import org.opendaylight.netconf.sal.connect.api.DeviceActionFactory;
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 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         this.privateKeyPath = netconfTopologyDeviceSetup.getPrivateKeyPath();
104         this.privateKeyPassphrase = netconfTopologyDeviceSetup.getPrivateKeyPassphrase();
105         this.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         this.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();
156         final long keepaliveDelay = node.getKeepaliveDelay() == null
157                 ? NetconfTopologyUtils.DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay();
158         final boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null
159                 ? NetconfTopologyUtils.DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.isReconnectOnChangedSchema();
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         // FIXME: this list not used anywhere. Should it be retained or discarded? (why?)
173         //        it would seem those registrations should be bound to NetconfConnectorDTO
174         final List<SchemaSourceRegistration<YangTextSchemaSource>> registeredYangLibSources = Lists.newArrayList();
175         if (node.getYangLibrary() != null) {
176             final String yangLibURL = node.getYangLibrary().getYangLibraryUrl().getValue();
177             final String yangLibUsername = node.getYangLibrary().getUsername();
178             final String yangLigPassword = node.getYangLibrary().getPassword();
179
180             final LibraryModulesSchemas libraryModulesSchemas;
181             if (yangLibURL != null) {
182                 if (yangLibUsername != null && yangLigPassword != null) {
183                     libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL, yangLibUsername, yangLigPassword);
184                 } else {
185                     libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL);
186                 }
187
188                 for (final Map.Entry<SourceIdentifier, URL> sourceIdentifierURLEntry :
189                         libraryModulesSchemas.getAvailableModels().entrySet()) {
190                     registeredYangLibSources
191                             .add(schemaResourcesDTO.getSchemaRegistry().registerSchemaSource(
192                                     new YangLibrarySchemaYangSourceProvider(remoteDeviceId,
193                                             libraryModulesSchemas.getAvailableModels()),
194                                     PotentialSchemaSource
195                                             .create(sourceIdentifierURLEntry.getKey(), YangTextSchemaSource.class,
196                                                     PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
197                 }
198             }
199         }
200
201         final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> device;
202         if (node.isSchemaless()) {
203             device = new SchemalessNetconfDevice(remoteDeviceId, salFacade);
204         } else {
205             device = new NetconfDeviceBuilder()
206                     .setReconnectOnSchemasChange(reconnectOnChangedSchema)
207                     .setSchemaResourcesDTO(schemaResourcesDTO)
208                     .setGlobalProcessingExecutor(netconfTopologyDeviceSetup.getProcessingExecutor())
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();
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 =
225              userCapabilities.isPresent() ? new NetconfDeviceCommunicator(remoteDeviceId, device,
226              new UserPreferences(userCapabilities.get(),
227                  node.getYangModuleCapabilities() == null ? false : node.getYangModuleCapabilities().isOverride(),
228                  node.getNonModuleCapabilities() == null ? false : node.getNonModuleCapabilities().isOverride()),
229              rpcMessageLimit)
230             : new NetconfDeviceCommunicator(remoteDeviceId, device, rpcMessageLimit);
231
232         if (salFacade instanceof KeepaliveSalFacade) {
233             ((KeepaliveSalFacade)salFacade).setListener(netconfDeviceCommunicator);
234         }
235         return new NetconfConnectorDTO(netconfDeviceCommunicator, salFacade);
236     }
237
238     private static Optional<NetconfSessionPreferences> getUserCapabilities(final NetconfNode node) {
239         if (node.getYangModuleCapabilities() == null && node.getNonModuleCapabilities() == null) {
240             return Optional.empty();
241         }
242         final List<String> capabilities = new ArrayList<>();
243
244         if (node.getYangModuleCapabilities() != null) {
245             capabilities.addAll(node.getYangModuleCapabilities().getCapability());
246         }
247
248         //non-module capabilities should not exist in yang module capabilities
249         final NetconfSessionPreferences netconfSessionPreferences = NetconfSessionPreferences.fromStrings(capabilities);
250         checkState(netconfSessionPreferences.getNonModuleCaps().isEmpty(),
251                 "List yang-module-capabilities/capability should contain only module based capabilities. "
252                         + "Non-module capabilities used: " + netconfSessionPreferences.getNonModuleCaps());
253
254         if (node.getNonModuleCapabilities() != null) {
255             capabilities.addAll(node.getNonModuleCapabilities().getCapability());
256         }
257
258         return Optional.of(NetconfSessionPreferences.fromStrings(capabilities, CapabilityOrigin.UserDefined));
259     }
260
261     //TODO: duplicate code
262     private static InetSocketAddress getSocketAddress(final Host host, final int port) {
263         if (host.getDomainName() != null) {
264             return new InetSocketAddress(host.getDomainName().getValue(), port);
265         } else {
266             final IpAddress ipAddress = host.getIpAddress();
267             final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() :
268                     ipAddress.getIpv6Address().getValue();
269             return new InetSocketAddress(ip, port);
270         }
271     }
272
273     @VisibleForTesting
274     NetconfReconnectingClientConfiguration getClientConfig(final NetconfClientSessionListener listener,
275                                                            final NetconfNode node) {
276
277         //setup default values since default value is not supported in mdsal
278         final long clientConnectionTimeoutMillis = node.getConnectionTimeoutMillis() == null
279                 ? NetconfTopologyUtils.DEFAULT_CONNECTION_TIMEOUT_MILLIS : node.getConnectionTimeoutMillis();
280         final long maxConnectionAttempts = node.getMaxConnectionAttempts() == null
281                 ? NetconfTopologyUtils.DEFAULT_MAX_CONNECTION_ATTEMPTS : node.getMaxConnectionAttempts();
282         final int betweenAttemptsTimeoutMillis = node.getBetweenAttemptsTimeoutMillis() == null
283                 ? NetconfTopologyUtils.DEFAULT_BETWEEN_ATTEMPTS_TIMEOUT_MILLIS : node.getBetweenAttemptsTimeoutMillis();
284         final boolean isTcpOnly = node.isTcpOnly() == null
285                 ? NetconfTopologyUtils.DEFAULT_IS_TCP_ONLY : node.isTcpOnly();
286         final BigDecimal sleepFactor = node.getSleepFactor() == null
287                 ? NetconfTopologyUtils.DEFAULT_SLEEP_FACTOR : node.getSleepFactor();
288
289         final InetSocketAddress socketAddress = getSocketAddress(node.getHost(), node.getPort().getValue());
290
291         final ReconnectStrategyFactory sf =
292                 new TimedReconnectStrategyFactory(netconfTopologyDeviceSetup.getEventExecutor(), maxConnectionAttempts,
293                         betweenAttemptsTimeoutMillis, sleepFactor);
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 ? 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 }