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
9 package org.opendaylight.netconf.test.tool;
11 import com.google.common.base.Function;
12 import com.google.common.base.MoreObjects;
13 import com.google.common.base.Optional;
14 import com.google.common.collect.Collections2;
15 import com.google.common.collect.Lists;
16 import com.google.common.collect.Sets;
17 import com.google.common.util.concurrent.CheckedFuture;
18 import com.google.common.util.concurrent.Futures;
19 import com.google.common.util.concurrent.ThreadFactoryBuilder;
20 import io.netty.channel.Channel;
21 import io.netty.channel.ChannelFuture;
22 import io.netty.channel.local.LocalAddress;
23 import io.netty.channel.nio.NioEventLoopGroup;
24 import io.netty.util.HashedWheelTimer;
25 import java.io.Closeable;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.net.BindException;
30 import java.net.Inet4Address;
31 import java.net.InetSocketAddress;
32 import java.net.UnknownHostException;
33 import java.nio.file.Files;
34 import java.nio.file.Path;
35 import java.util.List;
37 import java.util.concurrent.ExecutionException;
38 import java.util.concurrent.ExecutorService;
39 import java.util.concurrent.Executors;
40 import java.util.concurrent.ScheduledExecutorService;
41 import org.apache.sshd.common.keyprovider.KeyPairProvider;
42 import org.apache.sshd.common.util.SecurityUtils;
43 import org.apache.sshd.common.util.threads.ThreadUtils;
44 import org.opendaylight.controller.config.util.capability.BasicCapability;
45 import org.opendaylight.controller.config.util.capability.Capability;
46 import org.opendaylight.controller.config.util.capability.YangModuleCapability;
47 import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
48 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
49 import org.opendaylight.netconf.auth.AuthProvider;
50 import org.opendaylight.netconf.impl.NetconfServerDispatcherImpl;
51 import org.opendaylight.netconf.impl.NetconfServerSessionNegotiatorFactory;
52 import org.opendaylight.netconf.impl.SessionIdProvider;
53 import org.opendaylight.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
54 import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactory;
55 import org.opendaylight.netconf.monitoring.osgi.NetconfMonitoringActivator;
56 import org.opendaylight.netconf.monitoring.osgi.NetconfMonitoringOperationService;
57 import org.opendaylight.netconf.ssh.SshProxyServer;
58 import org.opendaylight.netconf.ssh.SshProxyServerConfiguration;
59 import org.opendaylight.netconf.ssh.SshProxyServerConfigurationBuilder;
60 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
61 import org.opendaylight.yangtools.yang.model.api.Module;
62 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
63 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
64 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
65 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
66 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
67 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
68 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
69 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
70 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
71 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
72 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
73 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
74 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
75 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
76 import org.slf4j.Logger;
77 import org.slf4j.LoggerFactory;
79 public class NetconfDeviceSimulator implements Closeable {
81 private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSimulator.class);
83 private final NioEventLoopGroup nettyThreadgroup;
84 private final HashedWheelTimer hashedWheelTimer;
85 private final List<Channel> devicesChannels = Lists.newArrayList();
86 private final List<SshProxyServer> sshWrappers = Lists.newArrayList();
87 private final ScheduledExecutorService minaTimerExecutor;
88 private final ExecutorService nioExecutor;
89 private SchemaContext schemaContext;
91 private boolean sendFakeSchema = false;
93 public NetconfDeviceSimulator(final int ThreadPoolSize) {
94 this(new NioEventLoopGroup(), new HashedWheelTimer(),
95 Executors.newScheduledThreadPool(ThreadPoolSize, new ThreadFactoryBuilder().setNameFormat("netconf-ssh-server-mina-timers-%d").build()),
96 ThreadUtils.newFixedThreadPool("netconf-ssh-server-nio-group", ThreadPoolSize));
99 private NetconfDeviceSimulator(final NioEventLoopGroup eventExecutors, final HashedWheelTimer hashedWheelTimer, final ScheduledExecutorService minaTimerExecutor, final ExecutorService nioExecutor) {
100 this.nettyThreadgroup = eventExecutors;
101 this.hashedWheelTimer = hashedWheelTimer;
102 this.minaTimerExecutor = minaTimerExecutor;
103 this.nioExecutor = nioExecutor;
106 private NetconfServerDispatcherImpl createDispatcher(final Set<Capability> capabilities, final boolean exi, final int generateConfigsTimeout,
107 final Optional<File> notificationsFile, final boolean mdSal, final Optional<File> initialConfigXMLFile,
108 final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
110 final Set<Capability> transformedCapabilities = Sets.newHashSet(Collections2.transform(capabilities, new Function<Capability, Capability>() {
112 public Capability apply(final Capability input) {
113 if (sendFakeSchema) {
114 sendFakeSchema = false;
115 return new FakeCapability((YangModuleCapability) input);
122 final SessionIdProvider idProvider = new SessionIdProvider();
124 final AggregatedNetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory = new AggregatedNetconfOperationServiceFactory();
125 final NetconfOperationServiceFactory operationProvider = mdSal ? new MdsalOperationProvider(idProvider, transformedCapabilities, schemaContext, sourceProvider) :
126 new SimulatedOperationProvider(idProvider, transformedCapabilities, notificationsFile, initialConfigXMLFile);
128 transformedCapabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0"));
130 final NetconfMonitoringService monitoringService1 = new DummyMonitoringService(transformedCapabilities);
132 final NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory monitoringService =
133 new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(
134 new NetconfMonitoringOperationService(monitoringService1));
135 aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(operationProvider);
136 aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(monitoringService);
138 final Set<String> serverCapabilities = exi
139 ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES
140 : Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0, XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
142 final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new TesttoolNegotiationFactory(
143 hashedWheelTimer, aggregatedNetconfOperationServiceFactory, idProvider, generateConfigsTimeout, monitoringService1, serverCapabilities);
145 final NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(
146 serverNegotiatorFactory);
147 return new NetconfServerDispatcherImpl(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
150 public List<Integer> start(final TesttoolParameters params) {
151 LOG.info("Starting {}, {} simulated devices starting on port {}", params.deviceCount, params.ssh ? "SSH" : "TCP", params.startingPort);
153 final SharedSchemaRepository schemaRepo = new SharedSchemaRepository("netconf-simulator");
154 final Set<Capability> capabilities = parseSchemasToModuleCapabilities(params, schemaRepo);
156 final NetconfServerDispatcherImpl dispatcher = createDispatcher(capabilities, params.exi, params.generateConfigsTimeout,
157 Optional.fromNullable(params.notificationFile), params.mdSal, Optional.fromNullable(params.initialConfigXMLFile),
158 new SchemaSourceProvider<YangTextSchemaSource>() {
160 public CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
161 return schemaRepo.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class);
165 int currentPort = params.startingPort;
167 final List<Integer> openDevices = Lists.newArrayList();
169 // Generate key to temp folder
170 final KeyPairProvider keyPairProvider = getPemGeneratorHostKeyProvider();
172 for (int i = 0; i < params.deviceCount; i++) {
173 if (currentPort > 65535) {
174 LOG.warn("Port cannot be greater than 65535, stopping further attempts.");
177 final InetSocketAddress address = getAddress(params.ip, currentPort);
179 final ChannelFuture server;
181 final InetSocketAddress bindingAddress = InetSocketAddress.createUnresolved("0.0.0.0", currentPort);
182 final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());
184 server = dispatcher.createLocalServer(tcpLocalAddress);
186 final SshProxyServer sshServer = new SshProxyServer(minaTimerExecutor, nettyThreadgroup, nioExecutor);
187 sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress, keyPairProvider));
188 sshWrappers.add(sshServer);
189 } catch (final BindException e) {
190 LOG.warn("Cannot start simulated device on {}, port already in use. Skipping.", address);
191 // Close local server and continue
193 if(server.isDone()) {
194 server.channel().close();
197 } catch (final IOException e) {
198 LOG.warn("Cannot start simulated device on {} due to IOException.", address, e);
206 } catch (final InterruptedException e) {
207 throw new RuntimeException(e);
208 } catch (final ExecutionException e) {
209 LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
213 LOG.debug("Simulated SSH device started on {}", address);
216 server = dispatcher.createServer(address);
221 } catch (final InterruptedException e) {
222 throw new RuntimeException(e);
223 } catch (final ExecutionException e) {
224 LOG.warn("Cannot start tcp simulated device on {}, skipping", address, e);
228 LOG.debug("Simulated TCP device started on {}", address);
231 devicesChannels.add(server.channel());
232 openDevices.add(currentPort - 1);
235 if(openDevices.size() == params.deviceCount) {
236 LOG.info("All simulated devices started successfully from port {} to {}", params.startingPort, currentPort - 1);
237 } else if (openDevices.size() == 0) {
238 LOG.warn("No simulated devices started.");
240 LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
246 private static SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress,
247 final LocalAddress tcpLocalAddress, final KeyPairProvider keyPairProvider) {
248 return new SshProxyServerConfigurationBuilder()
249 .setBindingAddress(bindingAddress)
250 .setLocalAddress(tcpLocalAddress)
251 .setAuthenticator(new AuthProvider() {
253 public boolean authenticated(final String username, final String password) {
257 .setKeyPairProvider(keyPairProvider)
258 .setIdleTimeout(Integer.MAX_VALUE)
259 .createSshProxyServerConfiguration();
262 private static KeyPairProvider getPemGeneratorHostKeyProvider() {
264 final Path tempFile = Files.createTempFile("tempKeyNetconfTest", "suffix");
265 return SecurityUtils.createGeneratorHostKeyProvider(tempFile.toAbsolutePath());
266 } catch (final IOException e) {
267 LOG.error("Unable to generate PEM key", e);
268 throw new RuntimeException("Unable to generate PEM key", e);
272 private Set<Capability> parseSchemasToModuleCapabilities(final TesttoolParameters params, final SharedSchemaRepository consumer) {
273 final Set<SourceIdentifier> loadedSources = Sets.newHashSet();
275 consumer.registerSchemaSourceListener(TextToASTTransformer.create(consumer, consumer));
277 consumer.registerSchemaSourceListener(new SchemaSourceListener() {
279 public void schemaSourceEncountered(final SchemaSourceRepresentation schemaSourceRepresentation) {}
282 public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> potentialSchemaSources) {
283 for (final PotentialSchemaSource<?> potentialSchemaSource : potentialSchemaSources) {
284 loadedSources.add(potentialSchemaSource.getSourceIdentifier());
289 public void schemaSourceUnregistered(final PotentialSchemaSource<?> potentialSchemaSource) {}
292 if(params.schemasDir != null) {
293 final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(consumer, YangTextSchemaSource.class, params.schemasDir);
294 consumer.registerSchemaSourceListener(cache);
297 addDefaultSchemas(consumer);
300 //necessary for creating mdsal data stores and operations
301 this.schemaContext = consumer.createSchemaContextFactory(
302 SchemaSourceFilter.ALWAYS_ACCEPT)
303 .createSchemaContext(loadedSources).checkedGet();
304 } catch (final SchemaResolutionException e) {
305 throw new RuntimeException("Cannot parse schema context", e);
308 final Set<Capability> capabilities = Sets.newHashSet();
310 for (final Module module : schemaContext.getModules()) {
311 for (final Module subModule : module.getSubmodules()) {
312 addModuleCapability(consumer, capabilities, subModule);
314 addModuleCapability(consumer, capabilities, module);
319 private static void addModuleCapability(final SharedSchemaRepository consumer, final Set<Capability> capabilities,
320 final Module module) {
321 final SourceIdentifier moduleSourceIdentifier = SourceIdentifier.create(module.getName(),
322 (SimpleDateFormatUtil.DEFAULT_DATE_REV == module.getRevision() ? Optional.<String>absent() :
323 Optional.of(SimpleDateFormatUtil.getRevisionFormat().format(module.getRevision()))));
325 final String moduleContent = new String(consumer.getSchemaSource(moduleSourceIdentifier, YangTextSchemaSource.class)
326 .checkedGet().read());
327 capabilities.add(new YangModuleCapability(module, moduleContent));
328 //IOException would be thrown in creating SchemaContext already
329 } catch (SchemaSourceException |IOException e) {
330 throw new RuntimeException("Cannot retrieve schema source for module " + moduleSourceIdentifier.toString() + " from schema repository", e);
334 private static void addDefaultSchemas(final SharedSchemaRepository consumer) {
335 SourceIdentifier sId = RevisionSourceIdentifier.create("ietf-netconf-monitoring", "2010-10-04");
336 registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring.yang", sId);
338 sId = RevisionSourceIdentifier.create("ietf-netconf-monitoring-extension", "2013-12-10");
339 registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring-extension.yang", sId);
341 sId = RevisionSourceIdentifier.create("ietf-yang-types", "2013-07-15");
342 registerSource(consumer, "/META-INF/yang/ietf-yang-types@2013-07-15.yang", sId);
344 sId = RevisionSourceIdentifier.create("ietf-inet-types", "2013-07-15");
345 registerSource(consumer, "/META-INF/yang/ietf-inet-types@2013-07-15.yang", sId);
348 private static void registerSource(final SharedSchemaRepository consumer, final String resource,
349 final SourceIdentifier sourceId) {
350 consumer.registerSchemaSource(new SchemaSourceProvider<SchemaSourceRepresentation>() {
352 public CheckedFuture<? extends SchemaSourceRepresentation, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
353 return Futures.immediateCheckedFuture(new YangTextSchemaSource(sourceId) {
355 protected MoreObjects.ToStringHelper addToStringAttributes(final MoreObjects.ToStringHelper toStringHelper) {
356 return toStringHelper;
360 public InputStream openStream() throws IOException {
361 return getClass().getResourceAsStream(resource);
365 }, PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
368 private static InetSocketAddress getAddress(final String ip, final int port) {
370 return new InetSocketAddress(Inet4Address.getByName(ip), port);
371 } catch (final UnknownHostException e) {
372 throw new RuntimeException(e);
377 public void close() {
378 for (final SshProxyServer sshWrapper : sshWrappers) {
381 } catch (IOException e) {
382 LOG.error("Failed to close wrapper {}", sshWrapper, e);
385 for (final Channel deviceCh : devicesChannels) {
388 nettyThreadgroup.shutdownGracefully();
389 minaTimerExecutor.shutdownNow();
390 nioExecutor.shutdownNow();