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);
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() ? new NetconfDeviceCommunicator(remoteDeviceId, device,
210 new UserPreferences(userCapabilities.get(),
211 Objects.isNull(node.getYangModuleCapabilities())
212 ? false : node.getYangModuleCapabilities().isOverride(),
213 Objects.isNull(node.getNonModuleCapabilities())
214 ? false : node.getNonModuleCapabilities().isOverride()), rpcMessageLimit)
215 : new NetconfDeviceCommunicator(remoteDeviceId, device, rpcMessageLimit), salFacade);
218 private Optional<NetconfSessionPreferences> getUserCapabilities(final NetconfNode node) {
219 if (node.getYangModuleCapabilities() == null && node.getNonModuleCapabilities() == null) {
220 return Optional.empty();
222 final List<String> capabilities = new ArrayList<>();
224 if (node.getYangModuleCapabilities() != null) {
225 capabilities.addAll(node.getYangModuleCapabilities().getCapability());
228 //non-module capabilities should not exist in yang module capabilities
229 final NetconfSessionPreferences netconfSessionPreferences = NetconfSessionPreferences.fromStrings(capabilities);
230 Preconditions.checkState(netconfSessionPreferences.getNonModuleCaps().isEmpty(), "List yang-module-capabilities/capability " +
231 "should contain only module based capabilities. Non-module capabilities used: " +
232 netconfSessionPreferences.getNonModuleCaps());
234 if (node.getNonModuleCapabilities() != null) {
235 capabilities.addAll(node.getNonModuleCapabilities().getCapability());
238 return Optional.of(NetconfSessionPreferences.fromStrings(capabilities, CapabilityOrigin.UserDefined));
241 //TODO: duplicate code
242 private InetSocketAddress getSocketAddress(final Host host, final int port) {
243 if (host.getDomainName() != null) {
244 return new InetSocketAddress(host.getDomainName().getValue(), port);
246 final IpAddress ipAddress = host.getIpAddress();
247 final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() :
248 ipAddress.getIpv6Address().getValue();
249 return new InetSocketAddress(ip, port);
254 NetconfReconnectingClientConfiguration getClientConfig(final NetconfClientSessionListener listener,
255 final NetconfNode node) {
257 //setup default values since default value is not supported in mdsal
258 final long clientConnectionTimeoutMillis = node.getConnectionTimeoutMillis() == null
259 ? NetconfTopologyUtils.DEFAULT_CONNECTION_TIMEOUT_MILLIS : node.getConnectionTimeoutMillis();
260 final long maxConnectionAttempts = node.getMaxConnectionAttempts() == null
261 ? NetconfTopologyUtils.DEFAULT_MAX_CONNECTION_ATTEMPTS : node.getMaxConnectionAttempts();
262 final int betweenAttemptsTimeoutMillis = node.getBetweenAttemptsTimeoutMillis() == null
263 ? NetconfTopologyUtils.DEFAULT_BETWEEN_ATTEMPTS_TIMEOUT_MILLIS : node.getBetweenAttemptsTimeoutMillis();
264 final BigDecimal sleepFactor = node.getSleepFactor() == null
265 ? NetconfTopologyUtils.DEFAULT_SLEEP_FACTOR : node.getSleepFactor();
267 final InetSocketAddress socketAddress = getSocketAddress(node.getHost(), node.getPort().getValue());
269 final ReconnectStrategyFactory sf =
270 new TimedReconnectStrategyFactory(netconfTopologyDeviceSetup.getEventExecutor(), maxConnectionAttempts,
271 betweenAttemptsTimeoutMillis, sleepFactor);
272 final ReconnectStrategy strategy = sf.createReconnectStrategy();
274 final AuthenticationHandler authHandler;
275 final Credentials credentials = node.getCredentials();
276 if (credentials instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword) {
277 authHandler = new LoginPassword(
278 ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword) credentials).getUsername(),
279 ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword) credentials).getPassword());
281 throw new IllegalStateException(remoteDeviceId + ": Only login/password authentication is supported");
284 return NetconfReconnectingClientConfigurationBuilder.create()
285 .withAddress(socketAddress)
286 .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
287 .withReconnectStrategy(strategy)
288 .withAuthHandler(authHandler)
289 .withProtocol(node.isTcpOnly()
290 ? NetconfClientConfiguration.NetconfClientProtocol.TCP
291 : NetconfClientConfiguration.NetconfClientProtocol.SSH)
292 .withConnectStrategyFactory(sf)
293 .withSessionListener(listener)
297 private static final class TimedReconnectStrategyFactory implements ReconnectStrategyFactory {
298 private final Long connectionAttempts;
299 private final EventExecutor executor;
300 private final double sleepFactor;
301 private final int minSleep;
303 TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts,
304 final int minSleep, final BigDecimal sleepFactor) {
305 if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
306 connectionAttempts = maxConnectionAttempts;
308 connectionAttempts = null;
311 this.sleepFactor = sleepFactor.doubleValue();
312 this.executor = executor;
313 this.minSleep = minSleep;
317 public ReconnectStrategy createReconnectStrategy() {
318 final Long maxSleep = null;
319 final Long deadline = null;
321 return new TimedReconnectStrategy(executor, minSleep,
322 minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);