2 * Copyright (c) 2015 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;
11 import com.google.common.base.Preconditions;
12 import com.google.common.util.concurrent.FutureCallback;
13 import com.google.common.util.concurrent.Futures;
14 import com.google.common.util.concurrent.ListenableFuture;
15 import io.netty.util.concurrent.EventExecutor;
17 import java.math.BigDecimal;
18 import java.net.InetSocketAddress;
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.HashMap;
22 import java.util.HashSet;
24 import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
25 import org.opendaylight.controller.config.threadpool.ThreadPool;
26 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
27 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
28 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
29 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ProviderContext;
30 import org.opendaylight.controller.sal.binding.api.BindingAwareProvider;
31 import org.opendaylight.controller.sal.core.api.Broker;
32 import org.opendaylight.controller.sal.core.api.Broker.ProviderSession;
33 import org.opendaylight.controller.sal.core.api.Provider;
34 import org.opendaylight.netconf.client.NetconfClientDispatcher;
35 import org.opendaylight.netconf.client.NetconfClientSessionListener;
36 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
37 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration;
38 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder;
39 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
40 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.LoginPassword;
41 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
42 import org.opendaylight.netconf.sal.connect.netconf.NetconfDevice;
43 import org.opendaylight.netconf.sal.connect.netconf.NetconfStateSchemas;
44 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
45 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
46 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
47 import org.opendaylight.netconf.sal.connect.netconf.sal.KeepaliveSalFacade;
48 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
49 import org.opendaylight.netconf.topology.pipeline.TopologyMountPointFacade.ConnectionStatusListenerRegistration;
50 import org.opendaylight.protocol.framework.ReconnectStrategy;
51 import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
52 import org.opendaylight.protocol.framework.TimedReconnectStrategy;
53 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Host;
54 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.Credentials;
57 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
58 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
59 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
60 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
61 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
62 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
63 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
64 import org.opendaylight.yangtools.yang.binding.Identifier;
65 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
66 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
67 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
68 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
69 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
70 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
71 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
72 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
73 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
74 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
78 public abstract class AbstractNetconfTopology implements NetconfTopology, BindingAwareProvider, Provider{
80 private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfTopology.class);
82 protected static final long DEFAULT_REQUEST_TIMEOUT_MILIS = 60000L;
83 protected static final int DEFAULT_KEEPALIVE_DELAY = 0;
84 protected static final boolean DEFAULT_RECONNECT_ON_CHANGED_SCHEMA = false;
85 protected static final int DEFAULT_MAX_CONNECTION_ATTEMPTS = 0;
86 protected static final int DEFAULT_BETWEEN_ATTEMPTS_TIMEOUT_MILLIS = 2000;
87 protected static final BigDecimal DEFAULT_SLEEP_FACTOR = new BigDecimal(1.5);
89 private static FilesystemSchemaSourceCache<YangTextSchemaSource> CACHE = null;
90 //keep track of already initialized repositories to avoid adding redundant listeners
91 private static final Set<SchemaRepository> INITIALIZED_SCHEMA_REPOSITORIES = new HashSet<>();
93 protected final String topologyId;
94 private final NetconfClientDispatcher clientDispatcher;
95 protected final BindingAwareBroker bindingAwareBroker;
96 protected final Broker domBroker;
97 private final EventExecutor eventExecutor;
98 protected final ScheduledThreadPool keepaliveExecutor;
99 protected final ThreadPool processingExecutor;
100 protected final SharedSchemaRepository sharedSchemaRepository;
102 protected SchemaSourceRegistry schemaRegistry = null;
103 protected SchemaContextFactory schemaContextFactory = null;
105 protected DOMMountPointService mountPointService = null;
106 protected DataBroker dataBroker = null;
107 protected final HashMap<NodeId, NetconfConnectorDTO> activeConnectors = new HashMap<>();
109 protected AbstractNetconfTopology(final String topologyId, final NetconfClientDispatcher clientDispatcher,
110 final BindingAwareBroker bindingAwareBroker, final Broker domBroker,
111 final EventExecutor eventExecutor, final ScheduledThreadPool keepaliveExecutor,
112 final ThreadPool processingExecutor, final SchemaRepositoryProvider schemaRepositoryProvider) {
113 this.topologyId = topologyId;
114 this.clientDispatcher = clientDispatcher;
115 this.bindingAwareBroker = bindingAwareBroker;
116 this.domBroker = domBroker;
117 this.eventExecutor = eventExecutor;
118 this.keepaliveExecutor = keepaliveExecutor;
119 this.processingExecutor = processingExecutor;
120 this.sharedSchemaRepository = schemaRepositoryProvider.getSharedSchemaRepository();
122 initFilesystemSchemaSourceCache(sharedSchemaRepository);
125 protected void registerToSal(BindingAwareProvider baProvider, Provider provider) {
126 domBroker.registerProvider(provider);
127 bindingAwareBroker.registerProvider(baProvider);
130 private void initFilesystemSchemaSourceCache(SharedSchemaRepository repository) {
131 LOG.warn("Schema repository used: {}", repository.getIdentifier());
133 CACHE = new FilesystemSchemaSourceCache<>(repository, YangTextSchemaSource.class, new File("cache/schema"));
135 if (!INITIALIZED_SCHEMA_REPOSITORIES.contains(repository)) {
136 repository.registerSchemaSourceListener(CACHE);
137 repository.registerSchemaSourceListener(TextToASTTransformer.create(repository, repository));
138 INITIALIZED_SCHEMA_REPOSITORIES.add(repository);
140 setSchemaRegistry(repository);
141 setSchemaContextFactory(repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT));
144 public void setSchemaRegistry(final SchemaSourceRegistry schemaRegistry) {
145 this.schemaRegistry = schemaRegistry;
148 public void setSchemaContextFactory(final SchemaContextFactory schemaContextFactory) {
149 this.schemaContextFactory = schemaContextFactory;
153 public abstract void onSessionInitiated(ProviderContext session);
156 public String getTopologyId() {
161 public DataBroker getDataBroker() {
166 public ListenableFuture<NetconfDeviceCapabilities> connectNode(NodeId nodeId, Node configNode) {
167 LOG.info("Connecting RemoteDevice{{}} , with config {}", nodeId, configNode);
168 return setupConnection(nodeId, configNode);
172 public ListenableFuture<Void> disconnectNode(NodeId nodeId) {
173 LOG.debug("Disconnecting RemoteDevice{{}}", nodeId.getValue());
174 if (!activeConnectors.containsKey(nodeId)) {
175 return Futures.immediateFailedFuture(new IllegalStateException("Unable to disconnect device that is not connected"));
178 // retrieve connection, and disconnect it
179 final NetconfConnectorDTO connectorDTO = activeConnectors.remove(nodeId);
180 connectorDTO.getCommunicator().close();
181 connectorDTO.getFacade().close();
182 return Futures.immediateFuture(null);
185 protected ListenableFuture<NetconfDeviceCapabilities> setupConnection(final NodeId nodeId,
186 final Node configNode) {
187 final NetconfNode netconfNode = configNode.getAugmentation(NetconfNode.class);
189 Preconditions.checkNotNull(netconfNode.getHost());
190 Preconditions.checkNotNull(netconfNode.getPort());
191 Preconditions.checkNotNull(netconfNode.isTcpOnly());
193 final NetconfConnectorDTO deviceCommunicatorDTO = createDeviceCommunicator(nodeId, netconfNode);
194 final NetconfDeviceCommunicator deviceCommunicator = deviceCommunicatorDTO.getCommunicator();
195 final NetconfClientSessionListener netconfClientSessionListener = deviceCommunicatorDTO.getSessionListener();
196 final NetconfReconnectingClientConfiguration clientConfig = getClientConfig(netconfClientSessionListener, netconfNode);
197 final ListenableFuture<NetconfDeviceCapabilities> future = deviceCommunicator.initializeRemoteConnection(clientDispatcher, clientConfig);
199 activeConnectors.put(nodeId, deviceCommunicatorDTO);
201 Futures.addCallback(future, new FutureCallback<NetconfDeviceCapabilities>() {
203 public void onSuccess(NetconfDeviceCapabilities result) {
204 LOG.debug("Connector for : " + nodeId.getValue() + " started succesfully");
208 public void onFailure(Throwable t) {
209 LOG.error("Connector for : " + nodeId.getValue() + " failed");
210 // remove this node from active connectors?
217 protected NetconfConnectorDTO createDeviceCommunicator(final NodeId nodeId,
218 final NetconfNode node) {
219 //setup default values since default value is not supported yet in mdsal
220 // TODO remove this when mdsal starts supporting default values
221 final Long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null ? DEFAULT_REQUEST_TIMEOUT_MILIS : node.getDefaultRequestTimeoutMillis();
222 final Long keepaliveDelay = node.getKeepaliveDelay() == null ? DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay();
223 final Boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null ? DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.isReconnectOnChangedSchema();
225 IpAddress ipAddress = node.getHost().getIpAddress();
226 InetSocketAddress address = new InetSocketAddress(ipAddress.getIpv4Address() != null ?
227 ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue(),
228 node.getPort().getValue());
229 RemoteDeviceId remoteDeviceId = new RemoteDeviceId(nodeId.getValue(), address);
231 RemoteDeviceHandler<NetconfSessionPreferences> salFacade =
232 createSalFacade(remoteDeviceId, domBroker, bindingAwareBroker, defaultRequestTimeoutMillis);
234 if (keepaliveDelay > 0) {
235 LOG.warn("Adding keepalive facade, for device {}", nodeId);
236 salFacade = new KeepaliveSalFacade(remoteDeviceId, salFacade, keepaliveExecutor.getExecutor(), keepaliveDelay);
239 NetconfDevice.SchemaResourcesDTO schemaResourcesDTO =
240 new NetconfDevice.SchemaResourcesDTO(schemaRegistry, schemaContextFactory, new NetconfStateSchemas.NetconfStateSchemasResolverImpl());
242 NetconfDevice device = new NetconfDevice(schemaResourcesDTO, remoteDeviceId, salFacade,
243 processingExecutor.getExecutor(), reconnectOnChangedSchema);
245 return new NetconfConnectorDTO(new NetconfDeviceCommunicator(remoteDeviceId, device), salFacade);
248 public NetconfReconnectingClientConfiguration getClientConfig(final NetconfClientSessionListener listener, NetconfNode node) {
250 //setup default values since default value is not supported yet in mdsal
251 // TODO remove this when mdsal starts supporting default values
252 final long clientConnectionTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null ? DEFAULT_REQUEST_TIMEOUT_MILIS : node.getDefaultRequestTimeoutMillis();
253 final long maxConnectionAttempts = node.getMaxConnectionAttempts() == null ? DEFAULT_MAX_CONNECTION_ATTEMPTS : node.getMaxConnectionAttempts();
254 final int betweenAttemptsTimeoutMillis = node.getBetweenAttemptsTimeoutMillis() == null ? DEFAULT_BETWEEN_ATTEMPTS_TIMEOUT_MILLIS : node.getBetweenAttemptsTimeoutMillis();
255 final BigDecimal sleepFactor = node.getSleepFactor() == null ? DEFAULT_SLEEP_FACTOR : node.getSleepFactor();
257 final InetSocketAddress socketAddress = getSocketAddress(node.getHost(), node.getPort().getValue());
259 final ReconnectStrategyFactory sf = new TimedReconnectStrategyFactory(eventExecutor,
260 maxConnectionAttempts, betweenAttemptsTimeoutMillis, sleepFactor);
261 final ReconnectStrategy strategy = sf.createReconnectStrategy();
263 final AuthenticationHandler authHandler;
264 final Credentials credentials = node.getCredentials();
265 if (credentials instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword) {
266 authHandler = new LoginPassword(
267 ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword) credentials).getUsername(),
268 ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword) credentials).getPassword());
270 throw new IllegalStateException("Only login/password authentification is supported");
273 return NetconfReconnectingClientConfigurationBuilder.create()
274 .withAddress(socketAddress)
275 .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
276 .withReconnectStrategy(strategy)
277 .withAuthHandler(authHandler)
278 .withProtocol(node.isTcpOnly() ?
279 NetconfClientConfiguration.NetconfClientProtocol.TCP :
280 NetconfClientConfiguration.NetconfClientProtocol.SSH)
281 .withConnectStrategyFactory(sf)
282 .withSessionListener(listener)
286 protected abstract RemoteDeviceHandler<NetconfSessionPreferences> createSalFacade(final RemoteDeviceId id, final Broker domBroker, final BindingAwareBroker bindingBroker, long defaultRequestTimeoutMillis);
289 public abstract ConnectionStatusListenerRegistration registerConnectionStatusListener(NodeId node, RemoteDeviceHandler<NetconfSessionPreferences> listener);
292 public void onSessionInitiated(ProviderSession session) {
293 mountPointService = session.getService(DOMMountPointService.class);
297 public Collection<ProviderFunctionality> getProviderFunctionality() {
298 return Collections.emptySet();
301 //TODO this needs to be an util method, since netconf clustering uses this aswell
303 * Determines the Netconf Node Node ID, given the node's instance
306 * @param pathArgument Node's path arument
307 * @return NodeId for the node
309 protected NodeId getNodeId(final PathArgument pathArgument) {
310 if (pathArgument instanceof InstanceIdentifier.IdentifiableItem<?, ?>) {
312 final Identifier key = ((InstanceIdentifier.IdentifiableItem) pathArgument).getKey();
313 if(key instanceof NodeKey) {
314 return ((NodeKey) key).getNodeId();
317 throw new IllegalStateException("Unable to create NodeId from: " + pathArgument);
320 protected static InstanceIdentifier<Topology> createTopologyId(final String topologyId) {
321 final InstanceIdentifier<NetworkTopology> networkTopology = InstanceIdentifier.create(NetworkTopology.class);
322 return networkTopology.child(Topology.class, new TopologyKey(new TopologyId(topologyId)));
325 private InetSocketAddress getSocketAddress(final Host host, int port) {
326 if(host.getDomainName() != null) {
327 return new InetSocketAddress(host.getDomainName().getValue(), port);
329 final IpAddress ipAddress = host.getIpAddress();
330 final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue();
331 return new InetSocketAddress(ip, port);
335 private static final class TimedReconnectStrategyFactory implements ReconnectStrategyFactory {
336 private final Long connectionAttempts;
337 private final EventExecutor executor;
338 private final double sleepFactor;
339 private final int minSleep;
341 TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts, 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);
363 protected static class NetconfConnectorDTO {
365 private final NetconfDeviceCommunicator communicator;
366 private final RemoteDeviceHandler<NetconfSessionPreferences> facade;
368 public NetconfConnectorDTO(final NetconfDeviceCommunicator communicator, final RemoteDeviceHandler<NetconfSessionPreferences> facade) {
369 this.communicator = communicator;
370 this.facade = facade;
373 public NetconfDeviceCommunicator getCommunicator() {
377 public RemoteDeviceHandler<NetconfSessionPreferences> getFacade() {
381 public NetconfClientSessionListener getSessionListener() {