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.List;
20 import java.util.concurrent.ExecutorService;
21 import java.util.concurrent.Executors;
22 import java.util.concurrent.ScheduledExecutorService;
23 import java.util.concurrent.ThreadFactory;
24 import org.opendaylight.controller.config.api.JmxAttributeValidationException;
25 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
26 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
27 import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfiguration;
28 import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder;
29 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.LoginPassword;
30 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
31 import org.opendaylight.controller.sal.connect.api.RemoteDeviceHandler;
32 import org.opendaylight.controller.sal.connect.netconf.NetconfDevice;
33 import org.opendaylight.controller.sal.connect.netconf.NetconfStateSchemas;
34 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator;
35 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionPreferences;
36 import org.opendaylight.controller.sal.connect.netconf.sal.KeepaliveSalFacade;
37 import org.opendaylight.controller.sal.connect.netconf.sal.NetconfDeviceSalFacade;
38 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
39 import org.opendaylight.controller.sal.core.api.Broker;
40 import org.opendaylight.protocol.framework.ReconnectStrategy;
41 import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
42 import org.opendaylight.protocol.framework.TimedReconnectStrategy;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Host;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
45 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
46 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
47 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
48 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
49 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
50 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
51 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
52 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
53 import org.osgi.framework.BundleContext;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
60 public final class NetconfConnectorModule extends org.opendaylight.controller.config.yang.md.sal.connector.netconf.AbstractNetconfConnectorModule
62 private static final Logger logger = LoggerFactory.getLogger(NetconfConnectorModule.class);
65 * Filesystem based caches are stored relative to the cache directory.
67 private static final String CACHE_DIRECTORY = "cache";
70 * The default cache directory relative to <code>CACHE_DIRECTORY</code>
72 private static final String DEFAULT_CACHE_DIRECTORY = "schema";
74 private BundleContext bundleContext;
75 private Optional<NetconfSessionPreferences> userCapabilities;
76 private SchemaSourceRegistry schemaRegistry;
77 private SchemaContextFactory schemaContextFactory;
78 private String instanceName;
80 public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
81 super(identifier, dependencyResolver);
84 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) {
85 super(identifier, dependencyResolver, oldModule, oldInstance);
89 protected void customValidation() {
90 checkNotNull(getAddress(), addressJmxAttribute);
91 checkCondition(isHostAddressPresent(getAddress()), "Host address not present in " + getAddress(), addressJmxAttribute);
92 checkNotNull(getPort(), portJmxAttribute);
93 checkNotNull(getDomRegistry(), portJmxAttribute);
94 checkNotNull(getDomRegistry(), domRegistryJmxAttribute);
96 checkNotNull(getConnectionTimeoutMillis(), connectionTimeoutMillisJmxAttribute);
97 checkCondition(getConnectionTimeoutMillis() > 0, "must be > 0", connectionTimeoutMillisJmxAttribute);
99 checkNotNull(getDefaultRequestTimeoutMillis(), defaultRequestTimeoutMillisJmxAttribute);
100 checkCondition(getDefaultRequestTimeoutMillis() > 0, "must be > 0", defaultRequestTimeoutMillisJmxAttribute);
102 checkNotNull(getBetweenAttemptsTimeoutMillis(), betweenAttemptsTimeoutMillisJmxAttribute);
103 checkCondition(getBetweenAttemptsTimeoutMillis() > 0, "must be > 0", betweenAttemptsTimeoutMillisJmxAttribute);
105 checkNotNull(getClientDispatcher(), clientDispatcherJmxAttribute);
106 checkNotNull(getBindingRegistry(), bindingRegistryJmxAttribute);
107 checkNotNull(getProcessingExecutor(), processingExecutorJmxAttribute);
109 // Check username + password in case of ssh
110 if(getTcpOnly() == false) {
111 checkNotNull(getUsername(), usernameJmxAttribute);
112 checkNotNull(getPassword(), passwordJmxAttribute);
115 userCapabilities = getUserCapabilities();
117 if(getKeepaliveExecutor() == null) {
118 logger.warn("Keepalive executor missing. Using default instance for now, the configuration needs to be updated");
120 // Instantiate the default executor, now we know its necessary
121 if(DEFAULT_KEEPALIVE_EXECUTOR == null) {
122 DEFAULT_KEEPALIVE_EXECUTOR = Executors.newScheduledThreadPool(2, new ThreadFactory() {
124 public Thread newThread(final Runnable r) {
125 final Thread thread = new Thread(r);
126 thread.setName("netconf-southound-keepalives-" + thread.getId());
127 thread.setDaemon(true);
135 private boolean isHostAddressPresent(final Host address) {
136 return address.getDomainName() != null ||
137 address.getIpAddress() != null && (address.getIpAddress().getIpv4Address() != null || address.getIpAddress().getIpv6Address() != null);
141 private static ScheduledExecutorService DEFAULT_KEEPALIVE_EXECUTOR;
144 public java.lang.AutoCloseable createInstance() {
145 final RemoteDeviceId id = new RemoteDeviceId(getIdentifier(), getSocketAddress());
147 final ExecutorService globalProcessingExecutor = getProcessingExecutorDependency().getExecutor();
149 final Broker domBroker = getDomRegistryDependency();
150 final BindingAwareBroker bindingBroker = getBindingRegistryDependency();
152 RemoteDeviceHandler<NetconfSessionPreferences> salFacade
153 = new NetconfDeviceSalFacade(id, domBroker, bindingBroker, bundleContext, getDefaultRequestTimeoutMillis());
155 final Long keepaliveDelay = getKeepaliveDelay();
156 if(shouldSendKeepalive()) {
157 // Keepalive executor is optional for now and a default instance is supported
158 final ScheduledExecutorService executor = getKeepaliveExecutor() == null ?
159 DEFAULT_KEEPALIVE_EXECUTOR : getKeepaliveExecutorDependency().getExecutor();
160 salFacade = new KeepaliveSalFacade(id, salFacade, executor, keepaliveDelay);
163 final String moduleSchemaCacheDirectory = getSchemaCacheDirectory();
164 // If a custom schema cache directory is specified, then create the backing Repository,
165 // SchemaContextFactory and FilesystemSchemaSourceCache. If the default is specified,
166 // the the defaults are used from NetconfConnectorModuleFactory.
167 if (!Strings.isNullOrEmpty(moduleSchemaCacheDirectory) &&
168 !moduleSchemaCacheDirectory.equals(DEFAULT_CACHE_DIRECTORY)) {
170 final SharedSchemaRepository repository = new SharedSchemaRepository(instanceName);
171 final SchemaContextFactory schemaContextFactory
172 = repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
173 setSchemaRegistry(repository);
174 setSchemaContextFactory(schemaContextFactory);
176 final FilesystemSchemaSourceCache<YangTextSchemaSource> deviceCache =
177 createDeviceFilesystemCache(moduleSchemaCacheDirectory);
178 repository.registerSchemaSourceListener(deviceCache);
179 logger.info("Netconf connector for device {} will use schema cache directory {} instead of {}",
180 instanceName, moduleSchemaCacheDirectory, DEFAULT_CACHE_DIRECTORY);
183 schemaRegistry.registerSchemaSourceListener(
184 TextToASTTransformer.create((SchemaRepository) schemaRegistry, schemaRegistry));
186 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO =
187 new NetconfDevice.SchemaResourcesDTO(this.schemaRegistry, this.schemaContextFactory, new NetconfStateSchemas.NetconfStateSchemasResolverImpl());
189 final NetconfDevice device =
190 new NetconfDevice(schemaResourcesDTO, id, salFacade, globalProcessingExecutor, getReconnectOnChangedSchema());
192 final NetconfDeviceCommunicator listener = userCapabilities.isPresent() ?
193 new NetconfDeviceCommunicator(id, device, userCapabilities.get()) : new NetconfDeviceCommunicator(id, device);
195 if(shouldSendKeepalive()) {
196 ((KeepaliveSalFacade) salFacade).setListener(listener);
199 final NetconfReconnectingClientConfiguration clientConfig = getClientConfig(listener);
200 final NetconfClientDispatcher dispatcher = getClientDispatcherDependency();
202 listener.initializeRemoteConnection(dispatcher, clientConfig);
204 return new SalConnectorCloseable(listener, salFacade);
208 * Creates a <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory.
210 * @param schemaCacheDirectory The custom cache directory relative to "cache"
211 * @return A <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory
213 private FilesystemSchemaSourceCache<YangTextSchemaSource> createDeviceFilesystemCache(final String schemaCacheDirectory) {
214 final String relativeSchemaCacheDirectory = CACHE_DIRECTORY + File.separator + schemaCacheDirectory;
215 return new FilesystemSchemaSourceCache<>(schemaRegistry, YangTextSchemaSource.class, new File(relativeSchemaCacheDirectory));
218 private boolean shouldSendKeepalive() {
219 return getKeepaliveDelay() > 0;
222 private Optional<NetconfSessionPreferences> getUserCapabilities() {
223 if(getYangModuleCapabilities() == null) {
224 return Optional.absent();
227 final List<String> capabilities = getYangModuleCapabilities().getCapability();
228 if(capabilities == null || capabilities.isEmpty()) {
229 return Optional.absent();
232 final NetconfSessionPreferences parsedOverrideCapabilities = NetconfSessionPreferences.fromStrings(capabilities);
233 JmxAttributeValidationException.checkCondition(
234 parsedOverrideCapabilities.getNonModuleCaps().isEmpty(),
235 "Capabilities to override can only contain module based capabilities, non-module capabilities will be retrieved from the device," +
236 " configured non-module capabilities: " + parsedOverrideCapabilities.getNonModuleCaps(),
237 yangModuleCapabilitiesJmxAttribute);
239 return Optional.of(parsedOverrideCapabilities);
242 public void setBundleContext(final BundleContext bundleContext) {
243 this.bundleContext = bundleContext;
246 public NetconfReconnectingClientConfiguration getClientConfig(final NetconfDeviceCommunicator listener) {
247 final InetSocketAddress socketAddress = getSocketAddress();
248 final long clientConnectionTimeoutMillis = getConnectionTimeoutMillis();
250 final ReconnectStrategyFactory sf = new TimedReconnectStrategyFactory(
251 getEventExecutorDependency(), getMaxConnectionAttempts(), getBetweenAttemptsTimeoutMillis(), getSleepFactor());
252 final ReconnectStrategy strategy = sf.createReconnectStrategy();
254 return NetconfReconnectingClientConfigurationBuilder.create()
255 .withAddress(socketAddress)
256 .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
257 .withReconnectStrategy(strategy)
258 .withAuthHandler(new LoginPassword(getUsername(), getPassword()))
259 .withProtocol(getTcpOnly() ?
260 NetconfClientConfiguration.NetconfClientProtocol.TCP :
261 NetconfClientConfiguration.NetconfClientProtocol.SSH)
262 .withConnectStrategyFactory(sf)
263 .withSessionListener(listener)
267 private static final class SalConnectorCloseable implements AutoCloseable {
268 private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
269 private final NetconfDeviceCommunicator listener;
271 public SalConnectorCloseable(final NetconfDeviceCommunicator listener,
272 final RemoteDeviceHandler<NetconfSessionPreferences> salFacade) {
273 this.listener = listener;
274 this.salFacade = salFacade;
278 public void close() {
284 private static final class TimedReconnectStrategyFactory implements ReconnectStrategyFactory {
285 private final Long connectionAttempts;
286 private final EventExecutor executor;
287 private final double sleepFactor;
288 private final int minSleep;
290 TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts, final int minSleep, final BigDecimal sleepFactor) {
291 if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
292 connectionAttempts = maxConnectionAttempts;
294 logger.trace("Setting {} on {} to infinity", maxConnectionAttemptsJmxAttribute, this);
295 connectionAttempts = null;
298 this.sleepFactor = sleepFactor.doubleValue();
299 this.executor = executor;
300 this.minSleep = minSleep;
304 public ReconnectStrategy createReconnectStrategy() {
305 final Long maxSleep = null;
306 final Long deadline = null;
308 return new TimedReconnectStrategy(executor, minSleep,
309 minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
313 private InetSocketAddress getSocketAddress() {
314 if(getAddress().getDomainName() != null) {
315 return new InetSocketAddress(getAddress().getDomainName().getValue(), getPort().getValue());
317 final IpAddress ipAddress = getAddress().getIpAddress();
318 final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue();
319 return new InetSocketAddress(ip, getPort().getValue());
323 public void setSchemaRegistry(final SchemaSourceRegistry schemaRegistry) {
324 this.schemaRegistry = schemaRegistry;
327 public void setSchemaContextFactory(final SchemaContextFactory schemaContextFactory) {
328 this.schemaContextFactory = schemaContextFactory;
331 public void setInstanceName(final String instanceName) {
332 this.instanceName = instanceName;