57bd458bf514e1614ba6c2589f4d29b9aa384bd2
[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 io.netty.util.concurrent.EventExecutor;
20 import java.math.BigDecimal;
21 import java.net.InetSocketAddress;
22 import java.net.URL;
23 import java.util.ArrayList;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Objects;
27 import java.util.Optional;
28 import javax.annotation.Nullable;
29 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
30 import org.opendaylight.netconf.api.NetconfMessage;
31 import org.opendaylight.netconf.client.NetconfClientSessionListener;
32 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
33 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration;
34 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder;
35 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
36 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.PublicKeyAuth;
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.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.schema.YangLibrarySchemaYangSourceProvider;
49 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
50 import org.opendaylight.netconf.topology.singleton.api.RemoteDeviceConnector;
51 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfConnectorDTO;
52 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
53 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
54 import org.opendaylight.protocol.framework.ReconnectStrategy;
55 import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
56 import org.opendaylight.protocol.framework.TimedReconnectStrategy;
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.opendaylight.netconf.node.topology.rev150114.NetconfNode;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapability.CapabilityOrigin;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.Credentials;
62 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
63 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
64 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
65 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
66 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
69
70 public class RemoteDeviceConnectorImpl implements RemoteDeviceConnector {
71
72     private static final Logger LOG = LoggerFactory.getLogger(RemoteDeviceConnectorImpl.class);
73
74     // Initializes default constant instances for the case when the default schema repository
75     // directory cache/schema is used.
76
77     private final NetconfTopologySetup netconfTopologyDeviceSetup;
78     private final RemoteDeviceId remoteDeviceId;
79     private final DOMMountPointService mountService;
80     private final Timeout actorResponseWaitTime;
81     private final String privateKeyPath;
82     private final String privateKeyPassphrase;
83
84     private NetconfConnectorDTO deviceCommunicatorDTO;
85
86     public RemoteDeviceConnectorImpl(final NetconfTopologySetup netconfTopologyDeviceSetup,
87                                      final RemoteDeviceId remoteDeviceId, final Timeout actorResponseWaitTime,
88                                      final DOMMountPointService mountService) {
89
90         this.netconfTopologyDeviceSetup = Preconditions.checkNotNull(netconfTopologyDeviceSetup);
91         this.remoteDeviceId = remoteDeviceId;
92         this.actorResponseWaitTime = actorResponseWaitTime;
93         this.mountService = mountService;
94         this.privateKeyPath = netconfTopologyDeviceSetup.getPrivateKeyPath();
95         this.privateKeyPassphrase = netconfTopologyDeviceSetup.getPrivateKeyPassphrase();
96     }
97
98     @Override
99     public void startRemoteDeviceConnection(final ActorRef deviceContextActorRef) {
100
101         final NetconfNode netconfNode = netconfTopologyDeviceSetup.getNode().getAugmentation(NetconfNode.class);
102         final NodeId nodeId = netconfTopologyDeviceSetup.getNode().getNodeId();
103         Preconditions.checkNotNull(netconfNode.getHost());
104         Preconditions.checkNotNull(netconfNode.getPort());
105         Preconditions.checkNotNull(netconfNode.isTcpOnly());
106
107         this.deviceCommunicatorDTO = createDeviceCommunicator(nodeId, netconfNode, deviceContextActorRef);
108         final NetconfDeviceCommunicator deviceCommunicator = deviceCommunicatorDTO.getCommunicator();
109         final NetconfClientSessionListener netconfClientSessionListener = deviceCommunicatorDTO.getSessionListener();
110         final NetconfReconnectingClientConfiguration clientConfig =
111                 getClientConfig(netconfClientSessionListener, netconfNode);
112         final ListenableFuture<NetconfDeviceCapabilities> future = deviceCommunicator
113                 .initializeRemoteConnection(netconfTopologyDeviceSetup.getNetconfClientDispatcher(), clientConfig);
114
115         Futures.addCallback(future, new FutureCallback<NetconfDeviceCapabilities>() {
116             @Override
117             public void onSuccess(final NetconfDeviceCapabilities result) {
118                 LOG.debug("{}: Connector started successfully", remoteDeviceId);
119             }
120
121             @Override
122             public void onFailure(@Nullable final Throwable throwable) {
123                 LOG.error("{}: Connector failed, {}", remoteDeviceId, throwable);
124             }
125         });
126     }
127
128     @SuppressWarnings("checkstyle:IllegalCatch")
129     @Override
130     public void stopRemoteDeviceConnection() {
131         Preconditions.checkNotNull(deviceCommunicatorDTO, remoteDeviceId + ": Device communicator was not created.");
132         try {
133             deviceCommunicatorDTO.close();
134         } catch (final Exception e) {
135             LOG.error("{}: Error at closing device communicator.", remoteDeviceId, e);
136         }
137     }
138
139     @VisibleForTesting
140     NetconfConnectorDTO createDeviceCommunicator(final NodeId nodeId, final NetconfNode node,
141                                                  final ActorRef deviceContextActorRef) {
142         //setup default values since default value is not supported in mdsal
143         final Long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null
144                 ? NetconfTopologyUtils.DEFAULT_REQUEST_TIMEOUT_MILLIS : node.getDefaultRequestTimeoutMillis();
145         final Long keepaliveDelay = node.getKeepaliveDelay() == null
146                 ? NetconfTopologyUtils.DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay();
147         final Boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null
148                 ? NetconfTopologyUtils.DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.isReconnectOnChangedSchema();
149
150         RemoteDeviceHandler<NetconfSessionPreferences> salFacade = new MasterSalFacade(remoteDeviceId,
151                 netconfTopologyDeviceSetup.getActorSystem(), deviceContextActorRef, actorResponseWaitTime,
152                 mountService, netconfTopologyDeviceSetup.getDataBroker());
153         if (keepaliveDelay > 0) {
154             LOG.info("{}: Adding keepalive facade.", remoteDeviceId);
155             salFacade = new KeepaliveSalFacade(remoteDeviceId, salFacade,
156                     netconfTopologyDeviceSetup.getKeepaliveExecutor().getExecutor(), keepaliveDelay,
157                     defaultRequestTimeoutMillis);
158         }
159
160         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = netconfTopologyDeviceSetup.getSchemaResourcesDTO();
161
162
163         // pre register yang library sources as fallback schemas to schema registry
164         final List<SchemaSourceRegistration<YangTextSchemaSource>> registeredYangLibSources = Lists.newArrayList();
165         if (node.getYangLibrary() != null) {
166             final String yangLibURL = node.getYangLibrary().getYangLibraryUrl().getValue();
167             final String yangLibUsername = node.getYangLibrary().getUsername();
168             final String yangLigPassword = node.getYangLibrary().getPassword();
169
170             final LibraryModulesSchemas libraryModulesSchemas;
171             if (yangLibURL != null) {
172                 if (yangLibUsername != null && yangLigPassword != null) {
173                     libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL, yangLibUsername, yangLigPassword);
174                 } else {
175                     libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL);
176                 }
177
178                 for (final Map.Entry<SourceIdentifier, URL> sourceIdentifierURLEntry :
179                         libraryModulesSchemas.getAvailableModels().entrySet()) {
180                     registeredYangLibSources
181                             .add(schemaResourcesDTO.getSchemaRegistry().registerSchemaSource(
182                                     new YangLibrarySchemaYangSourceProvider(remoteDeviceId,
183                                             libraryModulesSchemas.getAvailableModels()),
184                                     PotentialSchemaSource
185                                             .create(sourceIdentifierURLEntry.getKey(), YangTextSchemaSource.class,
186                                                     PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
187                 }
188             }
189         }
190
191         final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> device;
192         if (node.isSchemaless()) {
193             device = new SchemalessNetconfDevice(remoteDeviceId, salFacade);
194         } else {
195             device = new NetconfDeviceBuilder()
196                     .setReconnectOnSchemasChange(reconnectOnChangedSchema)
197                     .setSchemaResourcesDTO(schemaResourcesDTO)
198                     .setGlobalProcessingExecutor(netconfTopologyDeviceSetup.getProcessingExecutor().getExecutor())
199                     .setId(remoteDeviceId)
200                     .setSalFacade(salFacade)
201                     .build();
202         }
203
204         final Optional<NetconfSessionPreferences> userCapabilities = getUserCapabilities(node);
205         final int rpcMessageLimit =
206                 node.getConcurrentRpcLimit() == null
207                         ? NetconfTopologyUtils.DEFAULT_CONCURRENT_RPC_LIMIT : node.getConcurrentRpcLimit();
208
209         if (rpcMessageLimit < 1) {
210             LOG.info("{}: Concurrent rpc limit is smaller than 1, no limit will be enforced.", remoteDeviceId);
211         }
212
213         return new NetconfConnectorDTO(
214                 userCapabilities.isPresent() ? new NetconfDeviceCommunicator(remoteDeviceId, device,
215                         new UserPreferences(userCapabilities.get(),
216                                 Objects.isNull(node.getYangModuleCapabilities())
217                                         ? false : node.getYangModuleCapabilities().isOverride(),
218                                 Objects.isNull(node.getNonModuleCapabilities())
219                                         ? false : node.getNonModuleCapabilities().isOverride()), rpcMessageLimit)
220                         : new NetconfDeviceCommunicator(remoteDeviceId, device, rpcMessageLimit), salFacade);
221     }
222
223     private Optional<NetconfSessionPreferences> getUserCapabilities(final NetconfNode node) {
224         if (node.getYangModuleCapabilities() == null && node.getNonModuleCapabilities() == null) {
225             return Optional.empty();
226         }
227         final List<String> capabilities = new ArrayList<>();
228
229         if (node.getYangModuleCapabilities() != null) {
230             capabilities.addAll(node.getYangModuleCapabilities().getCapability());
231         }
232
233         //non-module capabilities should not exist in yang module capabilities
234         final NetconfSessionPreferences netconfSessionPreferences = NetconfSessionPreferences.fromStrings(capabilities);
235         Preconditions.checkState(netconfSessionPreferences.getNonModuleCaps().isEmpty(),
236                 "List yang-module-capabilities/capability should contain only module based capabilities. "
237                         + "Non-module capabilities used: " + netconfSessionPreferences.getNonModuleCaps());
238
239         if (node.getNonModuleCapabilities() != null) {
240             capabilities.addAll(node.getNonModuleCapabilities().getCapability());
241         }
242
243         return Optional.of(NetconfSessionPreferences.fromStrings(capabilities, CapabilityOrigin.UserDefined));
244     }
245
246     //TODO: duplicate code
247     private InetSocketAddress getSocketAddress(final Host host, final int port) {
248         if (host.getDomainName() != null) {
249             return new InetSocketAddress(host.getDomainName().getValue(), port);
250         } else {
251             final IpAddress ipAddress = host.getIpAddress();
252             final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() :
253                     ipAddress.getIpv6Address().getValue();
254             return new InetSocketAddress(ip, port);
255         }
256     }
257
258     @VisibleForTesting
259     NetconfReconnectingClientConfiguration getClientConfig(final NetconfClientSessionListener listener,
260                                                            final NetconfNode node) {
261
262         //setup default values since default value is not supported in mdsal
263         final long clientConnectionTimeoutMillis = node.getConnectionTimeoutMillis() == null
264                 ? NetconfTopologyUtils.DEFAULT_CONNECTION_TIMEOUT_MILLIS : node.getConnectionTimeoutMillis();
265         final long maxConnectionAttempts = node.getMaxConnectionAttempts() == null
266                 ? NetconfTopologyUtils.DEFAULT_MAX_CONNECTION_ATTEMPTS : node.getMaxConnectionAttempts();
267         final int betweenAttemptsTimeoutMillis = node.getBetweenAttemptsTimeoutMillis() == null
268                 ? NetconfTopologyUtils.DEFAULT_BETWEEN_ATTEMPTS_TIMEOUT_MILLIS : node.getBetweenAttemptsTimeoutMillis();
269         final BigDecimal sleepFactor = node.getSleepFactor() == null
270                 ? NetconfTopologyUtils.DEFAULT_SLEEP_FACTOR : node.getSleepFactor();
271
272         final InetSocketAddress socketAddress = getSocketAddress(node.getHost(), node.getPort().getValue());
273
274         final ReconnectStrategyFactory sf =
275                 new TimedReconnectStrategyFactory(netconfTopologyDeviceSetup.getEventExecutor(), maxConnectionAttempts,
276                         betweenAttemptsTimeoutMillis, sleepFactor);
277         final ReconnectStrategy strategy = sf.createReconnectStrategy();
278
279         final AuthenticationHandler authHandler;
280         final Credentials credentials = node.getCredentials();
281         if (credentials instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf
282                 .node.credentials.credentials.LoginPassword) {
283             authHandler = new PublicKeyAuth(
284                     ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf
285                             .node.credentials.credentials.LoginPassword) credentials).getUsername(),
286                     ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf
287                             .node.credentials.credentials.LoginPassword) credentials).getPassword(),
288                     this.privateKeyPath, this.privateKeyPassphrase);
289         } else {
290             throw new IllegalStateException(remoteDeviceId + ": Only login/password authentication is supported");
291         }
292
293         return NetconfReconnectingClientConfigurationBuilder.create()
294                 .withAddress(socketAddress)
295                 .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
296                 .withReconnectStrategy(strategy)
297                 .withAuthHandler(authHandler)
298                 .withProtocol(node.isTcpOnly()
299                         ? NetconfClientConfiguration.NetconfClientProtocol.TCP
300                         : NetconfClientConfiguration.NetconfClientProtocol.SSH)
301                 .withConnectStrategyFactory(sf)
302                 .withSessionListener(listener)
303                 .build();
304     }
305
306     private static final class TimedReconnectStrategyFactory implements ReconnectStrategyFactory {
307         private final Long connectionAttempts;
308         private final EventExecutor executor;
309         private final double sleepFactor;
310         private final int minSleep;
311
312         TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts,
313                                       final int minSleep, final BigDecimal sleepFactor) {
314             if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
315                 connectionAttempts = maxConnectionAttempts;
316             } else {
317                 connectionAttempts = null;
318             }
319
320             this.sleepFactor = sleepFactor.doubleValue();
321             this.executor = executor;
322             this.minSleep = minSleep;
323         }
324
325         @Override
326         public ReconnectStrategy createReconnectStrategy() {
327             final Long maxSleep = null;
328             final Long deadline = null;
329
330             return new TimedReconnectStrategy(executor, minSleep,
331                     minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
332         }
333     }
334 }