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 com.google.common.util.concurrent.MoreExecutors;
20 import io.netty.util.concurrent.EventExecutor;
21 import java.math.BigDecimal;
22 import java.net.InetSocketAddress;
24 import java.util.ArrayList;
25 import java.util.List;
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;
72 public class RemoteDeviceConnectorImpl implements RemoteDeviceConnector {
74 private static final Logger LOG = LoggerFactory.getLogger(RemoteDeviceConnectorImpl.class);
76 // Initializes default constant instances for the case when the default schema repository
77 // directory cache/schema is used.
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;
88 public RemoteDeviceConnectorImpl(final NetconfTopologySetup netconfTopologyDeviceSetup,
89 final RemoteDeviceId remoteDeviceId, final Timeout actorResponseWaitTime,
90 final DOMMountPointService mountService) {
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();
102 public void startRemoteDeviceConnection(final ActorRef deviceContextActorRef) {
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());
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);
118 Futures.addCallback(future, new FutureCallback<NetconfDeviceCapabilities>() {
120 public void onSuccess(final NetconfDeviceCapabilities result) {
121 LOG.debug("{}: Connector started successfully", remoteDeviceId);
125 public void onFailure(@Nullable final Throwable throwable) {
126 LOG.error("{}: Connector failed, {}", remoteDeviceId, throwable);
128 }, MoreExecutors.directExecutor());
131 @SuppressWarnings("checkstyle:IllegalCatch")
133 public void stopRemoteDeviceConnection() {
134 Preconditions.checkNotNull(deviceCommunicatorDTO, remoteDeviceId + ": Device communicator was not created.");
136 deviceCommunicatorDTO.close();
137 } catch (final Exception e) {
138 LOG.error("{}: Error at closing device communicator.", remoteDeviceId, e);
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();
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);
163 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = netconfTopologyDeviceSetup.getSchemaResourcesDTO();
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();
173 final LibraryModulesSchemas libraryModulesSchemas;
174 if (yangLibURL != null) {
175 if (yangLibUsername != null && yangLigPassword != null) {
176 libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL, yangLibUsername, yangLigPassword);
178 libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL);
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())));
194 final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> device;
195 if (node.isSchemaless()) {
196 device = new SchemalessNetconfDevice(remoteDeviceId, salFacade);
198 device = new NetconfDeviceBuilder()
199 .setReconnectOnSchemasChange(reconnectOnChangedSchema)
200 .setSchemaResourcesDTO(schemaResourcesDTO)
201 .setGlobalProcessingExecutor(netconfTopologyDeviceSetup.getProcessingExecutor().getExecutor())
202 .setId(remoteDeviceId)
203 .setSalFacade(salFacade)
207 final Optional<NetconfSessionPreferences> userCapabilities = getUserCapabilities(node);
208 final int rpcMessageLimit =
209 node.getConcurrentRpcLimit() == null
210 ? NetconfTopologyUtils.DEFAULT_CONCURRENT_RPC_LIMIT : node.getConcurrentRpcLimit();
212 if (rpcMessageLimit < 1) {
213 LOG.info("{}: Concurrent rpc limit is smaller than 1, no limit will be enforced.", remoteDeviceId);
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);
226 private Optional<NetconfSessionPreferences> getUserCapabilities(final NetconfNode node) {
227 if (node.getYangModuleCapabilities() == null && node.getNonModuleCapabilities() == null) {
228 return Optional.empty();
230 final List<String> capabilities = new ArrayList<>();
232 if (node.getYangModuleCapabilities() != null) {
233 capabilities.addAll(node.getYangModuleCapabilities().getCapability());
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());
242 if (node.getNonModuleCapabilities() != null) {
243 capabilities.addAll(node.getNonModuleCapabilities().getCapability());
246 return Optional.of(NetconfSessionPreferences.fromStrings(capabilities, CapabilityOrigin.UserDefined));
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);
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);
262 NetconfReconnectingClientConfiguration getClientConfig(final NetconfClientSessionListener listener,
263 final NetconfNode node) {
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();
275 final InetSocketAddress socketAddress = getSocketAddress(node.getHost(), node.getPort().getValue());
277 final ReconnectStrategyFactory sf =
278 new TimedReconnectStrategyFactory(netconfTopologyDeviceSetup.getEventExecutor(), maxConnectionAttempts,
279 betweenAttemptsTimeoutMillis, sleepFactor);
280 final ReconnectStrategy strategy = sf.createReconnectStrategy();
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);
294 throw new IllegalStateException(remoteDeviceId + ": Only login/password authentication is supported");
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)
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;
316 TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts,
317 final int minSleep, final BigDecimal sleepFactor) {
318 if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
319 connectionAttempts = maxConnectionAttempts;
321 connectionAttempts = null;
324 this.sleepFactor = sleepFactor.doubleValue();
325 this.executor = executor;
326 this.minSleep = minSleep;
330 public ReconnectStrategy createReconnectStrategy() {
331 final Long maxSleep = null;
332 final Long deadline = null;
334 return new TimedReconnectStrategy(executor, minSleep,
335 minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);