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 // if (getNetconfTopology() == null) {
111 // checkNotNull(getDomRegistry(), domRegistryJmxAttribute);
112 // checkNotNull(getClientDispatcher(), clientDispatcherJmxAttribute);
113 // checkNotNull(getBindingRegistry(), bindingRegistryJmxAttribute);
114 // checkNotNull(getProcessingExecutor(), processingExecutorJmxAttribute);
117 // Check username + password in case of ssh
118 if(getTcpOnly() == false) {
119 checkNotNull(getUsername(), usernameJmxAttribute);
120 checkNotNull(getPassword(), passwordJmxAttribute);
123 userCapabilities = getUserCapabilities();
126 private boolean isHostAddressPresent(final Host address) {
127 return address.getDomainName() != null ||
128 address.getIpAddress() != null && (address.getIpAddress().getIpv4Address() != null || address.getIpAddress().getIpv6Address() != null);
132 private static ScheduledExecutorService DEFAULT_KEEPALIVE_EXECUTOR;
135 public java.lang.AutoCloseable createInstance() {
136 initDependenciesFromTopology();
137 final RemoteDeviceId id = new RemoteDeviceId(getIdentifier(), getSocketAddress());
139 final ExecutorService globalProcessingExecutor = processingExecutor.getExecutor();
141 RemoteDeviceHandler<NetconfSessionPreferences> salFacade
142 = new NetconfDeviceSalFacade(id, domRegistry, bindingRegistry, getDefaultRequestTimeoutMillis());
144 final Long keepaliveDelay = getKeepaliveDelay();
145 if (shouldSendKeepalive()) {
146 // Keepalive executor is optional for now and a default instance is supported
147 final ScheduledExecutorService executor = keepaliveExecutor == null ? DEFAULT_KEEPALIVE_EXECUTOR : keepaliveExecutor.getExecutor();
149 salFacade = new KeepaliveSalFacade(id, salFacade, executor, keepaliveDelay);
152 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO =
153 new NetconfDevice.SchemaResourcesDTO(schemaRegistry, schemaContextFactory, new NetconfStateSchemas.NetconfStateSchemasResolverImpl());
155 final NetconfDevice device =
156 new NetconfDevice(schemaResourcesDTO, id, salFacade, globalProcessingExecutor, getReconnectOnChangedSchema());
158 final NetconfDeviceCommunicator listener = userCapabilities.isPresent() ?
159 new NetconfDeviceCommunicator(id, device, userCapabilities.get()) : new NetconfDeviceCommunicator(id, device);
161 if (shouldSendKeepalive()) {
162 ((KeepaliveSalFacade) salFacade).setListener(listener);
165 final NetconfReconnectingClientConfiguration clientConfig = getClientConfig(listener);
166 listener.initializeRemoteConnection(clientDispatcher, clientConfig);
168 return new SalConnectorCloseable(listener, salFacade);
171 private void initDependenciesFromTopology() {
172 // topology = getNetconfTopologyDependency();
174 // domRegistry = topology.getDomRegistryDependency();
175 // clientDispatcher = topology.getNetconfClientDispatcherDependency();
176 // bindingRegistry = topology.getBindingAwareBroker();
177 // processingExecutor = topology.getProcessingExecutorDependency();
178 // keepaliveExecutor = topology.getKeepaliveExecutorDependency();
179 // sharedSchemaRepository = topology.getSharedSchemaRepository().getSharedSchemaRepository();
180 // eventExecutor = topology.getEventExecutorDependency();
182 // initFilesystemSchemaSourceCache(sharedSchemaRepository);
183 domRegistry = getDomRegistryDependency();
184 clientDispatcher = getClientDispatcherDependency();
185 bindingRegistry = getBindingRegistryDependency();
186 processingExecutor = getProcessingExecutorDependency();
187 eventExecutor = getEventExecutorDependency();
189 if(getKeepaliveExecutor() == null) {
190 LOG.warn("Keepalive executor missing. Using default instance for now, the configuration needs to be updated");
192 // Instantiate the default executor, now we know its necessary
193 if(DEFAULT_KEEPALIVE_EXECUTOR == null) {
194 DEFAULT_KEEPALIVE_EXECUTOR = Executors.newScheduledThreadPool(2, new ThreadFactory() {
196 public Thread newThread(final Runnable r) {
197 final Thread thread = new Thread(r);
198 thread.setName("netconf-southound-keepalives-" + thread.getId());
199 thread.setDaemon(true);
206 LOG.warn("No topology defined in config, using default-shared-schema-repo");
207 if (DEFAULT_SCHEMA_REPOSITORY == null) {
208 DEFAULT_SCHEMA_REPOSITORY = new SharedSchemaRepository("default shared schema repo");
210 initFilesystemSchemaSourceCache(DEFAULT_SCHEMA_REPOSITORY);
213 private void initFilesystemSchemaSourceCache(SharedSchemaRepository repository) {
214 LOG.warn("Schema repository used: {}", repository.getIdentifier());
216 CACHE = new FilesystemSchemaSourceCache<>(repository, YangTextSchemaSource.class, new File("cache/schema"));
218 if (!INITIALIZED_SCHEMA_REPOSITORIES.contains(repository)) {
219 repository.registerSchemaSourceListener(CACHE);
220 repository.registerSchemaSourceListener(TextToASTTransformer.create(repository, repository));
221 INITIALIZED_SCHEMA_REPOSITORIES.add(repository);
223 setSchemaRegistry(repository);
224 setSchemaContextFactory(repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT));
227 private boolean shouldSendKeepalive() {
228 return getKeepaliveDelay() > 0;
231 private Optional<NetconfSessionPreferences> getUserCapabilities() {
232 if(getYangModuleCapabilities() == null) {
233 return Optional.absent();
236 final List<String> capabilities = getYangModuleCapabilities().getCapability();
237 if(capabilities == null || capabilities.isEmpty()) {
238 return Optional.absent();
241 final NetconfSessionPreferences parsedOverrideCapabilities = NetconfSessionPreferences.fromStrings(capabilities);
242 JmxAttributeValidationException.checkCondition(
243 parsedOverrideCapabilities.getNonModuleCaps().isEmpty(),
244 "Capabilities to override can only contain module based capabilities, non-module capabilities will be retrieved from the device," +
245 " configured non-module capabilities: " + parsedOverrideCapabilities.getNonModuleCaps(),
246 yangModuleCapabilitiesJmxAttribute);
248 return Optional.of(parsedOverrideCapabilities);
251 public NetconfReconnectingClientConfiguration getClientConfig(final NetconfDeviceCommunicator listener) {
252 final InetSocketAddress socketAddress = getSocketAddress();
253 final long clientConnectionTimeoutMillis = getConnectionTimeoutMillis();
255 final ReconnectStrategyFactory sf = new TimedReconnectStrategyFactory(eventExecutor,
256 getMaxConnectionAttempts(), getBetweenAttemptsTimeoutMillis(), getSleepFactor());
257 final ReconnectStrategy strategy = sf.createReconnectStrategy();
259 return NetconfReconnectingClientConfigurationBuilder.create()
260 .withAddress(socketAddress)
261 .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
262 .withReconnectStrategy(strategy)
263 .withAuthHandler(new LoginPassword(getUsername(), getPassword()))
264 .withProtocol(getTcpOnly() ?
265 NetconfClientConfiguration.NetconfClientProtocol.TCP :
266 NetconfClientConfiguration.NetconfClientProtocol.SSH)
267 .withConnectStrategyFactory(sf)
268 .withSessionListener(listener)
272 private static final class SalConnectorCloseable implements AutoCloseable {
273 private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
274 private final NetconfDeviceCommunicator listener;
276 public SalConnectorCloseable(final NetconfDeviceCommunicator listener,
277 final RemoteDeviceHandler<NetconfSessionPreferences> salFacade) {
278 this.listener = listener;
279 this.salFacade = salFacade;
283 public void close() {
289 private static final class TimedReconnectStrategyFactory implements ReconnectStrategyFactory {
290 private final Long connectionAttempts;
291 private final EventExecutor executor;
292 private final double sleepFactor;
293 private final int minSleep;
295 TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts, final int minSleep, final BigDecimal sleepFactor) {
296 if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
297 connectionAttempts = maxConnectionAttempts;
299 LOG.trace("Setting {} on {} to infinity", maxConnectionAttemptsJmxAttribute, this);
300 connectionAttempts = null;
303 this.sleepFactor = sleepFactor.doubleValue();
304 this.executor = executor;
305 this.minSleep = minSleep;
309 public ReconnectStrategy createReconnectStrategy() {
310 final Long maxSleep = null;
311 final Long deadline = null;
313 return new TimedReconnectStrategy(executor, minSleep,
314 minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
318 private InetSocketAddress getSocketAddress() {
319 if(getAddress().getDomainName() != null) {
320 return new InetSocketAddress(getAddress().getDomainName().getValue(), getPort().getValue());
322 final IpAddress ipAddress = getAddress().getIpAddress();
323 final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue();
324 return new InetSocketAddress(ip, getPort().getValue());
328 public void setSchemaRegistry(final SchemaSourceRegistry schemaRegistry) {
329 this.schemaRegistry = schemaRegistry;
332 public void setSchemaContextFactory(final SchemaContextFactory schemaContextFactory) {
333 this.schemaContextFactory = schemaContextFactory;