785be9954d3e038b3f2cb7655180584a2b88c564
[netconf.git] / opendaylight / netconf / sal-netconf-connector / src / main / java / org / opendaylight / controller / config / yang / md / sal / connector / netconf / NetconfConnectorModule.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.config.yang.md.sal.connector.netconf;
9
10 import static org.opendaylight.controller.config.api.JmxAttributeValidationException.checkCondition;
11 import static org.opendaylight.controller.config.api.JmxAttributeValidationException.checkNotNull;
12
13 import com.google.common.base.Optional;
14 import com.google.common.base.Strings;
15 import io.netty.util.concurrent.EventExecutor;
16 import java.io.File;
17 import java.math.BigDecimal;
18 import java.net.InetSocketAddress;
19 import java.util.HashMap;
20 import java.util.List;
21 import java.util.Map;
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;
61
62 /**
63  *
64  */
65 public final class NetconfConnectorModule extends org.opendaylight.controller.config.yang.md.sal.connector.netconf.AbstractNetconfConnectorModule
66 {
67     private static final Logger LOG = LoggerFactory.getLogger(NetconfConnectorModule.class);
68
69     /**
70      * Filesystem based caches are stored relative to the cache directory.
71      */
72     private static final String CACHE_DIRECTORY = "cache";
73
74     /**
75      * The default cache directory relative to <code>CACHE_DIRECTORY</code>
76      */
77     private static final String DEFAULT_CACHE_DIRECTORY = "schema";
78
79     /**
80      * The qualified schema cache directory <code>cache/schema</code>
81      */
82     private static final String QUALIFIED_DEFAULT_CACHE_DIRECTORY = CACHE_DIRECTORY + File.separator+ DEFAULT_CACHE_DIRECTORY;
83
84     /**
85      * The name for the default schema repository
86      */
87     private static final String DEFAULT_SCHEMA_REPOSITORY_NAME = "sal-netconf-connector";
88
89     /**
90      * The default schema repository in the case that one is not specified.
91      */
92     private static final SharedSchemaRepository DEFAULT_SCHEMA_REPOSITORY =
93             new SharedSchemaRepository(DEFAULT_SCHEMA_REPOSITORY_NAME);
94
95     /**
96      * The default <code>FilesystemSchemaSourceCache</code>, which stores cached files in <code>cache/schema</code>.
97      */
98     private static final FilesystemSchemaSourceCache<YangTextSchemaSource> DEFAULT_CACHE =
99             new FilesystemSchemaSourceCache<>(DEFAULT_SCHEMA_REPOSITORY, YangTextSchemaSource.class,
100                     new File(QUALIFIED_DEFAULT_CACHE_DIRECTORY));
101
102     /**
103      * The default factory for creating <code>SchemaContext</code> instances.
104      */
105     private static final SchemaContextFactory DEFAULT_SCHEMA_CONTEXT_FACTORY =
106             DEFAULT_SCHEMA_REPOSITORY.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
107
108     /**
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.
115      */
116     private static volatile Map<String, NetconfDevice.SchemaResourcesDTO> schemaResourcesDTOs = new HashMap<>();
117
118     // Initializes default constant instances for the case when the default schema repository
119     // directory cache/schema is used.
120     static {
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));
128     }
129
130     private BundleContext bundleContext;
131     private Optional<NetconfSessionPreferences> userCapabilities;
132     private SchemaSourceRegistry schemaRegistry = DEFAULT_SCHEMA_REPOSITORY;
133     private SchemaContextFactory schemaContextFactory = DEFAULT_SCHEMA_CONTEXT_FACTORY;
134
135     private Broker domRegistry;
136     private NetconfClientDispatcher clientDispatcher;
137     private BindingAwareBroker bindingRegistry;
138     private ThreadPool processingExecutor;
139     private ScheduledThreadPool keepaliveExecutor;
140     private EventExecutor eventExecutor;
141
142     /**
143      * The name associated with the Netconf mount point.  This value is passed from <code>NetconfConnectorModuleFactory</code>.
144      */
145     private String instanceName;
146
147     public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
148         super(identifier, dependencyResolver);
149     }
150
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);
153     }
154
155     @Override
156     protected void customValidation() {
157         checkNotNull(getAddress(), addressJmxAttribute);
158         checkCondition(isHostAddressPresent(getAddress()), "Host address not present in " + getAddress(), addressJmxAttribute);
159         checkNotNull(getPort(), portJmxAttribute);
160
161         checkNotNull(getConnectionTimeoutMillis(), connectionTimeoutMillisJmxAttribute);
162         checkCondition(getConnectionTimeoutMillis() > 0, "must be > 0", connectionTimeoutMillisJmxAttribute);
163
164         checkNotNull(getDefaultRequestTimeoutMillis(), defaultRequestTimeoutMillisJmxAttribute);
165         checkCondition(getDefaultRequestTimeoutMillis() > 0, "must be > 0", defaultRequestTimeoutMillisJmxAttribute);
166
167         checkNotNull(getBetweenAttemptsTimeoutMillis(), betweenAttemptsTimeoutMillisJmxAttribute);
168         checkCondition(getBetweenAttemptsTimeoutMillis() > 0, "must be > 0", betweenAttemptsTimeoutMillisJmxAttribute);
169
170         // Check username + password in case of ssh
171         if(getTcpOnly() == false) {
172             checkNotNull(getUsername(), usernameJmxAttribute);
173             checkNotNull(getPassword(), passwordJmxAttribute);
174         }
175
176         userCapabilities = getUserCapabilities();
177     }
178
179     private boolean isHostAddressPresent(final Host address) {
180         return address.getDomainName() != null ||
181                address.getIpAddress() != null && (address.getIpAddress().getIpv4Address() != null || address.getIpAddress().getIpv6Address() != null);
182     }
183
184     @Deprecated
185     private static ScheduledExecutorService DEFAULT_KEEPALIVE_EXECUTOR;
186
187     @Override
188     public java.lang.AutoCloseable createInstance() {
189         initDependencies();
190         final RemoteDeviceId id = new RemoteDeviceId(getIdentifier(), getSocketAddress());
191
192         final ExecutorService globalProcessingExecutor = processingExecutor.getExecutor();
193
194         RemoteDeviceHandler<NetconfSessionPreferences> salFacade
195                 = new NetconfDeviceSalFacade(id, domRegistry, bindingRegistry, getDefaultRequestTimeoutMillis());
196
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();
201
202             salFacade = new KeepaliveSalFacade(id, salFacade, executor, keepaliveDelay);
203         }
204
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);
219                     if (dto == null) {
220                         schemaResourcesDTO = createSchemaResourcesDTO(moduleSchemaCacheDirectory);
221                         schemaRegistry.registerSchemaSourceListener(
222                                 TextToASTTransformer.create((SchemaRepository) schemaRegistry, schemaRegistry));
223                         schemaResourcesDTOs.put(moduleSchemaCacheDirectory, schemaResourcesDTO);
224                     } else {
225                         setSchemaContextFactory(dto.getSchemaContextFactory());
226                         setSchemaRegistry(dto.getSchemaRegistry());
227                         schemaResourcesDTO = dto;
228                     }
229                 }
230                 LOG.info("Netconf connector for device {} will use schema cache directory {} instead of {}",
231                         instanceName, moduleSchemaCacheDirectory, DEFAULT_CACHE_DIRECTORY);
232             }
233         } else {
234             LOG.warn("schema-cache-directory for {} is null or empty;  using the default {}",
235                     instanceName, QUALIFIED_DEFAULT_CACHE_DIRECTORY);
236         }
237
238         if (schemaResourcesDTO == null) {
239             schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(schemaRegistry, schemaContextFactory,
240                     new NetconfStateSchemas.NetconfStateSchemasResolverImpl());
241         }
242
243         final NetconfDevice device =
244                 new NetconfDevice(schemaResourcesDTO, id, salFacade, globalProcessingExecutor, getReconnectOnChangedSchema());
245
246         final NetconfDeviceCommunicator listener = userCapabilities.isPresent() ?
247                 new NetconfDeviceCommunicator(id, device,
248                         new UserPreferences(userCapabilities.get(), getYangModuleCapabilities().getOverride())):
249                 new NetconfDeviceCommunicator(id, device);
250
251         if (shouldSendKeepalive()) {
252             ((KeepaliveSalFacade) salFacade).setListener(listener);
253         }
254
255         final NetconfReconnectingClientConfiguration clientConfig = getClientConfig(listener);
256         listener.initializeRemoteConnection(clientDispatcher, clientConfig);
257
258         return new SalConnectorCloseable(listener, salFacade);
259     }
260
261     /**
262      * Creates the backing Schema classes for a particular directory.
263      *
264      * @param moduleSchemaCacheDirectory The string directory relative to "cache"
265      * @return A DTO containing the Schema classes for the Netconf mount.
266      */
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());
278     }
279
280     /**
281      * Creates a <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory.
282      *
283      * @param schemaCacheDirectory The custom cache directory relative to "cache"
284      * @return A <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory
285      */
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));
289     }
290
291     private void initDependencies() {
292         domRegistry = getDomRegistryDependency();
293         clientDispatcher = getClientDispatcherDependency();
294         bindingRegistry = getBindingRegistryDependency();
295         processingExecutor = getProcessingExecutorDependency();
296         eventExecutor = getEventExecutorDependency();
297
298         if(getKeepaliveExecutor() == null) {
299             LOG.warn("Keepalive executor missing. Using default instance for now, the configuration needs to be updated");
300
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() {
304                     @Override
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);
309                         return thread;
310                     }
311                 });
312             }
313         } else {
314             keepaliveExecutor = getKeepaliveExecutorDependency();
315         }
316     }
317
318     private boolean shouldSendKeepalive() {
319         return getKeepaliveDelay() > 0;
320     }
321
322     private Optional<NetconfSessionPreferences> getUserCapabilities() {
323         if(getYangModuleCapabilities() == null) {
324             return Optional.absent();
325         }
326
327         final List<String> capabilities = getYangModuleCapabilities().getCapability();
328         if(capabilities == null || capabilities.isEmpty()) {
329             return Optional.absent();
330         }
331
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);
338
339         return Optional.of(parsedOverrideCapabilities);
340     }
341
342     public NetconfReconnectingClientConfiguration getClientConfig(final NetconfDeviceCommunicator listener) {
343         final InetSocketAddress socketAddress = getSocketAddress();
344         final long clientConnectionTimeoutMillis = getConnectionTimeoutMillis();
345
346         final ReconnectStrategyFactory sf = new TimedReconnectStrategyFactory(eventExecutor,
347                 getMaxConnectionAttempts(), getBetweenAttemptsTimeoutMillis(), getSleepFactor());
348         final ReconnectStrategy strategy = sf.createReconnectStrategy();
349
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)
360         .build();
361     }
362
363     private static final class SalConnectorCloseable implements AutoCloseable {
364         private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
365         private final NetconfDeviceCommunicator listener;
366
367         public SalConnectorCloseable(final NetconfDeviceCommunicator listener,
368                                      final RemoteDeviceHandler<NetconfSessionPreferences> salFacade) {
369             this.listener = listener;
370             this.salFacade = salFacade;
371         }
372
373         @Override
374         public void close() {
375             listener.close();
376             salFacade.close();
377         }
378     }
379
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;
385
386         TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts, final int minSleep, final BigDecimal sleepFactor) {
387             if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
388                 connectionAttempts = maxConnectionAttempts;
389             } else {
390                 LOG.trace("Setting {} on {} to infinity", maxConnectionAttemptsJmxAttribute, this);
391                 connectionAttempts = null;
392             }
393
394             this.sleepFactor = sleepFactor.doubleValue();
395             this.executor = executor;
396             this.minSleep = minSleep;
397         }
398
399         @Override
400         public ReconnectStrategy createReconnectStrategy() {
401             final Long maxSleep = null;
402             final Long deadline = null;
403
404             return new TimedReconnectStrategy(executor, minSleep,
405                     minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
406         }
407     }
408
409     private InetSocketAddress getSocketAddress() {
410         if(getAddress().getDomainName() != null) {
411             return new InetSocketAddress(getAddress().getDomainName().getValue(), getPort().getValue());
412         } else {
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());
416         }
417     }
418
419     public void setSchemaRegistry(final SchemaSourceRegistry schemaRegistry) {
420         this.schemaRegistry = schemaRegistry;
421     }
422
423     public void setSchemaContextFactory(final SchemaContextFactory schemaContextFactory) {
424         this.schemaContextFactory = schemaContextFactory;
425     }
426
427     public void setInstanceName(final String instanceName) {
428         this.instanceName = instanceName;
429     }
430 }