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