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 com.google.common.base.Strings;
15 import io.netty.util.concurrent.EventExecutor;
17 import java.math.BigDecimal;
18 import java.net.InetSocketAddress;
19 import java.util.HashMap;
20 import java.util.List;
22 import java.util.concurrent.ExecutorService;
23 import java.util.concurrent.Executors;
24 import java.util.concurrent.ScheduledExecutorService;
25 import java.util.concurrent.ThreadFactory;
26 import org.opendaylight.controller.config.api.JmxAttributeValidationException;
27 import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
28 import org.opendaylight.controller.config.threadpool.ThreadPool;
29 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
30 import org.opendaylight.controller.sal.core.api.Broker;
31 import org.opendaylight.netconf.client.NetconfClientDispatcher;
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.LoginPassword;
36 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
37 import org.opendaylight.netconf.sal.connect.netconf.NetconfDevice;
38 import org.opendaylight.netconf.sal.connect.netconf.NetconfStateSchemas;
39 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
40 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
41 import org.opendaylight.netconf.sal.connect.netconf.listener.UserPreferences;
42 import org.opendaylight.netconf.sal.connect.netconf.sal.KeepaliveSalFacade;
43 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceSalFacade;
44 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
45 import org.opendaylight.protocol.framework.ReconnectStrategy;
46 import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
47 import org.opendaylight.protocol.framework.TimedReconnectStrategy;
48 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Host;
49 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
50 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
51 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
52 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
53 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
54 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
55 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
56 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
57 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
58 import org.osgi.framework.BundleContext;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
65 public final class NetconfConnectorModule extends org.opendaylight.controller.config.yang.md.sal.connector.netconf.AbstractNetconfConnectorModule
67 private static final Logger LOG = LoggerFactory.getLogger(NetconfConnectorModule.class);
70 * Filesystem based caches are stored relative to the cache directory.
72 private static final String CACHE_DIRECTORY = "cache";
75 * The default cache directory relative to <code>CACHE_DIRECTORY</code>
77 private static final String DEFAULT_CACHE_DIRECTORY = "schema";
80 * The qualified schema cache directory <code>cache/schema</code>
82 private static final String QUALIFIED_DEFAULT_CACHE_DIRECTORY = CACHE_DIRECTORY + File.separator+ DEFAULT_CACHE_DIRECTORY;
85 * The name for the default schema repository
87 private static final String DEFAULT_SCHEMA_REPOSITORY_NAME = "sal-netconf-connector";
90 * The default schema repository in the case that one is not specified.
92 private static final SharedSchemaRepository DEFAULT_SCHEMA_REPOSITORY =
93 new SharedSchemaRepository(DEFAULT_SCHEMA_REPOSITORY_NAME);
96 * The default <code>FilesystemSchemaSourceCache</code>, which stores cached files in <code>cache/schema</code>.
98 private static final FilesystemSchemaSourceCache<YangTextSchemaSource> DEFAULT_CACHE =
99 new FilesystemSchemaSourceCache<>(DEFAULT_SCHEMA_REPOSITORY, YangTextSchemaSource.class,
100 new File(QUALIFIED_DEFAULT_CACHE_DIRECTORY));
103 * The default factory for creating <code>SchemaContext</code> instances.
105 private static final SchemaContextFactory DEFAULT_SCHEMA_CONTEXT_FACTORY =
106 DEFAULT_SCHEMA_REPOSITORY.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
109 * Keeps track of initialized Schema resources. A Map is maintained in which the key represents the name
110 * of the schema cache directory, and the value is a corresponding <code>SchemaResourcesDTO</code>. The
111 * <code>SchemaResourcesDTO</code> is essentially a container that allows for the extraction of the
112 * <code>SchemaRegistry</code> and <code>SchemaContextFactory</code> which should be used for a particular
113 * Netconf mount. Access to <code>schemaResourcesDTOs</code> should be surrounded by appropriate
114 * synchronization locks.
116 private static volatile Map<String, NetconfDevice.SchemaResourcesDTO> schemaResourcesDTOs = new HashMap<>();
118 // Initializes default constant instances for the case when the default schema repository
119 // directory cache/schema is used.
121 schemaResourcesDTOs.put(DEFAULT_CACHE_DIRECTORY,
122 new NetconfDevice.SchemaResourcesDTO(DEFAULT_SCHEMA_REPOSITORY,
123 DEFAULT_SCHEMA_CONTEXT_FACTORY,
124 new NetconfStateSchemas.NetconfStateSchemasResolverImpl()));
125 DEFAULT_SCHEMA_REPOSITORY.registerSchemaSourceListener(DEFAULT_CACHE);
126 DEFAULT_SCHEMA_REPOSITORY.registerSchemaSourceListener(
127 TextToASTTransformer.create(DEFAULT_SCHEMA_REPOSITORY, DEFAULT_SCHEMA_REPOSITORY));
130 private BundleContext bundleContext;
131 private Optional<NetconfSessionPreferences> userCapabilities;
132 private SchemaSourceRegistry schemaRegistry = DEFAULT_SCHEMA_REPOSITORY;
133 private SchemaContextFactory schemaContextFactory = DEFAULT_SCHEMA_CONTEXT_FACTORY;
135 private Broker domRegistry;
136 private NetconfClientDispatcher clientDispatcher;
137 private BindingAwareBroker bindingRegistry;
138 private ThreadPool processingExecutor;
139 private ScheduledThreadPool keepaliveExecutor;
140 private EventExecutor eventExecutor;
143 * The name associated with the Netconf mount point. This value is passed from <code>NetconfConnectorModuleFactory</code>.
145 private String instanceName;
147 public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
148 super(identifier, dependencyResolver);
151 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) {
152 super(identifier, dependencyResolver, oldModule, oldInstance);
156 protected void customValidation() {
157 checkNotNull(getAddress(), addressJmxAttribute);
158 checkCondition(isHostAddressPresent(getAddress()), "Host address not present in " + getAddress(), addressJmxAttribute);
159 checkNotNull(getPort(), portJmxAttribute);
161 checkNotNull(getConnectionTimeoutMillis(), connectionTimeoutMillisJmxAttribute);
162 checkCondition(getConnectionTimeoutMillis() > 0, "must be > 0", connectionTimeoutMillisJmxAttribute);
164 checkNotNull(getDefaultRequestTimeoutMillis(), defaultRequestTimeoutMillisJmxAttribute);
165 checkCondition(getDefaultRequestTimeoutMillis() > 0, "must be > 0", defaultRequestTimeoutMillisJmxAttribute);
167 checkNotNull(getBetweenAttemptsTimeoutMillis(), betweenAttemptsTimeoutMillisJmxAttribute);
168 checkCondition(getBetweenAttemptsTimeoutMillis() > 0, "must be > 0", betweenAttemptsTimeoutMillisJmxAttribute);
170 // Check username + password in case of ssh
171 if(getTcpOnly() == false) {
172 checkNotNull(getUsername(), usernameJmxAttribute);
173 checkNotNull(getPassword(), passwordJmxAttribute);
176 userCapabilities = getUserCapabilities();
179 private boolean isHostAddressPresent(final Host address) {
180 return address.getDomainName() != null ||
181 address.getIpAddress() != null && (address.getIpAddress().getIpv4Address() != null || address.getIpAddress().getIpv6Address() != null);
185 private static ScheduledExecutorService DEFAULT_KEEPALIVE_EXECUTOR;
188 public java.lang.AutoCloseable createInstance() {
190 final RemoteDeviceId id = new RemoteDeviceId(getIdentifier(), getSocketAddress());
192 final ExecutorService globalProcessingExecutor = processingExecutor.getExecutor();
194 RemoteDeviceHandler<NetconfSessionPreferences> salFacade
195 = new NetconfDeviceSalFacade(id, domRegistry, bindingRegistry);
197 final Long keepaliveDelay = getKeepaliveDelay();
198 if (shouldSendKeepalive()) {
199 // Keepalive executor is optional for now and a default instance is supported
200 final ScheduledExecutorService executor = keepaliveExecutor == null ? DEFAULT_KEEPALIVE_EXECUTOR : keepaliveExecutor.getExecutor();
202 salFacade = new KeepaliveSalFacade(id, salFacade, executor, keepaliveDelay, getDefaultRequestTimeoutMillis());
205 // Setup information related to the SchemaRegistry, SchemaResourceFactory, etc.
206 NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = null;
207 final String moduleSchemaCacheDirectory = getSchemaCacheDirectory();
208 // Only checks to ensure the String is not empty or null; further checks related to directory accessibility and file permissions
209 // are handled during the FilesystemScehamSourceCache initialization.
210 if (!Strings.isNullOrEmpty(moduleSchemaCacheDirectory)) {
211 // If a custom schema cache directory is specified, create the backing DTO; otherwise, the SchemaRegistry and
212 // SchemaContextFactory remain the default values.
213 if (!moduleSchemaCacheDirectory.equals(DEFAULT_CACHE_DIRECTORY)) {
214 // Multiple modules may be created at once; synchronize to avoid issues with data consistency among threads.
215 synchronized(schemaResourcesDTOs) {
216 // Look for the cached DTO to reuse SchemaRegistry and SchemaContextFactory variables if they already exist
217 final NetconfDevice.SchemaResourcesDTO dto =
218 schemaResourcesDTOs.get(moduleSchemaCacheDirectory);
220 schemaResourcesDTO = createSchemaResourcesDTO(moduleSchemaCacheDirectory);
221 schemaRegistry.registerSchemaSourceListener(
222 TextToASTTransformer.create((SchemaRepository) schemaRegistry, schemaRegistry));
223 schemaResourcesDTOs.put(moduleSchemaCacheDirectory, schemaResourcesDTO);
225 setSchemaContextFactory(dto.getSchemaContextFactory());
226 setSchemaRegistry(dto.getSchemaRegistry());
227 schemaResourcesDTO = dto;
230 LOG.info("Netconf connector for device {} will use schema cache directory {} instead of {}",
231 instanceName, moduleSchemaCacheDirectory, DEFAULT_CACHE_DIRECTORY);
234 LOG.warn("schema-cache-directory for {} is null or empty; using the default {}",
235 instanceName, QUALIFIED_DEFAULT_CACHE_DIRECTORY);
238 if (schemaResourcesDTO == null) {
239 schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(schemaRegistry, schemaContextFactory,
240 new NetconfStateSchemas.NetconfStateSchemasResolverImpl());
243 final NetconfDevice device =
244 new NetconfDevice(schemaResourcesDTO, id, salFacade, globalProcessingExecutor, getReconnectOnChangedSchema());
246 final NetconfDeviceCommunicator listener = userCapabilities.isPresent() ?
247 new NetconfDeviceCommunicator(id, device,
248 new UserPreferences(userCapabilities.get(), getYangModuleCapabilities().getOverride())):
249 new NetconfDeviceCommunicator(id, device);
251 if (shouldSendKeepalive()) {
252 ((KeepaliveSalFacade) salFacade).setListener(listener);
255 final NetconfReconnectingClientConfiguration clientConfig = getClientConfig(listener);
256 listener.initializeRemoteConnection(clientDispatcher, clientConfig);
258 return new SalConnectorCloseable(listener, salFacade);
262 * Creates the backing Schema classes for a particular directory.
264 * @param moduleSchemaCacheDirectory The string directory relative to "cache"
265 * @return A DTO containing the Schema classes for the Netconf mount.
267 private NetconfDevice.SchemaResourcesDTO createSchemaResourcesDTO(final String moduleSchemaCacheDirectory) {
268 final SharedSchemaRepository repository = new SharedSchemaRepository(instanceName);
269 final SchemaContextFactory schemaContextFactory
270 = repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
271 setSchemaRegistry(repository);
272 setSchemaContextFactory(schemaContextFactory);
273 final FilesystemSchemaSourceCache<YangTextSchemaSource> deviceCache =
274 createDeviceFilesystemCache(moduleSchemaCacheDirectory);
275 repository.registerSchemaSourceListener(deviceCache);
276 return new NetconfDevice.SchemaResourcesDTO(repository, schemaContextFactory,
277 new NetconfStateSchemas.NetconfStateSchemasResolverImpl());
281 * Creates a <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory.
283 * @param schemaCacheDirectory The custom cache directory relative to "cache"
284 * @return A <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory
286 private FilesystemSchemaSourceCache<YangTextSchemaSource> createDeviceFilesystemCache(final String schemaCacheDirectory) {
287 final String relativeSchemaCacheDirectory = CACHE_DIRECTORY + File.separator + schemaCacheDirectory;
288 return new FilesystemSchemaSourceCache<>(schemaRegistry, YangTextSchemaSource.class, new File(relativeSchemaCacheDirectory));
291 private void initDependencies() {
292 domRegistry = getDomRegistryDependency();
293 clientDispatcher = getClientDispatcherDependency();
294 bindingRegistry = getBindingRegistryDependency();
295 processingExecutor = getProcessingExecutorDependency();
296 eventExecutor = getEventExecutorDependency();
298 if(getKeepaliveExecutor() == null) {
299 LOG.warn("Keepalive executor missing. Using default instance for now, the configuration needs to be updated");
301 // Instantiate the default executor, now we know its necessary
302 if(DEFAULT_KEEPALIVE_EXECUTOR == null) {
303 DEFAULT_KEEPALIVE_EXECUTOR = Executors.newScheduledThreadPool(2, new ThreadFactory() {
305 public Thread newThread(final Runnable r) {
306 final Thread thread = new Thread(r);
307 thread.setName("netconf-southound-keepalives-" + thread.getId());
308 thread.setDaemon(true);
314 keepaliveExecutor = getKeepaliveExecutorDependency();
318 private boolean shouldSendKeepalive() {
319 return getKeepaliveDelay() > 0;
322 private Optional<NetconfSessionPreferences> getUserCapabilities() {
323 if(getYangModuleCapabilities() == null) {
324 return Optional.absent();
327 final List<String> capabilities = getYangModuleCapabilities().getCapability();
328 if(capabilities == null || capabilities.isEmpty()) {
329 return Optional.absent();
332 final NetconfSessionPreferences parsedOverrideCapabilities = NetconfSessionPreferences.fromStrings(capabilities);
333 JmxAttributeValidationException.checkCondition(
334 parsedOverrideCapabilities.getNonModuleCaps().isEmpty(),
335 "Capabilities to override can only contain module based capabilities, non-module capabilities will be retrieved from the device," +
336 " configured non-module capabilities: " + parsedOverrideCapabilities.getNonModuleCaps(),
337 yangModuleCapabilitiesJmxAttribute);
339 return Optional.of(parsedOverrideCapabilities);
342 public NetconfReconnectingClientConfiguration getClientConfig(final NetconfDeviceCommunicator listener) {
343 final InetSocketAddress socketAddress = getSocketAddress();
344 final long clientConnectionTimeoutMillis = getConnectionTimeoutMillis();
346 final ReconnectStrategyFactory sf = new TimedReconnectStrategyFactory(eventExecutor,
347 getMaxConnectionAttempts(), getBetweenAttemptsTimeoutMillis(), getSleepFactor());
348 final ReconnectStrategy strategy = sf.createReconnectStrategy();
350 return NetconfReconnectingClientConfigurationBuilder.create()
351 .withAddress(socketAddress)
352 .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
353 .withReconnectStrategy(strategy)
354 .withAuthHandler(new LoginPassword(getUsername(), getPassword()))
355 .withProtocol(getTcpOnly() ?
356 NetconfClientConfiguration.NetconfClientProtocol.TCP :
357 NetconfClientConfiguration.NetconfClientProtocol.SSH)
358 .withConnectStrategyFactory(sf)
359 .withSessionListener(listener)
363 private static final class SalConnectorCloseable implements AutoCloseable {
364 private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
365 private final NetconfDeviceCommunicator listener;
367 public SalConnectorCloseable(final NetconfDeviceCommunicator listener,
368 final RemoteDeviceHandler<NetconfSessionPreferences> salFacade) {
369 this.listener = listener;
370 this.salFacade = salFacade;
374 public void close() {
380 private static final class TimedReconnectStrategyFactory implements ReconnectStrategyFactory {
381 private final Long connectionAttempts;
382 private final EventExecutor executor;
383 private final double sleepFactor;
384 private final int minSleep;
386 TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts, final int minSleep, final BigDecimal sleepFactor) {
387 if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
388 connectionAttempts = maxConnectionAttempts;
390 LOG.trace("Setting {} on {} to infinity", maxConnectionAttemptsJmxAttribute, this);
391 connectionAttempts = null;
394 this.sleepFactor = sleepFactor.doubleValue();
395 this.executor = executor;
396 this.minSleep = minSleep;
400 public ReconnectStrategy createReconnectStrategy() {
401 final Long maxSleep = null;
402 final Long deadline = null;
404 return new TimedReconnectStrategy(executor, minSleep,
405 minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
409 private InetSocketAddress getSocketAddress() {
410 if(getAddress().getDomainName() != null) {
411 return new InetSocketAddress(getAddress().getDomainName().getValue(), getPort().getValue());
413 final IpAddress ipAddress = getAddress().getIpAddress();
414 final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue();
415 return new InetSocketAddress(ip, getPort().getValue());
419 public void setSchemaRegistry(final SchemaSourceRegistry schemaRegistry) {
420 this.schemaRegistry = schemaRegistry;
423 public void setSchemaContextFactory(final SchemaContextFactory schemaContextFactory) {
424 this.schemaContextFactory = schemaContextFactory;
427 public void setInstanceName(final String instanceName) {
428 this.instanceName = instanceName;