Merge "Fix findbugs violations in netconf"
[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 akka.actor.ActorRef;
12 import akka.util.Timeout;
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.base.Preconditions;
15 import com.google.common.collect.Lists;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.MoreExecutors;
20 import io.netty.util.concurrent.EventExecutor;
21 import java.math.BigDecimal;
22 import java.net.InetSocketAddress;
23 import java.net.URL;
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Objects;
28 import java.util.Optional;
29 import javax.annotation.Nullable;
30 import org.opendaylight.aaa.encrypt.AAAEncryptionService;
31 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
32 import org.opendaylight.netconf.api.NetconfMessage;
33 import org.opendaylight.netconf.client.NetconfClientSessionListener;
34 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
35 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration;
36 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder;
37 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
38 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.LoginPasswordHandler;
39 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
40 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
41 import org.opendaylight.netconf.sal.connect.netconf.LibraryModulesSchemas;
42 import org.opendaylight.netconf.sal.connect.netconf.NetconfDevice;
43 import org.opendaylight.netconf.sal.connect.netconf.NetconfDeviceBuilder;
44 import org.opendaylight.netconf.sal.connect.netconf.SchemalessNetconfDevice;
45 import org.opendaylight.netconf.sal.connect.netconf.auth.DatastoreBackedPublicKeyAuth;
46 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
47 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
48 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
49 import org.opendaylight.netconf.sal.connect.netconf.listener.UserPreferences;
50 import org.opendaylight.netconf.sal.connect.netconf.sal.KeepaliveSalFacade;
51 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfKeystoreAdapter;
52 import org.opendaylight.netconf.sal.connect.netconf.schema.YangLibrarySchemaYangSourceProvider;
53 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
54 import org.opendaylight.netconf.topology.singleton.api.RemoteDeviceConnector;
55 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfConnectorDTO;
56 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
57 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
58 import org.opendaylight.protocol.framework.ReconnectStrategy;
59 import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
60 import org.opendaylight.protocol.framework.TimedReconnectStrategy;
61 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
62 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapability.CapabilityOrigin;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.Credentials;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.KeyAuth;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPw;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPwUnencrypted;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.key.auth.KeyBased;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.login.pw.LoginPassword;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.login.pw.unencrypted.LoginPasswordUnencrypted;
72 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
73 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
74 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
75 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
76 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
79
80 public class RemoteDeviceConnectorImpl implements RemoteDeviceConnector {
81
82     private static final Logger LOG = LoggerFactory.getLogger(RemoteDeviceConnectorImpl.class);
83
84     // Initializes default constant instances for the case when the default schema repository
85     // directory cache/schema is used.
86
87     private final NetconfTopologySetup netconfTopologyDeviceSetup;
88     private final RemoteDeviceId remoteDeviceId;
89     private final DOMMountPointService mountService;
90     private final Timeout actorResponseWaitTime;
91     private final String privateKeyPath;
92     private final String privateKeyPassphrase;
93     private final AAAEncryptionService encryptionService;
94     private NetconfConnectorDTO deviceCommunicatorDTO;
95     private final NetconfKeystoreAdapter keystoreAdapter;
96
97     public RemoteDeviceConnectorImpl(final NetconfTopologySetup netconfTopologyDeviceSetup,
98                                      final RemoteDeviceId remoteDeviceId, final Timeout actorResponseWaitTime,
99                                      final DOMMountPointService mountService) {
100
101         this.netconfTopologyDeviceSetup = Preconditions.checkNotNull(netconfTopologyDeviceSetup);
102         this.remoteDeviceId = remoteDeviceId;
103         this.actorResponseWaitTime = actorResponseWaitTime;
104         this.mountService = mountService;
105         this.privateKeyPath = netconfTopologyDeviceSetup.getPrivateKeyPath();
106         this.privateKeyPassphrase = netconfTopologyDeviceSetup.getPrivateKeyPassphrase();
107         this.encryptionService = netconfTopologyDeviceSetup.getEncryptionService();
108         keystoreAdapter = new NetconfKeystoreAdapter(netconfTopologyDeviceSetup.getDataBroker());
109     }
110
111     @Override
112     public void startRemoteDeviceConnection(final ActorRef deviceContextActorRef) {
113
114         final NetconfNode netconfNode = netconfTopologyDeviceSetup.getNode().getAugmentation(NetconfNode.class);
115         final NodeId nodeId = netconfTopologyDeviceSetup.getNode().getNodeId();
116         Preconditions.checkNotNull(netconfNode.getHost());
117         Preconditions.checkNotNull(netconfNode.getPort());
118         Preconditions.checkNotNull(netconfNode.isTcpOnly());
119
120         this.deviceCommunicatorDTO = createDeviceCommunicator(nodeId, netconfNode, deviceContextActorRef);
121         final NetconfDeviceCommunicator deviceCommunicator = deviceCommunicatorDTO.getCommunicator();
122         final NetconfClientSessionListener netconfClientSessionListener = deviceCommunicatorDTO.getSessionListener();
123         final NetconfReconnectingClientConfiguration clientConfig =
124                 getClientConfig(netconfClientSessionListener, netconfNode);
125         final ListenableFuture<NetconfDeviceCapabilities> future = deviceCommunicator
126                 .initializeRemoteConnection(netconfTopologyDeviceSetup.getNetconfClientDispatcher(), clientConfig);
127
128         Futures.addCallback(future, new FutureCallback<NetconfDeviceCapabilities>() {
129             @Override
130             public void onSuccess(final NetconfDeviceCapabilities result) {
131                 LOG.debug("{}: Connector started successfully", remoteDeviceId);
132             }
133
134             @Override
135             public void onFailure(@Nullable final Throwable throwable) {
136                 LOG.error("{}: Connector failed, {}", remoteDeviceId, throwable);
137             }
138         }, MoreExecutors.directExecutor());
139     }
140
141     @SuppressWarnings("checkstyle:IllegalCatch")
142     @Override
143     public void stopRemoteDeviceConnection() {
144         Preconditions.checkNotNull(deviceCommunicatorDTO, remoteDeviceId + ": Device communicator was not created.");
145         try {
146             deviceCommunicatorDTO.close();
147         } catch (final Exception e) {
148             LOG.error("{}: Error at closing device communicator.", remoteDeviceId, e);
149         }
150     }
151
152     @VisibleForTesting
153     NetconfConnectorDTO createDeviceCommunicator(final NodeId nodeId, final NetconfNode node,
154                                                  final ActorRef deviceContextActorRef) {
155         //setup default values since default value is not supported in mdsal
156         final long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null
157                 ? NetconfTopologyUtils.DEFAULT_REQUEST_TIMEOUT_MILLIS : node.getDefaultRequestTimeoutMillis();
158         final long keepaliveDelay = node.getKeepaliveDelay() == null
159                 ? NetconfTopologyUtils.DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay();
160         final boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null
161                 ? NetconfTopologyUtils.DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.isReconnectOnChangedSchema();
162
163         RemoteDeviceHandler<NetconfSessionPreferences> salFacade = new MasterSalFacade(remoteDeviceId,
164                 netconfTopologyDeviceSetup.getActorSystem(), deviceContextActorRef, actorResponseWaitTime,
165                 mountService, netconfTopologyDeviceSetup.getDataBroker());
166         if (keepaliveDelay > 0) {
167             LOG.info("{}: Adding keepalive facade.", remoteDeviceId);
168             salFacade = new KeepaliveSalFacade(remoteDeviceId, salFacade,
169                     netconfTopologyDeviceSetup.getKeepaliveExecutor().getExecutor(), keepaliveDelay,
170                     defaultRequestTimeoutMillis);
171         }
172
173         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = netconfTopologyDeviceSetup.getSchemaResourcesDTO();
174
175
176         // pre register yang library sources as fallback schemas to schema registry
177         final List<SchemaSourceRegistration<YangTextSchemaSource>> registeredYangLibSources = Lists.newArrayList();
178         if (node.getYangLibrary() != null) {
179             final String yangLibURL = node.getYangLibrary().getYangLibraryUrl().getValue();
180             final String yangLibUsername = node.getYangLibrary().getUsername();
181             final String yangLigPassword = node.getYangLibrary().getPassword();
182
183             final LibraryModulesSchemas libraryModulesSchemas;
184             if (yangLibURL != null) {
185                 if (yangLibUsername != null && yangLigPassword != null) {
186                     libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL, yangLibUsername, yangLigPassword);
187                 } else {
188                     libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL);
189                 }
190
191                 for (final Map.Entry<SourceIdentifier, URL> sourceIdentifierURLEntry :
192                         libraryModulesSchemas.getAvailableModels().entrySet()) {
193                     registeredYangLibSources
194                             .add(schemaResourcesDTO.getSchemaRegistry().registerSchemaSource(
195                                     new YangLibrarySchemaYangSourceProvider(remoteDeviceId,
196                                             libraryModulesSchemas.getAvailableModels()),
197                                     PotentialSchemaSource
198                                             .create(sourceIdentifierURLEntry.getKey(), YangTextSchemaSource.class,
199                                                     PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
200                 }
201             }
202         }
203
204         final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> device;
205         if (node.isSchemaless()) {
206             device = new SchemalessNetconfDevice(remoteDeviceId, salFacade);
207         } else {
208             device = new NetconfDeviceBuilder()
209                     .setReconnectOnSchemasChange(reconnectOnChangedSchema)
210                     .setSchemaResourcesDTO(schemaResourcesDTO)
211                     .setGlobalProcessingExecutor(netconfTopologyDeviceSetup.getProcessingExecutor().getExecutor())
212                     .setId(remoteDeviceId)
213                     .setSalFacade(salFacade)
214                     .build();
215         }
216
217         final Optional<NetconfSessionPreferences> userCapabilities = getUserCapabilities(node);
218         final int rpcMessageLimit =
219                 node.getConcurrentRpcLimit() == null
220                         ? NetconfTopologyUtils.DEFAULT_CONCURRENT_RPC_LIMIT : node.getConcurrentRpcLimit();
221
222         if (rpcMessageLimit < 1) {
223             LOG.info("{}: Concurrent rpc limit is smaller than 1, no limit will be enforced.", remoteDeviceId);
224         }
225
226         return new NetconfConnectorDTO(
227                 userCapabilities.isPresent() ? new NetconfDeviceCommunicator(remoteDeviceId, device,
228                         new UserPreferences(userCapabilities.get(),
229                                 Objects.isNull(node.getYangModuleCapabilities())
230                                         ? false : node.getYangModuleCapabilities().isOverride(),
231                                 Objects.isNull(node.getNonModuleCapabilities())
232                                         ? false : node.getNonModuleCapabilities().isOverride()), rpcMessageLimit)
233                         : new NetconfDeviceCommunicator(remoteDeviceId, device, rpcMessageLimit), salFacade);
234     }
235
236     private 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         Preconditions.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 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();
278         final long maxConnectionAttempts = node.getMaxConnectionAttempts() == null
279                 ? NetconfTopologyUtils.DEFAULT_MAX_CONNECTION_ATTEMPTS : node.getMaxConnectionAttempts();
280         final int betweenAttemptsTimeoutMillis = node.getBetweenAttemptsTimeoutMillis() == null
281                 ? NetconfTopologyUtils.DEFAULT_BETWEEN_ATTEMPTS_TIMEOUT_MILLIS : node.getBetweenAttemptsTimeoutMillis();
282         final BigDecimal sleepFactor = node.getSleepFactor() == null
283                 ? NetconfTopologyUtils.DEFAULT_SLEEP_FACTOR : node.getSleepFactor();
284
285         final InetSocketAddress socketAddress = getSocketAddress(node.getHost(), node.getPort().getValue());
286
287         final ReconnectStrategyFactory sf =
288                 new TimedReconnectStrategyFactory(netconfTopologyDeviceSetup.getEventExecutor(), maxConnectionAttempts,
289                         betweenAttemptsTimeoutMillis, sleepFactor);
290         final ReconnectStrategy strategy = sf.createReconnectStrategy();
291
292         final AuthenticationHandler authHandler = getHandlerFromCredentials(node.getCredentials());
293
294         return NetconfReconnectingClientConfigurationBuilder.create()
295                 .withAddress(socketAddress)
296                 .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
297                 .withReconnectStrategy(strategy)
298                 .withAuthHandler(authHandler)
299                 .withProtocol(node.isTcpOnly()
300                         ? NetconfClientConfiguration.NetconfClientProtocol.TCP
301                         : NetconfClientConfiguration.NetconfClientProtocol.SSH)
302                 .withConnectStrategyFactory(sf)
303                 .withSessionListener(listener)
304                 .build();
305     }
306
307     private AuthenticationHandler getHandlerFromCredentials(final Credentials credentials) {
308         if (credentials instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology
309                 .rev150114.netconf.node.credentials.credentials.LoginPassword) {
310             final org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology
311                     .rev150114.netconf.node.credentials.credentials.LoginPassword loginPassword
312                     = (org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology
313                     .rev150114.netconf.node.credentials.credentials.LoginPassword) credentials;
314             return new LoginPasswordHandler(loginPassword.getUsername(), loginPassword.getPassword());
315         }
316         if (credentials instanceof LoginPwUnencrypted) {
317             final LoginPasswordUnencrypted loginPassword =
318                     ((LoginPwUnencrypted) credentials).getLoginPasswordUnencrypted();
319             return new LoginPasswordHandler(loginPassword.getUsername(), loginPassword.getPassword());
320         }
321         if (credentials instanceof LoginPw) {
322             final LoginPassword loginPassword = ((LoginPw) credentials).getLoginPassword();
323             return new LoginPasswordHandler(loginPassword.getUsername(),
324                     encryptionService.decrypt(loginPassword.getPassword()));
325         }
326         if (credentials instanceof KeyAuth) {
327             final KeyBased keyPair = ((KeyAuth) credentials).getKeyBased();
328             return new DatastoreBackedPublicKeyAuth(keyPair.getUsername(), keyPair.getKeyId(),
329                     keystoreAdapter, encryptionService);
330         }
331         throw new IllegalStateException("Unsupported credential type: " + credentials.getClass());
332     }
333
334     private static final class TimedReconnectStrategyFactory implements ReconnectStrategyFactory {
335         private final Long connectionAttempts;
336         private final EventExecutor executor;
337         private final double sleepFactor;
338         private final int minSleep;
339
340         TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts,
341                                       final int minSleep, final BigDecimal sleepFactor) {
342             if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
343                 connectionAttempts = maxConnectionAttempts;
344             } else {
345                 connectionAttempts = null;
346             }
347
348             this.sleepFactor = sleepFactor.doubleValue();
349             this.executor = executor;
350             this.minSleep = minSleep;
351         }
352
353         @Override
354         public ReconnectStrategy createReconnectStrategy() {
355             return new TimedReconnectStrategy(executor, minSleep,
356                     minSleep, sleepFactor, null /*maxSleep*/, connectionAttempts, null /*deadline*/);
357         }
358     }
359 }