Merge "BUG-9048 Fix actor crash when writing incorrect data"
[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.PublicKeyAuth;
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.listener.NetconfDeviceCapabilities;
46 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
47 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
48 import org.opendaylight.netconf.sal.connect.netconf.listener.UserPreferences;
49 import org.opendaylight.netconf.sal.connect.netconf.sal.KeepaliveSalFacade;
50 import org.opendaylight.netconf.sal.connect.netconf.schema.YangLibrarySchemaYangSourceProvider;
51 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
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.protocol.framework.ReconnectStrategy;
57 import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
58 import org.opendaylight.protocol.framework.TimedReconnectStrategy;
59 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
60 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
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.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
65 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
66 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
67 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
68 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
71
72 public class RemoteDeviceConnectorImpl implements RemoteDeviceConnector {
73
74     private static final Logger LOG = LoggerFactory.getLogger(RemoteDeviceConnectorImpl.class);
75
76     // Initializes default constant instances for the case when the default schema repository
77     // directory cache/schema is used.
78
79     private final NetconfTopologySetup netconfTopologyDeviceSetup;
80     private final RemoteDeviceId remoteDeviceId;
81     private final DOMMountPointService mountService;
82     private final Timeout actorResponseWaitTime;
83     private final String privateKeyPath;
84     private final String privateKeyPassphrase;
85     private final AAAEncryptionService encryptionService;
86     private NetconfConnectorDTO deviceCommunicatorDTO;
87
88     public RemoteDeviceConnectorImpl(final NetconfTopologySetup netconfTopologyDeviceSetup,
89                                      final RemoteDeviceId remoteDeviceId, final Timeout actorResponseWaitTime,
90                                      final DOMMountPointService mountService) {
91
92         this.netconfTopologyDeviceSetup = Preconditions.checkNotNull(netconfTopologyDeviceSetup);
93         this.remoteDeviceId = remoteDeviceId;
94         this.actorResponseWaitTime = actorResponseWaitTime;
95         this.mountService = mountService;
96         this.privateKeyPath = netconfTopologyDeviceSetup.getPrivateKeyPath();
97         this.privateKeyPassphrase = netconfTopologyDeviceSetup.getPrivateKeyPassphrase();
98         this.encryptionService = netconfTopologyDeviceSetup.getEncryptionService();
99     }
100
101     @Override
102     public void startRemoteDeviceConnection(final ActorRef deviceContextActorRef) {
103
104         final NetconfNode netconfNode = netconfTopologyDeviceSetup.getNode().getAugmentation(NetconfNode.class);
105         final NodeId nodeId = netconfTopologyDeviceSetup.getNode().getNodeId();
106         Preconditions.checkNotNull(netconfNode.getHost());
107         Preconditions.checkNotNull(netconfNode.getPort());
108         Preconditions.checkNotNull(netconfNode.isTcpOnly());
109
110         this.deviceCommunicatorDTO = createDeviceCommunicator(nodeId, netconfNode, deviceContextActorRef);
111         final NetconfDeviceCommunicator deviceCommunicator = deviceCommunicatorDTO.getCommunicator();
112         final NetconfClientSessionListener netconfClientSessionListener = deviceCommunicatorDTO.getSessionListener();
113         final NetconfReconnectingClientConfiguration clientConfig =
114                 getClientConfig(netconfClientSessionListener, netconfNode);
115         final ListenableFuture<NetconfDeviceCapabilities> future = deviceCommunicator
116                 .initializeRemoteConnection(netconfTopologyDeviceSetup.getNetconfClientDispatcher(), clientConfig);
117
118         Futures.addCallback(future, new FutureCallback<NetconfDeviceCapabilities>() {
119             @Override
120             public void onSuccess(final NetconfDeviceCapabilities result) {
121                 LOG.debug("{}: Connector started successfully", remoteDeviceId);
122             }
123
124             @Override
125             public void onFailure(@Nullable final Throwable throwable) {
126                 LOG.error("{}: Connector failed, {}", remoteDeviceId, throwable);
127             }
128         }, MoreExecutors.directExecutor());
129     }
130
131     @SuppressWarnings("checkstyle:IllegalCatch")
132     @Override
133     public void stopRemoteDeviceConnection() {
134         Preconditions.checkNotNull(deviceCommunicatorDTO, remoteDeviceId + ": Device communicator was not created.");
135         try {
136             deviceCommunicatorDTO.close();
137         } catch (final Exception e) {
138             LOG.error("{}: Error at closing device communicator.", remoteDeviceId, e);
139         }
140     }
141
142     @VisibleForTesting
143     NetconfConnectorDTO createDeviceCommunicator(final NodeId nodeId, final NetconfNode node,
144                                                  final ActorRef deviceContextActorRef) {
145         //setup default values since default value is not supported in mdsal
146         final Long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null
147                 ? NetconfTopologyUtils.DEFAULT_REQUEST_TIMEOUT_MILLIS : node.getDefaultRequestTimeoutMillis();
148         final Long keepaliveDelay = node.getKeepaliveDelay() == null
149                 ? NetconfTopologyUtils.DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay();
150         final Boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null
151                 ? NetconfTopologyUtils.DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.isReconnectOnChangedSchema();
152
153         RemoteDeviceHandler<NetconfSessionPreferences> salFacade = new MasterSalFacade(remoteDeviceId,
154                 netconfTopologyDeviceSetup.getActorSystem(), deviceContextActorRef, actorResponseWaitTime,
155                 mountService, netconfTopologyDeviceSetup.getDataBroker());
156         if (keepaliveDelay > 0) {
157             LOG.info("{}: Adding keepalive facade.", remoteDeviceId);
158             salFacade = new KeepaliveSalFacade(remoteDeviceId, salFacade,
159                     netconfTopologyDeviceSetup.getKeepaliveExecutor().getExecutor(), keepaliveDelay,
160                     defaultRequestTimeoutMillis);
161         }
162
163         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = netconfTopologyDeviceSetup.getSchemaResourcesDTO();
164
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().getExecutor())
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         return new NetconfConnectorDTO(
217                 userCapabilities.isPresent() ? new NetconfDeviceCommunicator(remoteDeviceId, device,
218                         new UserPreferences(userCapabilities.get(),
219                                 Objects.isNull(node.getYangModuleCapabilities())
220                                         ? false : node.getYangModuleCapabilities().isOverride(),
221                                 Objects.isNull(node.getNonModuleCapabilities())
222                                         ? false : node.getNonModuleCapabilities().isOverride()), rpcMessageLimit)
223                         : new NetconfDeviceCommunicator(remoteDeviceId, device, rpcMessageLimit), salFacade);
224     }
225
226     private Optional<NetconfSessionPreferences> getUserCapabilities(final NetconfNode node) {
227         if (node.getYangModuleCapabilities() == null && node.getNonModuleCapabilities() == null) {
228             return Optional.empty();
229         }
230         final List<String> capabilities = new ArrayList<>();
231
232         if (node.getYangModuleCapabilities() != null) {
233             capabilities.addAll(node.getYangModuleCapabilities().getCapability());
234         }
235
236         //non-module capabilities should not exist in yang module capabilities
237         final NetconfSessionPreferences netconfSessionPreferences = NetconfSessionPreferences.fromStrings(capabilities);
238         Preconditions.checkState(netconfSessionPreferences.getNonModuleCaps().isEmpty(),
239                 "List yang-module-capabilities/capability should contain only module based capabilities. "
240                         + "Non-module capabilities used: " + netconfSessionPreferences.getNonModuleCaps());
241
242         if (node.getNonModuleCapabilities() != null) {
243             capabilities.addAll(node.getNonModuleCapabilities().getCapability());
244         }
245
246         return Optional.of(NetconfSessionPreferences.fromStrings(capabilities, CapabilityOrigin.UserDefined));
247     }
248
249     //TODO: duplicate code
250     private InetSocketAddress getSocketAddress(final Host host, final int port) {
251         if (host.getDomainName() != null) {
252             return new InetSocketAddress(host.getDomainName().getValue(), port);
253         } else {
254             final IpAddress ipAddress = host.getIpAddress();
255             final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() :
256                     ipAddress.getIpv6Address().getValue();
257             return new InetSocketAddress(ip, port);
258         }
259     }
260
261     @VisibleForTesting
262     NetconfReconnectingClientConfiguration getClientConfig(final NetconfClientSessionListener listener,
263                                                            final NetconfNode node) {
264
265         //setup default values since default value is not supported in mdsal
266         final long clientConnectionTimeoutMillis = node.getConnectionTimeoutMillis() == null
267                 ? NetconfTopologyUtils.DEFAULT_CONNECTION_TIMEOUT_MILLIS : node.getConnectionTimeoutMillis();
268         final long maxConnectionAttempts = node.getMaxConnectionAttempts() == null
269                 ? NetconfTopologyUtils.DEFAULT_MAX_CONNECTION_ATTEMPTS : node.getMaxConnectionAttempts();
270         final int betweenAttemptsTimeoutMillis = node.getBetweenAttemptsTimeoutMillis() == null
271                 ? NetconfTopologyUtils.DEFAULT_BETWEEN_ATTEMPTS_TIMEOUT_MILLIS : node.getBetweenAttemptsTimeoutMillis();
272         final BigDecimal sleepFactor = node.getSleepFactor() == null
273                 ? NetconfTopologyUtils.DEFAULT_SLEEP_FACTOR : node.getSleepFactor();
274
275         final InetSocketAddress socketAddress = getSocketAddress(node.getHost(), node.getPort().getValue());
276
277         final ReconnectStrategyFactory sf =
278                 new TimedReconnectStrategyFactory(netconfTopologyDeviceSetup.getEventExecutor(), maxConnectionAttempts,
279                         betweenAttemptsTimeoutMillis, sleepFactor);
280         final ReconnectStrategy strategy = sf.createReconnectStrategy();
281
282         final AuthenticationHandler authHandler;
283         final Credentials credentials = node.getCredentials();
284         if (credentials instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf
285                 .node.credentials.credentials.LoginPassword) {
286             authHandler = new PublicKeyAuth(
287                     ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf
288                             .node.credentials.credentials.LoginPassword) credentials).getUsername(),
289                     ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf
290                             .node.credentials.credentials.LoginPassword) credentials).getPassword(),
291                     this.privateKeyPath, this.privateKeyPassphrase, encryptionService);
292
293         } else {
294             throw new IllegalStateException(remoteDeviceId + ": Only login/password authentication is supported");
295         }
296
297         return NetconfReconnectingClientConfigurationBuilder.create()
298                 .withAddress(socketAddress)
299                 .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
300                 .withReconnectStrategy(strategy)
301                 .withAuthHandler(authHandler)
302                 .withProtocol(node.isTcpOnly()
303                         ? NetconfClientConfiguration.NetconfClientProtocol.TCP
304                         : NetconfClientConfiguration.NetconfClientProtocol.SSH)
305                 .withConnectStrategyFactory(sf)
306                 .withSessionListener(listener)
307                 .build();
308     }
309
310     private static final class TimedReconnectStrategyFactory implements ReconnectStrategyFactory {
311         private final Long connectionAttempts;
312         private final EventExecutor executor;
313         private final double sleepFactor;
314         private final int minSleep;
315
316         TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts,
317                                       final int minSleep, final BigDecimal sleepFactor) {
318             if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
319                 connectionAttempts = maxConnectionAttempts;
320             } else {
321                 connectionAttempts = null;
322             }
323
324             this.sleepFactor = sleepFactor.doubleValue();
325             this.executor = executor;
326             this.minSleep = minSleep;
327         }
328
329         @Override
330         public ReconnectStrategy createReconnectStrategy() {
331             final Long maxSleep = null;
332             final Long deadline = null;
333
334             return new TimedReconnectStrategy(executor, minSleep,
335                     minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
336         }
337     }
338 }