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.LoginPasswordHandler;
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.auth.DatastoreBackedPublicKeyAuth;
46 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
47 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
48 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
49 import org.opendaylight.netconf.sal.connect.netconf.listener.UserPreferences;
50 import org.opendaylight.netconf.sal.connect.netconf.sal.KeepaliveSalFacade;
51 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfKeystoreAdapter;
52 import org.opendaylight.netconf.sal.connect.netconf.schema.YangLibrarySchemaYangSourceProvider;
53 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
54 import org.opendaylight.netconf.topology.singleton.api.RemoteDeviceConnector;
55 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfConnectorDTO;
56 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
57 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
58 import org.opendaylight.protocol.framework.ReconnectStrategy;
59 import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
60 import org.opendaylight.protocol.framework.TimedReconnectStrategy;
61 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
62 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapability.CapabilityOrigin;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.Credentials;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.KeyAuth;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPw;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPwUnencrypted;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.key.auth.KeyBased;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.login.pw.LoginPassword;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.login.pw.unencrypted.LoginPasswordUnencrypted;
72 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
73 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
74 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
75 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
76 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
80 public class RemoteDeviceConnectorImpl implements RemoteDeviceConnector {
82 private static final Logger LOG = LoggerFactory.getLogger(RemoteDeviceConnectorImpl.class);
84 // Initializes default constant instances for the case when the default schema repository
85 // directory cache/schema is used.
87 private final NetconfTopologySetup netconfTopologyDeviceSetup;
88 private final RemoteDeviceId remoteDeviceId;
89 private final DOMMountPointService mountService;
90 private final Timeout actorResponseWaitTime;
91 private final String privateKeyPath;
92 private final String privateKeyPassphrase;
93 private final AAAEncryptionService encryptionService;
94 private NetconfConnectorDTO deviceCommunicatorDTO;
95 private final NetconfKeystoreAdapter keystoreAdapter;
97 public RemoteDeviceConnectorImpl(final NetconfTopologySetup netconfTopologyDeviceSetup,
98 final RemoteDeviceId remoteDeviceId, final Timeout actorResponseWaitTime,
99 final DOMMountPointService mountService) {
101 this.netconfTopologyDeviceSetup = Preconditions.checkNotNull(netconfTopologyDeviceSetup);
102 this.remoteDeviceId = remoteDeviceId;
103 this.actorResponseWaitTime = actorResponseWaitTime;
104 this.mountService = mountService;
105 this.privateKeyPath = netconfTopologyDeviceSetup.getPrivateKeyPath();
106 this.privateKeyPassphrase = netconfTopologyDeviceSetup.getPrivateKeyPassphrase();
107 this.encryptionService = netconfTopologyDeviceSetup.getEncryptionService();
108 keystoreAdapter = new NetconfKeystoreAdapter(netconfTopologyDeviceSetup.getDataBroker());
112 public void startRemoteDeviceConnection(final ActorRef deviceContextActorRef) {
114 final NetconfNode netconfNode = netconfTopologyDeviceSetup.getNode().getAugmentation(NetconfNode.class);
115 final NodeId nodeId = netconfTopologyDeviceSetup.getNode().getNodeId();
116 Preconditions.checkNotNull(netconfNode.getHost());
117 Preconditions.checkNotNull(netconfNode.getPort());
118 Preconditions.checkNotNull(netconfNode.isTcpOnly());
120 this.deviceCommunicatorDTO = createDeviceCommunicator(nodeId, netconfNode, deviceContextActorRef);
121 final NetconfDeviceCommunicator deviceCommunicator = deviceCommunicatorDTO.getCommunicator();
122 final NetconfClientSessionListener netconfClientSessionListener = deviceCommunicatorDTO.getSessionListener();
123 final NetconfReconnectingClientConfiguration clientConfig =
124 getClientConfig(netconfClientSessionListener, netconfNode);
125 final ListenableFuture<NetconfDeviceCapabilities> future = deviceCommunicator
126 .initializeRemoteConnection(netconfTopologyDeviceSetup.getNetconfClientDispatcher(), clientConfig);
128 Futures.addCallback(future, new FutureCallback<NetconfDeviceCapabilities>() {
130 public void onSuccess(final NetconfDeviceCapabilities result) {
131 LOG.debug("{}: Connector started successfully", remoteDeviceId);
135 public void onFailure(@Nullable final Throwable throwable) {
136 LOG.error("{}: Connector failed, {}", remoteDeviceId, throwable);
138 }, MoreExecutors.directExecutor());
141 @SuppressWarnings("checkstyle:IllegalCatch")
143 public void stopRemoteDeviceConnection() {
144 Preconditions.checkNotNull(deviceCommunicatorDTO, remoteDeviceId + ": Device communicator was not created.");
146 deviceCommunicatorDTO.close();
147 } catch (final Exception e) {
148 LOG.error("{}: Error at closing device communicator.", remoteDeviceId, e);
153 NetconfConnectorDTO createDeviceCommunicator(final NodeId nodeId, final NetconfNode node,
154 final ActorRef deviceContextActorRef) {
155 //setup default values since default value is not supported in mdsal
156 final Long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null
157 ? NetconfTopologyUtils.DEFAULT_REQUEST_TIMEOUT_MILLIS : node.getDefaultRequestTimeoutMillis();
158 final Long keepaliveDelay = node.getKeepaliveDelay() == null
159 ? NetconfTopologyUtils.DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay();
160 final Boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null
161 ? NetconfTopologyUtils.DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.isReconnectOnChangedSchema();
163 RemoteDeviceHandler<NetconfSessionPreferences> salFacade = new MasterSalFacade(remoteDeviceId,
164 netconfTopologyDeviceSetup.getActorSystem(), deviceContextActorRef, actorResponseWaitTime,
165 mountService, netconfTopologyDeviceSetup.getDataBroker());
166 if (keepaliveDelay > 0) {
167 LOG.info("{}: Adding keepalive facade.", remoteDeviceId);
168 salFacade = new KeepaliveSalFacade(remoteDeviceId, salFacade,
169 netconfTopologyDeviceSetup.getKeepaliveExecutor().getExecutor(), keepaliveDelay,
170 defaultRequestTimeoutMillis);
173 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = netconfTopologyDeviceSetup.getSchemaResourcesDTO();
176 // pre register yang library sources as fallback schemas to schema registry
177 final List<SchemaSourceRegistration<YangTextSchemaSource>> registeredYangLibSources = Lists.newArrayList();
178 if (node.getYangLibrary() != null) {
179 final String yangLibURL = node.getYangLibrary().getYangLibraryUrl().getValue();
180 final String yangLibUsername = node.getYangLibrary().getUsername();
181 final String yangLigPassword = node.getYangLibrary().getPassword();
183 final LibraryModulesSchemas libraryModulesSchemas;
184 if (yangLibURL != null) {
185 if (yangLibUsername != null && yangLigPassword != null) {
186 libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL, yangLibUsername, yangLigPassword);
188 libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL);
191 for (final Map.Entry<SourceIdentifier, URL> sourceIdentifierURLEntry :
192 libraryModulesSchemas.getAvailableModels().entrySet()) {
193 registeredYangLibSources
194 .add(schemaResourcesDTO.getSchemaRegistry().registerSchemaSource(
195 new YangLibrarySchemaYangSourceProvider(remoteDeviceId,
196 libraryModulesSchemas.getAvailableModels()),
197 PotentialSchemaSource
198 .create(sourceIdentifierURLEntry.getKey(), YangTextSchemaSource.class,
199 PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
204 final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> device;
205 if (node.isSchemaless()) {
206 device = new SchemalessNetconfDevice(remoteDeviceId, salFacade);
208 device = new NetconfDeviceBuilder()
209 .setReconnectOnSchemasChange(reconnectOnChangedSchema)
210 .setSchemaResourcesDTO(schemaResourcesDTO)
211 .setGlobalProcessingExecutor(netconfTopologyDeviceSetup.getProcessingExecutor().getExecutor())
212 .setId(remoteDeviceId)
213 .setSalFacade(salFacade)
217 final Optional<NetconfSessionPreferences> userCapabilities = getUserCapabilities(node);
218 final int rpcMessageLimit =
219 node.getConcurrentRpcLimit() == null
220 ? NetconfTopologyUtils.DEFAULT_CONCURRENT_RPC_LIMIT : node.getConcurrentRpcLimit();
222 if (rpcMessageLimit < 1) {
223 LOG.info("{}: Concurrent rpc limit is smaller than 1, no limit will be enforced.", remoteDeviceId);
226 return new NetconfConnectorDTO(
227 userCapabilities.isPresent() ? new NetconfDeviceCommunicator(remoteDeviceId, device,
228 new UserPreferences(userCapabilities.get(),
229 Objects.isNull(node.getYangModuleCapabilities())
230 ? false : node.getYangModuleCapabilities().isOverride(),
231 Objects.isNull(node.getNonModuleCapabilities())
232 ? false : node.getNonModuleCapabilities().isOverride()), rpcMessageLimit)
233 : new NetconfDeviceCommunicator(remoteDeviceId, device, rpcMessageLimit), salFacade);
236 private Optional<NetconfSessionPreferences> getUserCapabilities(final NetconfNode node) {
237 if (node.getYangModuleCapabilities() == null && node.getNonModuleCapabilities() == null) {
238 return Optional.empty();
240 final List<String> capabilities = new ArrayList<>();
242 if (node.getYangModuleCapabilities() != null) {
243 capabilities.addAll(node.getYangModuleCapabilities().getCapability());
246 //non-module capabilities should not exist in yang module capabilities
247 final NetconfSessionPreferences netconfSessionPreferences = NetconfSessionPreferences.fromStrings(capabilities);
248 Preconditions.checkState(netconfSessionPreferences.getNonModuleCaps().isEmpty(),
249 "List yang-module-capabilities/capability should contain only module based capabilities. "
250 + "Non-module capabilities used: " + netconfSessionPreferences.getNonModuleCaps());
252 if (node.getNonModuleCapabilities() != null) {
253 capabilities.addAll(node.getNonModuleCapabilities().getCapability());
256 return Optional.of(NetconfSessionPreferences.fromStrings(capabilities, CapabilityOrigin.UserDefined));
259 //TODO: duplicate code
260 private InetSocketAddress getSocketAddress(final Host host, final int port) {
261 if (host.getDomainName() != null) {
262 return new InetSocketAddress(host.getDomainName().getValue(), port);
264 final IpAddress ipAddress = host.getIpAddress();
265 final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() :
266 ipAddress.getIpv6Address().getValue();
267 return new InetSocketAddress(ip, port);
272 NetconfReconnectingClientConfiguration getClientConfig(final NetconfClientSessionListener listener,
273 final NetconfNode node) {
275 //setup default values since default value is not supported in mdsal
276 final long clientConnectionTimeoutMillis = node.getConnectionTimeoutMillis() == null
277 ? NetconfTopologyUtils.DEFAULT_CONNECTION_TIMEOUT_MILLIS : node.getConnectionTimeoutMillis();
278 final long maxConnectionAttempts = node.getMaxConnectionAttempts() == null
279 ? NetconfTopologyUtils.DEFAULT_MAX_CONNECTION_ATTEMPTS : node.getMaxConnectionAttempts();
280 final int betweenAttemptsTimeoutMillis = node.getBetweenAttemptsTimeoutMillis() == null
281 ? NetconfTopologyUtils.DEFAULT_BETWEEN_ATTEMPTS_TIMEOUT_MILLIS : node.getBetweenAttemptsTimeoutMillis();
282 final BigDecimal sleepFactor = node.getSleepFactor() == null
283 ? NetconfTopologyUtils.DEFAULT_SLEEP_FACTOR : node.getSleepFactor();
285 final InetSocketAddress socketAddress = getSocketAddress(node.getHost(), node.getPort().getValue());
287 final ReconnectStrategyFactory sf =
288 new TimedReconnectStrategyFactory(netconfTopologyDeviceSetup.getEventExecutor(), maxConnectionAttempts,
289 betweenAttemptsTimeoutMillis, sleepFactor);
290 final ReconnectStrategy strategy = sf.createReconnectStrategy();
292 final AuthenticationHandler authHandler = getHandlerFromCredentials(node.getCredentials());
294 return NetconfReconnectingClientConfigurationBuilder.create()
295 .withAddress(socketAddress)
296 .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
297 .withReconnectStrategy(strategy)
298 .withAuthHandler(authHandler)
299 .withProtocol(node.isTcpOnly()
300 ? NetconfClientConfiguration.NetconfClientProtocol.TCP
301 : NetconfClientConfiguration.NetconfClientProtocol.SSH)
302 .withConnectStrategyFactory(sf)
303 .withSessionListener(listener)
307 private AuthenticationHandler getHandlerFromCredentials(final Credentials credentials) {
308 if (credentials instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology
309 .rev150114.netconf.node.credentials.credentials.LoginPassword) {
310 final org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology
311 .rev150114.netconf.node.credentials.credentials.LoginPassword loginPassword
312 = (org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology
313 .rev150114.netconf.node.credentials.credentials.LoginPassword) credentials;
314 return new LoginPasswordHandler(loginPassword.getUsername(), loginPassword.getPassword());
316 if (credentials instanceof LoginPwUnencrypted) {
317 final LoginPasswordUnencrypted loginPassword =
318 ((LoginPwUnencrypted) credentials).getLoginPasswordUnencrypted();
319 return new LoginPasswordHandler(loginPassword.getUsername(), loginPassword.getPassword());
321 if (credentials instanceof LoginPw) {
322 final LoginPassword loginPassword = ((LoginPw) credentials).getLoginPassword();
323 return new LoginPasswordHandler(loginPassword.getUsername(),
324 encryptionService.decrypt(loginPassword.getPassword()));
326 if (credentials instanceof KeyAuth) {
327 final KeyBased keyPair = ((KeyAuth) credentials).getKeyBased();
328 return new DatastoreBackedPublicKeyAuth(keyPair.getUsername(), keyPair.getKeyId(),
329 keystoreAdapter, encryptionService);
331 throw new IllegalStateException("Unsupported credential type: " + credentials.getClass());
334 private static final class TimedReconnectStrategyFactory implements ReconnectStrategyFactory {
335 private final Long connectionAttempts;
336 private final EventExecutor executor;
337 private final double sleepFactor;
338 private final int minSleep;
340 TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts,
341 final int minSleep, final BigDecimal sleepFactor) {
342 if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
343 connectionAttempts = maxConnectionAttempts;
345 connectionAttempts = null;
348 this.sleepFactor = sleepFactor.doubleValue();
349 this.executor = executor;
350 this.minSleep = minSleep;
354 public ReconnectStrategy createReconnectStrategy() {
355 final Long maxSleep = null;
356 final Long deadline = null;
358 return new TimedReconnectStrategy(executor, minSleep,
359 minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);