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