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.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.LoginPassword;
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;
70 public class RemoteDeviceConnectorImpl implements RemoteDeviceConnector {
72 private static final Logger LOG = LoggerFactory.getLogger(RemoteDeviceConnectorImpl.class);
74 // Initializes default constant instances for the case when the default schema repository
75 // directory cache/schema is used.
77 private final NetconfTopologySetup netconfTopologyDeviceSetup;
78 private final RemoteDeviceId remoteDeviceId;
79 private final DOMMountPointService mountService;
80 private final Timeout actorResponseWaitTime;
82 private NetconfConnectorDTO deviceCommunicatorDTO;
84 public RemoteDeviceConnectorImpl(final NetconfTopologySetup netconfTopologyDeviceSetup,
85 final RemoteDeviceId remoteDeviceId, final Timeout actorResponseWaitTime,
86 final DOMMountPointService mountService) {
88 this.netconfTopologyDeviceSetup = Preconditions.checkNotNull(netconfTopologyDeviceSetup);
89 this.remoteDeviceId = remoteDeviceId;
90 this.actorResponseWaitTime = actorResponseWaitTime;
91 this.mountService = mountService;
95 public void startRemoteDeviceConnection(final ActorRef deviceContextActorRef) {
97 final NetconfNode netconfNode = netconfTopologyDeviceSetup.getNode().getAugmentation(NetconfNode.class);
98 final NodeId nodeId = netconfTopologyDeviceSetup.getNode().getNodeId();
99 Preconditions.checkNotNull(netconfNode.getHost());
100 Preconditions.checkNotNull(netconfNode.getPort());
101 Preconditions.checkNotNull(netconfNode.isTcpOnly());
103 this.deviceCommunicatorDTO = createDeviceCommunicator(nodeId, netconfNode, deviceContextActorRef);
104 final NetconfDeviceCommunicator deviceCommunicator = deviceCommunicatorDTO.getCommunicator();
105 final NetconfClientSessionListener netconfClientSessionListener = deviceCommunicatorDTO.getSessionListener();
106 final NetconfReconnectingClientConfiguration clientConfig =
107 getClientConfig(netconfClientSessionListener, netconfNode);
108 final ListenableFuture<NetconfDeviceCapabilities> future = deviceCommunicator
109 .initializeRemoteConnection(netconfTopologyDeviceSetup.getNetconfClientDispatcher(), clientConfig);
111 Futures.addCallback(future, new FutureCallback<NetconfDeviceCapabilities>() {
113 public void onSuccess(final NetconfDeviceCapabilities result) {
114 LOG.debug("{}: Connector started successfully", remoteDeviceId);
118 public void onFailure(@Nullable final Throwable throwable) {
119 LOG.error("{}: Connector failed, {}", remoteDeviceId, throwable);
124 @SuppressWarnings("checkstyle:IllegalCatch")
126 public void stopRemoteDeviceConnection() {
127 Preconditions.checkNotNull(deviceCommunicatorDTO, remoteDeviceId + ": Device communicator was not created.");
129 deviceCommunicatorDTO.close();
130 } catch (final Exception e) {
131 LOG.error("{}: Error at closing device communicator.", remoteDeviceId, e);
136 NetconfConnectorDTO createDeviceCommunicator(final NodeId nodeId, final NetconfNode node,
137 final ActorRef deviceContextActorRef) {
138 //setup default values since default value is not supported in mdsal
139 final Long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null
140 ? NetconfTopologyUtils.DEFAULT_REQUEST_TIMEOUT_MILLIS : node.getDefaultRequestTimeoutMillis();
141 final Long keepaliveDelay = node.getKeepaliveDelay() == null
142 ? NetconfTopologyUtils.DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay();
143 final Boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null
144 ? NetconfTopologyUtils.DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.isReconnectOnChangedSchema();
146 RemoteDeviceHandler<NetconfSessionPreferences> salFacade = new MasterSalFacade(remoteDeviceId,
147 netconfTopologyDeviceSetup.getActorSystem(), deviceContextActorRef, actorResponseWaitTime,
148 mountService, netconfTopologyDeviceSetup.getDataBroker());
149 if (keepaliveDelay > 0) {
150 LOG.info("{}: Adding keepalive facade.", remoteDeviceId);
151 salFacade = new KeepaliveSalFacade(remoteDeviceId, salFacade,
152 netconfTopologyDeviceSetup.getKeepaliveExecutor().getExecutor(), keepaliveDelay,
153 defaultRequestTimeoutMillis);
156 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = netconfTopologyDeviceSetup.getSchemaResourcesDTO();
159 // pre register yang library sources as fallback schemas to schema registry
160 final List<SchemaSourceRegistration<YangTextSchemaSource>> registeredYangLibSources = Lists.newArrayList();
161 if (node.getYangLibrary() != null) {
162 final String yangLibURL = node.getYangLibrary().getYangLibraryUrl().getValue();
163 final String yangLibUsername = node.getYangLibrary().getUsername();
164 final String yangLigPassword = node.getYangLibrary().getPassword();
166 final LibraryModulesSchemas libraryModulesSchemas;
167 if (yangLibURL != null) {
168 if (yangLibUsername != null && yangLigPassword != null) {
169 libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL, yangLibUsername, yangLigPassword);
171 libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL);
174 for (final Map.Entry<SourceIdentifier, URL> sourceIdentifierURLEntry :
175 libraryModulesSchemas.getAvailableModels().entrySet()) {
176 registeredYangLibSources
177 .add(schemaResourcesDTO.getSchemaRegistry().registerSchemaSource(
178 new YangLibrarySchemaYangSourceProvider(remoteDeviceId,
179 libraryModulesSchemas.getAvailableModels()),
180 PotentialSchemaSource
181 .create(sourceIdentifierURLEntry.getKey(), YangTextSchemaSource.class,
182 PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
187 final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> device;
188 if (node.isSchemaless()) {
189 device = new SchemalessNetconfDevice(remoteDeviceId, salFacade);
191 device = new NetconfDeviceBuilder()
192 .setReconnectOnSchemasChange(reconnectOnChangedSchema)
193 .setSchemaResourcesDTO(schemaResourcesDTO)
194 .setGlobalProcessingExecutor(netconfTopologyDeviceSetup.getProcessingExecutor().getExecutor())
195 .setId(remoteDeviceId)
196 .setSalFacade(salFacade)
200 final Optional<NetconfSessionPreferences> userCapabilities = getUserCapabilities(node);
201 final int rpcMessageLimit =
202 node.getConcurrentRpcLimit() == null
203 ? NetconfTopologyUtils.DEFAULT_CONCURRENT_RPC_LIMIT : node.getConcurrentRpcLimit();
205 if (rpcMessageLimit < 1) {
206 LOG.info("{}: Concurrent rpc limit is smaller than 1, no limit will be enforced.", remoteDeviceId);
209 return new NetconfConnectorDTO(
210 userCapabilities.isPresent() ? new NetconfDeviceCommunicator(remoteDeviceId, device,
211 new UserPreferences(userCapabilities.get(),
212 Objects.isNull(node.getYangModuleCapabilities())
213 ? false : node.getYangModuleCapabilities().isOverride(),
214 Objects.isNull(node.getNonModuleCapabilities())
215 ? false : node.getNonModuleCapabilities().isOverride()), rpcMessageLimit)
216 : new NetconfDeviceCommunicator(remoteDeviceId, device, rpcMessageLimit), salFacade);
219 private Optional<NetconfSessionPreferences> getUserCapabilities(final NetconfNode node) {
220 if (node.getYangModuleCapabilities() == null && node.getNonModuleCapabilities() == null) {
221 return Optional.empty();
223 final List<String> capabilities = new ArrayList<>();
225 if (node.getYangModuleCapabilities() != null) {
226 capabilities.addAll(node.getYangModuleCapabilities().getCapability());
229 //non-module capabilities should not exist in yang module capabilities
230 final NetconfSessionPreferences netconfSessionPreferences = NetconfSessionPreferences.fromStrings(capabilities);
231 Preconditions.checkState(netconfSessionPreferences.getNonModuleCaps().isEmpty(),
232 "List yang-module-capabilities/capability should contain only module based capabilities. "
233 + "Non-module capabilities used: " + netconfSessionPreferences.getNonModuleCaps());
235 if (node.getNonModuleCapabilities() != null) {
236 capabilities.addAll(node.getNonModuleCapabilities().getCapability());
239 return Optional.of(NetconfSessionPreferences.fromStrings(capabilities, CapabilityOrigin.UserDefined));
242 //TODO: duplicate code
243 private InetSocketAddress getSocketAddress(final Host host, final int port) {
244 if (host.getDomainName() != null) {
245 return new InetSocketAddress(host.getDomainName().getValue(), port);
247 final IpAddress ipAddress = host.getIpAddress();
248 final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() :
249 ipAddress.getIpv6Address().getValue();
250 return new InetSocketAddress(ip, port);
255 NetconfReconnectingClientConfiguration getClientConfig(final NetconfClientSessionListener listener,
256 final NetconfNode node) {
258 //setup default values since default value is not supported in mdsal
259 final long clientConnectionTimeoutMillis = node.getConnectionTimeoutMillis() == null
260 ? NetconfTopologyUtils.DEFAULT_CONNECTION_TIMEOUT_MILLIS : node.getConnectionTimeoutMillis();
261 final long maxConnectionAttempts = node.getMaxConnectionAttempts() == null
262 ? NetconfTopologyUtils.DEFAULT_MAX_CONNECTION_ATTEMPTS : node.getMaxConnectionAttempts();
263 final int betweenAttemptsTimeoutMillis = node.getBetweenAttemptsTimeoutMillis() == null
264 ? NetconfTopologyUtils.DEFAULT_BETWEEN_ATTEMPTS_TIMEOUT_MILLIS : node.getBetweenAttemptsTimeoutMillis();
265 final BigDecimal sleepFactor = node.getSleepFactor() == null
266 ? NetconfTopologyUtils.DEFAULT_SLEEP_FACTOR : node.getSleepFactor();
268 final InetSocketAddress socketAddress = getSocketAddress(node.getHost(), node.getPort().getValue());
270 final ReconnectStrategyFactory sf =
271 new TimedReconnectStrategyFactory(netconfTopologyDeviceSetup.getEventExecutor(), maxConnectionAttempts,
272 betweenAttemptsTimeoutMillis, sleepFactor);
273 final ReconnectStrategy strategy = sf.createReconnectStrategy();
275 final AuthenticationHandler authHandler;
276 final Credentials credentials = node.getCredentials();
277 if (credentials instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf
278 .node.credentials.credentials.LoginPassword) {
279 authHandler = new LoginPassword(
280 ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf
281 .node.credentials.credentials.LoginPassword) credentials).getUsername(),
282 ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf
283 .node.credentials.credentials.LoginPassword) credentials).getPassword());
285 throw new IllegalStateException(remoteDeviceId + ": Only login/password authentication is supported");
288 return NetconfReconnectingClientConfigurationBuilder.create()
289 .withAddress(socketAddress)
290 .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
291 .withReconnectStrategy(strategy)
292 .withAuthHandler(authHandler)
293 .withProtocol(node.isTcpOnly()
294 ? NetconfClientConfiguration.NetconfClientProtocol.TCP
295 : NetconfClientConfiguration.NetconfClientProtocol.SSH)
296 .withConnectStrategyFactory(sf)
297 .withSessionListener(listener)
301 private static final class TimedReconnectStrategyFactory implements ReconnectStrategyFactory {
302 private final Long connectionAttempts;
303 private final EventExecutor executor;
304 private final double sleepFactor;
305 private final int minSleep;
307 TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts,
308 final int minSleep, final BigDecimal sleepFactor) {
309 if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
310 connectionAttempts = maxConnectionAttempts;
312 connectionAttempts = null;
315 this.sleepFactor = sleepFactor.doubleValue();
316 this.executor = executor;
317 this.minSleep = minSleep;
321 public ReconnectStrategy createReconnectStrategy() {
322 final Long maxSleep = null;
323 final Long deadline = null;
325 return new TimedReconnectStrategy(executor, minSleep,
326 minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);