2 * Copyright (c) 2014 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
8 package org.opendaylight.controller.config.yang.md.sal.connector.netconf;
10 import static org.opendaylight.controller.config.api.JmxAttributeValidationException.checkCondition;
11 import static org.opendaylight.controller.config.api.JmxAttributeValidationException.checkNotNull;
13 import com.google.common.base.Optional;
14 import io.netty.util.concurrent.EventExecutor;
16 import java.math.BigDecimal;
17 import java.net.InetSocketAddress;
18 import java.util.HashSet;
19 import java.util.List;
21 import java.util.concurrent.ExecutorService;
22 import java.util.concurrent.Executors;
23 import java.util.concurrent.ScheduledExecutorService;
24 import java.util.concurrent.ThreadFactory;
25 import org.opendaylight.controller.config.api.JmxAttributeValidationException;
26 import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
27 import org.opendaylight.controller.config.threadpool.ThreadPool;
28 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
29 import org.opendaylight.controller.sal.core.api.Broker;
30 import org.opendaylight.netconf.client.NetconfClientDispatcher;
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.LoginPassword;
35 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
36 import org.opendaylight.netconf.sal.connect.netconf.NetconfDevice;
37 import org.opendaylight.netconf.sal.connect.netconf.NetconfStateSchemas;
38 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
39 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
40 import org.opendaylight.netconf.sal.connect.netconf.sal.KeepaliveSalFacade;
41 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceSalFacade;
42 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
43 import org.opendaylight.protocol.framework.ReconnectStrategy;
44 import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
45 import org.opendaylight.protocol.framework.TimedReconnectStrategy;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Host;
47 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
48 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
49 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
50 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
51 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
52 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
53 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
54 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
55 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
56 import org.osgi.framework.BundleContext;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
63 public final class NetconfConnectorModule extends org.opendaylight.controller.config.yang.md.sal.connector.netconf.AbstractNetconfConnectorModule
65 private static final Logger LOG = LoggerFactory.getLogger(NetconfConnectorModule.class);
67 private static FilesystemSchemaSourceCache<YangTextSchemaSource> CACHE = null;
68 //when no topology is defined in connector config, we need to add a default schema repository to mantain backwards compatibility
69 private static SharedSchemaRepository DEFAULT_SCHEMA_REPOSITORY = null;
71 //keep track of already initialized repositories to avoid adding redundant listeners
72 private static final Set<SchemaRepository> INITIALIZED_SCHEMA_REPOSITORIES = new HashSet<>();
74 private BundleContext bundleContext;
75 private Optional<NetconfSessionPreferences> userCapabilities;
76 private SchemaSourceRegistry schemaRegistry;
77 private SchemaContextFactory schemaContextFactory;
79 private Broker domRegistry;
80 private NetconfClientDispatcher clientDispatcher;
81 private BindingAwareBroker bindingRegistry;
82 private ThreadPool processingExecutor;
83 private ScheduledThreadPool keepaliveExecutor;
84 private SharedSchemaRepository sharedSchemaRepository;
85 private EventExecutor eventExecutor;
87 public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
88 super(identifier, dependencyResolver);
91 public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, final NetconfConnectorModule oldModule, final java.lang.AutoCloseable oldInstance) {
92 super(identifier, dependencyResolver, oldModule, oldInstance);
96 protected void customValidation() {
97 checkNotNull(getAddress(), addressJmxAttribute);
98 checkCondition(isHostAddressPresent(getAddress()), "Host address not present in " + getAddress(), addressJmxAttribute);
99 checkNotNull(getPort(), portJmxAttribute);
101 checkNotNull(getConnectionTimeoutMillis(), connectionTimeoutMillisJmxAttribute);
102 checkCondition(getConnectionTimeoutMillis() > 0, "must be > 0", connectionTimeoutMillisJmxAttribute);
104 checkNotNull(getConnectionTimeoutMillis(), defaultRequestTimeoutMillisJmxAttribute);
105 checkCondition(getConnectionTimeoutMillis() > 0, "must be > 0", defaultRequestTimeoutMillisJmxAttribute);
107 checkNotNull(getBetweenAttemptsTimeoutMillis(), betweenAttemptsTimeoutMillisJmxAttribute);
108 checkCondition(getBetweenAttemptsTimeoutMillis() > 0, "must be > 0", betweenAttemptsTimeoutMillisJmxAttribute);
110 // Check username + password in case of ssh
111 if(getTcpOnly() == false) {
112 checkNotNull(getUsername(), usernameJmxAttribute);
113 checkNotNull(getPassword(), passwordJmxAttribute);
116 userCapabilities = getUserCapabilities();
119 private boolean isHostAddressPresent(final Host address) {
120 return address.getDomainName() != null ||
121 address.getIpAddress() != null && (address.getIpAddress().getIpv4Address() != null || address.getIpAddress().getIpv6Address() != null);
125 private static ScheduledExecutorService DEFAULT_KEEPALIVE_EXECUTOR;
128 public java.lang.AutoCloseable createInstance() {
130 final RemoteDeviceId id = new RemoteDeviceId(getIdentifier(), getSocketAddress());
132 final ExecutorService globalProcessingExecutor = processingExecutor.getExecutor();
134 RemoteDeviceHandler<NetconfSessionPreferences> salFacade
135 = new NetconfDeviceSalFacade(id, domRegistry, bindingRegistry, getDefaultRequestTimeoutMillis());
137 final Long keepaliveDelay = getKeepaliveDelay();
138 if (shouldSendKeepalive()) {
139 // Keepalive executor is optional for now and a default instance is supported
140 final ScheduledExecutorService executor = keepaliveExecutor == null ? DEFAULT_KEEPALIVE_EXECUTOR : keepaliveExecutor.getExecutor();
142 salFacade = new KeepaliveSalFacade(id, salFacade, executor, keepaliveDelay);
145 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO =
146 new NetconfDevice.SchemaResourcesDTO(schemaRegistry, schemaContextFactory, new NetconfStateSchemas.NetconfStateSchemasResolverImpl());
148 final NetconfDevice device =
149 new NetconfDevice(schemaResourcesDTO, id, salFacade, globalProcessingExecutor, getReconnectOnChangedSchema());
151 final NetconfDeviceCommunicator listener = userCapabilities.isPresent() ?
152 new NetconfDeviceCommunicator(id, device, userCapabilities.get()) : new NetconfDeviceCommunicator(id, device);
154 if (shouldSendKeepalive()) {
155 ((KeepaliveSalFacade) salFacade).setListener(listener);
158 final NetconfReconnectingClientConfiguration clientConfig = getClientConfig(listener);
159 listener.initializeRemoteConnection(clientDispatcher, clientConfig);
161 return new SalConnectorCloseable(listener, salFacade);
164 private void initDependencies() {
165 domRegistry = getDomRegistryDependency();
166 clientDispatcher = getClientDispatcherDependency();
167 bindingRegistry = getBindingRegistryDependency();
168 processingExecutor = getProcessingExecutorDependency();
169 eventExecutor = getEventExecutorDependency();
171 if(getKeepaliveExecutor() == null) {
172 LOG.warn("Keepalive executor missing. Using default instance for now, the configuration needs to be updated");
174 // Instantiate the default executor, now we know its necessary
175 if(DEFAULT_KEEPALIVE_EXECUTOR == null) {
176 DEFAULT_KEEPALIVE_EXECUTOR = Executors.newScheduledThreadPool(2, new ThreadFactory() {
178 public Thread newThread(final Runnable r) {
179 final Thread thread = new Thread(r);
180 thread.setName("netconf-southound-keepalives-" + thread.getId());
181 thread.setDaemon(true);
187 keepaliveExecutor = getKeepaliveExecutorDependency();
190 if (DEFAULT_SCHEMA_REPOSITORY == null) {
191 DEFAULT_SCHEMA_REPOSITORY = new SharedSchemaRepository("default shared schema repo");
193 initFilesystemSchemaSourceCache(DEFAULT_SCHEMA_REPOSITORY);
196 private void initFilesystemSchemaSourceCache(SharedSchemaRepository repository) {
197 LOG.warn("Schema repository used: {}", repository.getIdentifier());
199 CACHE = new FilesystemSchemaSourceCache<>(repository, YangTextSchemaSource.class, new File("cache/schema"));
201 if (!INITIALIZED_SCHEMA_REPOSITORIES.contains(repository)) {
202 repository.registerSchemaSourceListener(CACHE);
203 repository.registerSchemaSourceListener(TextToASTTransformer.create(repository, repository));
204 INITIALIZED_SCHEMA_REPOSITORIES.add(repository);
206 setSchemaRegistry(repository);
207 setSchemaContextFactory(repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT));
210 private boolean shouldSendKeepalive() {
211 return getKeepaliveDelay() > 0;
214 private Optional<NetconfSessionPreferences> getUserCapabilities() {
215 if(getYangModuleCapabilities() == null) {
216 return Optional.absent();
219 final List<String> capabilities = getYangModuleCapabilities().getCapability();
220 if(capabilities == null || capabilities.isEmpty()) {
221 return Optional.absent();
224 final NetconfSessionPreferences parsedOverrideCapabilities = NetconfSessionPreferences.fromStrings(capabilities);
225 JmxAttributeValidationException.checkCondition(
226 parsedOverrideCapabilities.getNonModuleCaps().isEmpty(),
227 "Capabilities to override can only contain module based capabilities, non-module capabilities will be retrieved from the device," +
228 " configured non-module capabilities: " + parsedOverrideCapabilities.getNonModuleCaps(),
229 yangModuleCapabilitiesJmxAttribute);
231 return Optional.of(parsedOverrideCapabilities);
234 public NetconfReconnectingClientConfiguration getClientConfig(final NetconfDeviceCommunicator listener) {
235 final InetSocketAddress socketAddress = getSocketAddress();
236 final long clientConnectionTimeoutMillis = getConnectionTimeoutMillis();
238 final ReconnectStrategyFactory sf = new TimedReconnectStrategyFactory(eventExecutor,
239 getMaxConnectionAttempts(), getBetweenAttemptsTimeoutMillis(), getSleepFactor());
240 final ReconnectStrategy strategy = sf.createReconnectStrategy();
242 return NetconfReconnectingClientConfigurationBuilder.create()
243 .withAddress(socketAddress)
244 .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
245 .withReconnectStrategy(strategy)
246 .withAuthHandler(new LoginPassword(getUsername(), getPassword()))
247 .withProtocol(getTcpOnly() ?
248 NetconfClientConfiguration.NetconfClientProtocol.TCP :
249 NetconfClientConfiguration.NetconfClientProtocol.SSH)
250 .withConnectStrategyFactory(sf)
251 .withSessionListener(listener)
255 private static final class SalConnectorCloseable implements AutoCloseable {
256 private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
257 private final NetconfDeviceCommunicator listener;
259 public SalConnectorCloseable(final NetconfDeviceCommunicator listener,
260 final RemoteDeviceHandler<NetconfSessionPreferences> salFacade) {
261 this.listener = listener;
262 this.salFacade = salFacade;
266 public void close() {
272 private static final class TimedReconnectStrategyFactory implements ReconnectStrategyFactory {
273 private final Long connectionAttempts;
274 private final EventExecutor executor;
275 private final double sleepFactor;
276 private final int minSleep;
278 TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts, final int minSleep, final BigDecimal sleepFactor) {
279 if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
280 connectionAttempts = maxConnectionAttempts;
282 LOG.trace("Setting {} on {} to infinity", maxConnectionAttemptsJmxAttribute, this);
283 connectionAttempts = null;
286 this.sleepFactor = sleepFactor.doubleValue();
287 this.executor = executor;
288 this.minSleep = minSleep;
292 public ReconnectStrategy createReconnectStrategy() {
293 final Long maxSleep = null;
294 final Long deadline = null;
296 return new TimedReconnectStrategy(executor, minSleep,
297 minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
301 private InetSocketAddress getSocketAddress() {
302 if(getAddress().getDomainName() != null) {
303 return new InetSocketAddress(getAddress().getDomainName().getValue(), getPort().getValue());
305 final IpAddress ipAddress = getAddress().getIpAddress();
306 final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue();
307 return new InetSocketAddress(ip, getPort().getValue());
311 public void setSchemaRegistry(final SchemaSourceRegistry schemaRegistry) {
312 this.schemaRegistry = schemaRegistry;
315 public void setSchemaContextFactory(final SchemaContextFactory schemaContextFactory) {
316 this.schemaContextFactory = schemaContextFactory;