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