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 com.google.common.collect.Lists;
16 import io.netty.util.concurrent.EventExecutor;
18 import java.math.BigDecimal;
19 import java.net.InetSocketAddress;
21 import java.util.HashMap;
22 import java.util.List;
24 import java.util.concurrent.ExecutorService;
25 import java.util.concurrent.Executors;
26 import java.util.concurrent.ScheduledExecutorService;
27 import java.util.concurrent.ThreadFactory;
28 import org.opendaylight.controller.config.api.JmxAttributeValidationException;
29 import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
30 import org.opendaylight.controller.config.threadpool.ThreadPool;
31 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
32 import org.opendaylight.controller.sal.core.api.Broker;
33 import org.opendaylight.netconf.client.NetconfClientDispatcher;
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.LoginPassword;
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.NetconfStateSchemas;
43 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
44 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
45 import org.opendaylight.netconf.sal.connect.netconf.listener.UserPreferences;
46 import org.opendaylight.netconf.sal.connect.netconf.sal.KeepaliveSalFacade;
47 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceSalFacade;
48 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
49 import org.opendaylight.netconf.sal.connect.netconf.schema.YangLibrarySchemaYangSourceProvider;
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.yangtools.yang.common.QName;
56 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
57 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
58 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
59 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
60 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
61 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
62 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
63 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
64 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
65 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
66 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
67 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
68 import org.osgi.framework.BundleContext;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
75 public final class NetconfConnectorModule extends org.opendaylight.controller.config.yang.md.sal.connector.netconf.AbstractNetconfConnectorModule
77 private static final Logger LOG = LoggerFactory.getLogger(NetconfConnectorModule.class);
80 * Filesystem based caches are stored relative to the cache directory.
82 private static final String CACHE_DIRECTORY = "cache";
85 * The default cache directory relative to <code>CACHE_DIRECTORY</code>
87 private static final String DEFAULT_CACHE_DIRECTORY = "schema";
90 * The qualified schema cache directory <code>cache/schema</code>
92 private static final String QUALIFIED_DEFAULT_CACHE_DIRECTORY = CACHE_DIRECTORY + File.separator+ DEFAULT_CACHE_DIRECTORY;
95 * The name for the default schema repository
97 private static final String DEFAULT_SCHEMA_REPOSITORY_NAME = "sal-netconf-connector";
100 * The default schema repository in the case that one is not specified.
102 private static final SharedSchemaRepository DEFAULT_SCHEMA_REPOSITORY =
103 new SharedSchemaRepository(DEFAULT_SCHEMA_REPOSITORY_NAME);
106 * The default <code>FilesystemSchemaSourceCache</code>, which stores cached files in <code>cache/schema</code>.
108 private static final FilesystemSchemaSourceCache<YangTextSchemaSource> DEFAULT_CACHE =
109 new FilesystemSchemaSourceCache<>(DEFAULT_SCHEMA_REPOSITORY, YangTextSchemaSource.class,
110 new File(QUALIFIED_DEFAULT_CACHE_DIRECTORY));
113 * The default factory for creating <code>SchemaContext</code> instances.
115 private static final SchemaContextFactory DEFAULT_SCHEMA_CONTEXT_FACTORY =
116 DEFAULT_SCHEMA_REPOSITORY.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
118 private static final int LOCAL_IO_FALLBACK_COST = PotentialSchemaSource.Costs.LOCAL_IO.getValue() + 1;
121 * Keeps track of initialized Schema resources. A Map is maintained in which the key represents the name
122 * of the schema cache directory, and the value is a corresponding <code>SchemaResourcesDTO</code>. The
123 * <code>SchemaResourcesDTO</code> is essentially a container that allows for the extraction of the
124 * <code>SchemaRegistry</code> and <code>SchemaContextFactory</code> which should be used for a particular
125 * Netconf mount. Access to <code>schemaResourcesDTOs</code> should be surrounded by appropriate
126 * synchronization locks.
128 private static volatile Map<String, NetconfDevice.SchemaResourcesDTO> schemaResourcesDTOs = new HashMap<>();
130 // Initializes default constant instances for the case when the default schema repository
131 // directory cache/schema is used.
133 schemaResourcesDTOs.put(DEFAULT_CACHE_DIRECTORY,
134 new NetconfDevice.SchemaResourcesDTO(DEFAULT_SCHEMA_REPOSITORY,
135 DEFAULT_SCHEMA_CONTEXT_FACTORY,
136 new NetconfStateSchemas.NetconfStateSchemasResolverImpl()));
137 DEFAULT_SCHEMA_REPOSITORY.registerSchemaSourceListener(DEFAULT_CACHE);
138 DEFAULT_SCHEMA_REPOSITORY.registerSchemaSourceListener(
139 TextToASTTransformer.create(DEFAULT_SCHEMA_REPOSITORY, DEFAULT_SCHEMA_REPOSITORY));
142 private BundleContext bundleContext;
143 private Optional<NetconfSessionPreferences> userCapabilities;
144 private SchemaSourceRegistry schemaRegistry = DEFAULT_SCHEMA_REPOSITORY;
145 private SchemaContextFactory schemaContextFactory = DEFAULT_SCHEMA_CONTEXT_FACTORY;
147 private Broker domRegistry;
148 private NetconfClientDispatcher clientDispatcher;
149 private BindingAwareBroker bindingRegistry;
150 private ThreadPool processingExecutor;
151 private ScheduledThreadPool keepaliveExecutor;
152 private EventExecutor eventExecutor;
155 * The name associated with the Netconf mount point. This value is passed from <code>NetconfConnectorModuleFactory</code>.
157 private String instanceName;
159 public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
160 super(identifier, dependencyResolver);
163 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) {
164 super(identifier, dependencyResolver, oldModule, oldInstance);
168 protected void customValidation() {
169 checkNotNull(getAddress(), addressJmxAttribute);
170 checkCondition(isHostAddressPresent(getAddress()), "Host address not present in " + getAddress(), addressJmxAttribute);
171 checkNotNull(getPort(), portJmxAttribute);
173 checkNotNull(getConnectionTimeoutMillis(), connectionTimeoutMillisJmxAttribute);
174 checkCondition(getConnectionTimeoutMillis() > 0, "must be > 0", connectionTimeoutMillisJmxAttribute);
176 checkNotNull(getDefaultRequestTimeoutMillis(), defaultRequestTimeoutMillisJmxAttribute);
177 checkCondition(getDefaultRequestTimeoutMillis() > 0, "must be > 0", defaultRequestTimeoutMillisJmxAttribute);
179 checkNotNull(getBetweenAttemptsTimeoutMillis(), betweenAttemptsTimeoutMillisJmxAttribute);
180 checkCondition(getBetweenAttemptsTimeoutMillis() > 0, "must be > 0", betweenAttemptsTimeoutMillisJmxAttribute);
182 // Check username + password in case of ssh
183 if(getTcpOnly() == false) {
184 checkNotNull(getUsername(), usernameJmxAttribute);
185 checkNotNull(getPassword(), passwordJmxAttribute);
188 userCapabilities = getUserCapabilities();
191 private boolean isHostAddressPresent(final Host address) {
192 return address.getDomainName() != null ||
193 address.getIpAddress() != null && (address.getIpAddress().getIpv4Address() != null || address.getIpAddress().getIpv6Address() != null);
197 private static ScheduledExecutorService DEFAULT_KEEPALIVE_EXECUTOR;
200 public java.lang.AutoCloseable createInstance() {
202 final RemoteDeviceId id = new RemoteDeviceId(getIdentifier(), getSocketAddress());
204 final ExecutorService globalProcessingExecutor = processingExecutor.getExecutor();
206 RemoteDeviceHandler<NetconfSessionPreferences> salFacade
207 = new NetconfDeviceSalFacade(id, domRegistry, bindingRegistry);
209 final Long keepaliveDelay = getKeepaliveDelay();
210 if (shouldSendKeepalive()) {
211 // Keepalive executor is optional for now and a default instance is supported
212 final ScheduledExecutorService executor = keepaliveExecutor == null ? DEFAULT_KEEPALIVE_EXECUTOR : keepaliveExecutor.getExecutor();
214 salFacade = new KeepaliveSalFacade(id, salFacade, executor, keepaliveDelay, getDefaultRequestTimeoutMillis());
217 // Setup information related to the SchemaRegistry, SchemaResourceFactory, etc.
218 NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = null;
219 final String moduleSchemaCacheDirectory = getSchemaCacheDirectory();
220 // Only checks to ensure the String is not empty or null; further checks related to directory accessibility and file permissions
221 // are handled during the FilesystemSchemaSourceCache initialization.
222 if (!Strings.isNullOrEmpty(moduleSchemaCacheDirectory)) {
223 // If a custom schema cache directory is specified, create the backing DTO; otherwise, the SchemaRegistry and
224 // SchemaContextFactory remain the default values.
225 if (!moduleSchemaCacheDirectory.equals(DEFAULT_CACHE_DIRECTORY)) {
226 // Multiple modules may be created at once; synchronize to avoid issues with data consistency among threads.
227 synchronized(schemaResourcesDTOs) {
228 // Look for the cached DTO to reuse SchemaRegistry and SchemaContextFactory variables if they already exist
229 final NetconfDevice.SchemaResourcesDTO dto =
230 schemaResourcesDTOs.get(moduleSchemaCacheDirectory);
232 schemaResourcesDTO = createSchemaResourcesDTO(moduleSchemaCacheDirectory);
233 schemaRegistry.registerSchemaSourceListener(
234 TextToASTTransformer.create((SchemaRepository) schemaRegistry, schemaRegistry));
235 schemaResourcesDTOs.put(moduleSchemaCacheDirectory, schemaResourcesDTO);
237 setSchemaContextFactory(dto.getSchemaContextFactory());
238 setSchemaRegistry(dto.getSchemaRegistry());
239 schemaResourcesDTO = dto;
241 if (userCapabilities.isPresent()) {
242 for (QName qname : userCapabilities.get().getModuleBasedCaps()) {
243 final SourceIdentifier sourceIdentifier = RevisionSourceIdentifier
244 .create(qname.getLocalName(), qname.getFormattedRevision());
245 dto.getSchemaRegistry().registerSchemaSource(DEFAULT_CACHE, PotentialSchemaSource
246 .create(sourceIdentifier, YangTextSchemaSource.class, LOCAL_IO_FALLBACK_COST));
250 LOG.info("Netconf connector for device {} will use schema cache directory {} instead of {}",
251 instanceName, moduleSchemaCacheDirectory, DEFAULT_CACHE_DIRECTORY);
254 LOG.warn("schema-cache-directory for {} is null or empty; using the default {}",
255 instanceName, QUALIFIED_DEFAULT_CACHE_DIRECTORY);
258 // pre register yang library sources as fallback schemas to schema registry
259 List<SchemaSourceRegistration<YangTextSchemaSource>> registeredYangLibSources = Lists.newArrayList();
260 if (getYangLibrary() != null) {
261 final String yangLibURL = getYangLibrary().getYangLibraryUrl().getValue();
262 final String yangLibUsername = getYangLibrary().getUsername();
263 final String yangLigPassword = getYangLibrary().getPassword();
265 LibraryModulesSchemas libraryModulesSchemas;
266 if(yangLibURL != null) {
267 if(yangLibUsername != null && yangLigPassword != null) {
268 libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL, yangLibUsername, yangLigPassword);
270 libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL);
273 for (Map.Entry<SourceIdentifier, URL> sourceIdentifierURLEntry : libraryModulesSchemas.getAvailableModels().entrySet()) {
274 registeredYangLibSources.
275 add(schemaRegistry.registerSchemaSource(
276 new YangLibrarySchemaYangSourceProvider(id, libraryModulesSchemas.getAvailableModels()),
277 PotentialSchemaSource
278 .create(sourceIdentifierURLEntry.getKey(), YangTextSchemaSource.class,
279 PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
284 if (schemaResourcesDTO == null) {
285 schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(schemaRegistry, schemaContextFactory,
286 new NetconfStateSchemas.NetconfStateSchemasResolverImpl());
289 final NetconfDevice device = new NetconfDeviceBuilder()
290 .setReconnectOnSchemasChange(getReconnectOnChangedSchema())
291 .setSchemaResourcesDTO(schemaResourcesDTO)
292 .setGlobalProcessingExecutor(globalProcessingExecutor)
294 .setSalFacade(salFacade)
297 final NetconfDeviceCommunicator listener = userCapabilities.isPresent() ?
298 new NetconfDeviceCommunicator(id, device,
299 new UserPreferences(userCapabilities.get(), getYangModuleCapabilities().getOverride())):
300 new NetconfDeviceCommunicator(id, device);
302 if (shouldSendKeepalive()) {
303 ((KeepaliveSalFacade) salFacade).setListener(listener);
306 final NetconfReconnectingClientConfiguration clientConfig = getClientConfig(listener);
307 listener.initializeRemoteConnection(clientDispatcher, clientConfig);
309 return new SalConnectorCloseable(listener, salFacade, registeredYangLibSources);
313 * Creates the backing Schema classes for a particular directory.
315 * @param moduleSchemaCacheDirectory The string directory relative to "cache"
316 * @return A DTO containing the Schema classes for the Netconf mount.
318 private NetconfDevice.SchemaResourcesDTO createSchemaResourcesDTO(final String moduleSchemaCacheDirectory) {
319 final SharedSchemaRepository repository = new SharedSchemaRepository(instanceName);
320 final SchemaContextFactory schemaContextFactory
321 = repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
322 setSchemaRegistry(repository);
323 setSchemaContextFactory(schemaContextFactory);
324 final FilesystemSchemaSourceCache<YangTextSchemaSource> deviceCache =
325 createDeviceFilesystemCache(moduleSchemaCacheDirectory);
326 repository.registerSchemaSourceListener(deviceCache);
327 return new NetconfDevice.SchemaResourcesDTO(repository, schemaContextFactory,
328 new NetconfStateSchemas.NetconfStateSchemasResolverImpl());
332 * Creates a <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory.
334 * @param schemaCacheDirectory The custom cache directory relative to "cache"
335 * @return A <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory
337 private FilesystemSchemaSourceCache<YangTextSchemaSource> createDeviceFilesystemCache(final String schemaCacheDirectory) {
338 final String relativeSchemaCacheDirectory = CACHE_DIRECTORY + File.separator + schemaCacheDirectory;
339 return new FilesystemSchemaSourceCache<>(schemaRegistry, YangTextSchemaSource.class, new File(relativeSchemaCacheDirectory));
342 private void initDependencies() {
343 domRegistry = getDomRegistryDependency();
344 clientDispatcher = getClientDispatcherDependency();
345 bindingRegistry = getBindingRegistryDependency();
346 processingExecutor = getProcessingExecutorDependency();
347 eventExecutor = getEventExecutorDependency();
349 if(getKeepaliveExecutor() == null) {
350 LOG.warn("Keepalive executor missing. Using default instance for now, the configuration needs to be updated");
352 // Instantiate the default executor, now we know its necessary
353 if(DEFAULT_KEEPALIVE_EXECUTOR == null) {
354 DEFAULT_KEEPALIVE_EXECUTOR = Executors.newScheduledThreadPool(2, new ThreadFactory() {
356 public Thread newThread(final Runnable r) {
357 final Thread thread = new Thread(r);
358 thread.setName("netconf-southound-keepalives-" + thread.getId());
359 thread.setDaemon(true);
365 keepaliveExecutor = getKeepaliveExecutorDependency();
369 private boolean shouldSendKeepalive() {
370 return getKeepaliveDelay() > 0;
373 private Optional<NetconfSessionPreferences> getUserCapabilities() {
374 if(getYangModuleCapabilities() == null) {
375 return Optional.absent();
378 final List<String> capabilities = getYangModuleCapabilities().getCapability();
379 if(capabilities == null || capabilities.isEmpty()) {
380 return Optional.absent();
383 final NetconfSessionPreferences parsedOverrideCapabilities = NetconfSessionPreferences.fromStrings(capabilities);
384 JmxAttributeValidationException.checkCondition(
385 parsedOverrideCapabilities.getNonModuleCaps().isEmpty(),
386 "Capabilities to override can only contain module based capabilities, non-module capabilities will be retrieved from the device," +
387 " configured non-module capabilities: " + parsedOverrideCapabilities.getNonModuleCaps(),
388 yangModuleCapabilitiesJmxAttribute);
390 return Optional.of(parsedOverrideCapabilities);
393 public NetconfReconnectingClientConfiguration getClientConfig(final NetconfDeviceCommunicator listener) {
394 final InetSocketAddress socketAddress = getSocketAddress();
395 final long clientConnectionTimeoutMillis = getConnectionTimeoutMillis();
397 final ReconnectStrategyFactory sf = new TimedReconnectStrategyFactory(eventExecutor,
398 getMaxConnectionAttempts(), getBetweenAttemptsTimeoutMillis(), getSleepFactor());
399 final ReconnectStrategy strategy = sf.createReconnectStrategy();
401 return NetconfReconnectingClientConfigurationBuilder.create()
402 .withAddress(socketAddress)
403 .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
404 .withReconnectStrategy(strategy)
405 .withAuthHandler(new LoginPassword(getUsername(), getPassword()))
406 .withProtocol(getTcpOnly() ?
407 NetconfClientConfiguration.NetconfClientProtocol.TCP :
408 NetconfClientConfiguration.NetconfClientProtocol.SSH)
409 .withConnectStrategyFactory(sf)
410 .withSessionListener(listener)
414 private static final class SalConnectorCloseable implements AutoCloseable {
415 private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
416 private final List<SchemaSourceRegistration<YangTextSchemaSource>> registeredYangLibSources;
417 private final NetconfDeviceCommunicator listener;
419 public SalConnectorCloseable(final NetconfDeviceCommunicator listener,
420 final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
421 final List<SchemaSourceRegistration<YangTextSchemaSource>> registeredYangLibSources) {
422 this.listener = listener;
423 this.salFacade = salFacade;
424 this.registeredYangLibSources = registeredYangLibSources;
428 public void close() {
429 for (SchemaSourceRegistration<YangTextSchemaSource> registeredYangLibSource : registeredYangLibSources) {
430 registeredYangLibSource.close();
437 private static final class TimedReconnectStrategyFactory implements ReconnectStrategyFactory {
438 private final Long connectionAttempts;
439 private final EventExecutor executor;
440 private final double sleepFactor;
441 private final int minSleep;
443 TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts, final int minSleep, final BigDecimal sleepFactor) {
444 if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
445 connectionAttempts = maxConnectionAttempts;
447 LOG.trace("Setting {} on {} to infinity", maxConnectionAttemptsJmxAttribute, this);
448 connectionAttempts = null;
451 this.sleepFactor = sleepFactor.doubleValue();
452 this.executor = executor;
453 this.minSleep = minSleep;
457 public ReconnectStrategy createReconnectStrategy() {
458 final Long maxSleep = null;
459 final Long deadline = null;
461 return new TimedReconnectStrategy(executor, minSleep,
462 minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
466 private InetSocketAddress getSocketAddress() {
467 if(getAddress().getDomainName() != null) {
468 return new InetSocketAddress(getAddress().getDomainName().getValue(), getPort().getValue());
470 final IpAddress ipAddress = getAddress().getIpAddress();
471 final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue();
472 return new InetSocketAddress(ip, getPort().getValue());
476 public void setSchemaRegistry(final SchemaSourceRegistry schemaRegistry) {
477 this.schemaRegistry = schemaRegistry;
480 public void setSchemaContextFactory(final SchemaContextFactory schemaContextFactory) {
481 this.schemaContextFactory = schemaContextFactory;
484 public void setInstanceName(final String instanceName) {
485 this.instanceName = instanceName;