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