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.util.ThreadUtils;
42 import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
43 import org.opendaylight.controller.config.util.capability.BasicCapability;
44 import org.opendaylight.controller.config.util.capability.Capability;
45 import org.opendaylight.controller.config.util.capability.YangModuleCapability;
46 import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
47 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
48 import org.opendaylight.netconf.auth.AuthProvider;
49 import org.opendaylight.netconf.impl.NetconfServerDispatcherImpl;
50 import org.opendaylight.netconf.impl.NetconfServerSessionNegotiatorFactory;
51 import org.opendaylight.netconf.impl.SessionIdProvider;
52 import org.opendaylight.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
53 import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactory;
54 import org.opendaylight.netconf.monitoring.osgi.NetconfMonitoringActivator;
55 import org.opendaylight.netconf.monitoring.osgi.NetconfMonitoringOperationService;
56 import org.opendaylight.netconf.ssh.SshProxyServer;
57 import org.opendaylight.netconf.ssh.SshProxyServerConfiguration;
58 import org.opendaylight.netconf.ssh.SshProxyServerConfigurationBuilder;
59 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
60 import org.opendaylight.yangtools.yang.model.api.Module;
61 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
62 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
63 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
64 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
65 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
66 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
67 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
68 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
69 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
70 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
71 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
72 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
73 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
77 public class NetconfDeviceSimulator implements Closeable {
79 private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSimulator.class);
81 private final NioEventLoopGroup nettyThreadgroup;
82 private final HashedWheelTimer hashedWheelTimer;
83 private final List<Channel> devicesChannels = Lists.newArrayList();
84 private final List<SshProxyServer> sshWrappers = Lists.newArrayList();
85 private final ScheduledExecutorService minaTimerExecutor;
86 private final ExecutorService nioExecutor;
87 private SchemaContext schemaContext;
89 private boolean sendFakeSchema = false;
91 public NetconfDeviceSimulator() {
92 // TODO make pool size configurable
93 this(new NioEventLoopGroup(), new HashedWheelTimer(),
94 Executors.newScheduledThreadPool(8, new ThreadFactoryBuilder().setNameFormat("netconf-ssh-server-mina-timers-%d").build()),
95 ThreadUtils.newFixedThreadPool("netconf-ssh-server-nio-group", 8));
98 private NetconfDeviceSimulator(final NioEventLoopGroup eventExecutors, final HashedWheelTimer hashedWheelTimer, final ScheduledExecutorService minaTimerExecutor, final ExecutorService nioExecutor) {
99 this.nettyThreadgroup = eventExecutors;
100 this.hashedWheelTimer = hashedWheelTimer;
101 this.minaTimerExecutor = minaTimerExecutor;
102 this.nioExecutor = nioExecutor;
105 private NetconfServerDispatcherImpl createDispatcher(final Set<Capability> capabilities, final boolean exi, final int generateConfigsTimeout,
106 final Optional<File> notificationsFile, final boolean mdSal, final Optional<File> initialConfigXMLFile,
107 final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
109 final Set<Capability> transformedCapabilities = Sets.newHashSet(Collections2.transform(capabilities, new Function<Capability, Capability>() {
111 public Capability apply(final Capability input) {
112 if (sendFakeSchema) {
113 sendFakeSchema = false;
114 return new FakeCapability((YangModuleCapability) input);
121 final SessionIdProvider idProvider = new SessionIdProvider();
123 final AggregatedNetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory = new AggregatedNetconfOperationServiceFactory();
124 final NetconfOperationServiceFactory operationProvider = mdSal ? new MdsalOperationProvider(idProvider, transformedCapabilities, schemaContext, sourceProvider) :
125 new SimulatedOperationProvider(idProvider, transformedCapabilities, notificationsFile, initialConfigXMLFile);
127 transformedCapabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0"));
129 final NetconfMonitoringService monitoringService1 = new DummyMonitoringService(transformedCapabilities);
131 final NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory monitoringService =
132 new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(
133 new NetconfMonitoringOperationService(monitoringService1));
134 aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(operationProvider);
135 aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(monitoringService);
137 final Set<String> serverCapabilities = exi
138 ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES
139 : Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0, XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
141 final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new TesttoolNegotiationFactory(
142 hashedWheelTimer, aggregatedNetconfOperationServiceFactory, idProvider, generateConfigsTimeout, monitoringService1, serverCapabilities);
144 final NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(
145 serverNegotiatorFactory);
146 return new NetconfServerDispatcherImpl(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
149 public List<Integer> start(final TesttoolParameters params) {
150 LOG.info("Starting {}, {} simulated devices starting on port {}", params.deviceCount, params.ssh ? "SSH" : "TCP", params.startingPort);
152 final SharedSchemaRepository schemaRepo = new SharedSchemaRepository("netconf-simulator");
153 final Set<Capability> capabilities = parseSchemasToModuleCapabilities(params, schemaRepo);
155 final NetconfServerDispatcherImpl dispatcher = createDispatcher(capabilities, params.exi, params.generateConfigsTimeout,
156 Optional.fromNullable(params.notificationFile), params.mdSal, Optional.fromNullable(params.initialConfigXMLFile),
157 new SchemaSourceProvider<YangTextSchemaSource>() {
159 public CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
160 return schemaRepo.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class);
164 int currentPort = params.startingPort;
166 final List<Integer> openDevices = Lists.newArrayList();
168 // Generate key to temp folder
169 final PEMGeneratorHostKeyProvider keyPairProvider = getPemGeneratorHostKeyProvider();
171 for (int i = 0; i < params.deviceCount; i++) {
172 if (currentPort > 65535) {
173 LOG.warn("Port cannot be greater than 65535, stopping further attempts.");
176 final InetSocketAddress address = getAddress(currentPort);
178 final ChannelFuture server;
180 final InetSocketAddress bindingAddress = InetSocketAddress.createUnresolved("0.0.0.0", currentPort);
181 final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());
183 server = dispatcher.createLocalServer(tcpLocalAddress);
185 final SshProxyServer sshServer = new SshProxyServer(minaTimerExecutor, nettyThreadgroup, nioExecutor);
186 sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress, keyPairProvider));
187 sshWrappers.add(sshServer);
188 } catch (final BindException e) {
189 LOG.warn("Cannot start simulated device on {}, port already in use. Skipping.", address);
190 // Close local server and continue
192 if(server.isDone()) {
193 server.channel().close();
196 } catch (final IOException e) {
197 LOG.warn("Cannot start simulated device on {} due to IOException.", address, e);
205 } catch (final InterruptedException e) {
206 throw new RuntimeException(e);
207 } catch (final ExecutionException e) {
208 LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
212 LOG.debug("Simulated SSH device started on {}", address);
215 server = dispatcher.createServer(address);
220 } catch (final InterruptedException e) {
221 throw new RuntimeException(e);
222 } catch (final ExecutionException e) {
223 LOG.warn("Cannot start tcp simulated device on {}, skipping", address, e);
227 LOG.debug("Simulated TCP device started on {}", address);
230 devicesChannels.add(server.channel());
231 openDevices.add(currentPort - 1);
234 if(openDevices.size() == params.deviceCount) {
235 LOG.info("All simulated devices started successfully from port {} to {}", params.startingPort, currentPort - 1);
236 } else if (openDevices.size() == 0) {
237 LOG.warn("No simulated devices started.");
239 LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
245 private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress, final LocalAddress tcpLocalAddress, final PEMGeneratorHostKeyProvider keyPairProvider) throws IOException {
246 return new SshProxyServerConfigurationBuilder()
247 .setBindingAddress(bindingAddress)
248 .setLocalAddress(tcpLocalAddress)
249 .setAuthenticator(new AuthProvider() {
251 public boolean authenticated(final String username, final String password) {
255 .setKeyPairProvider(keyPairProvider)
256 .setIdleTimeout(Integer.MAX_VALUE)
257 .createSshProxyServerConfiguration();
260 private PEMGeneratorHostKeyProvider getPemGeneratorHostKeyProvider() {
262 final Path tempFile = Files.createTempFile("tempKeyNetconfTest", "suffix");
263 return new PEMGeneratorHostKeyProvider(tempFile.toAbsolutePath().toString());
264 } catch (final IOException e) {
265 LOG.error("Unable to generate PEM key", e);
266 throw new RuntimeException(e);
270 private Set<Capability> parseSchemasToModuleCapabilities(final TesttoolParameters params, final SharedSchemaRepository consumer) {
271 final Set<SourceIdentifier> loadedSources = Sets.newHashSet();
273 consumer.registerSchemaSourceListener(TextToASTTransformer.create(consumer, consumer));
275 consumer.registerSchemaSourceListener(new SchemaSourceListener() {
277 public void schemaSourceEncountered(final SchemaSourceRepresentation schemaSourceRepresentation) {}
280 public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> potentialSchemaSources) {
281 for (final PotentialSchemaSource<?> potentialSchemaSource : potentialSchemaSources) {
282 loadedSources.add(potentialSchemaSource.getSourceIdentifier());
287 public void schemaSourceUnregistered(final PotentialSchemaSource<?> potentialSchemaSource) {}
290 if(params.schemasDir != null) {
291 final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(consumer, YangTextSchemaSource.class, params.schemasDir);
292 consumer.registerSchemaSourceListener(cache);
295 addDefaultSchemas(consumer);
298 //necessary for creating mdsal data stores and operations
299 this.schemaContext = consumer.createSchemaContextFactory(
300 SchemaSourceFilter.ALWAYS_ACCEPT)
301 .createSchemaContext(loadedSources).checkedGet();
302 } catch (final SchemaResolutionException e) {
303 throw new RuntimeException("Cannot parse schema context", e);
306 final Set<Capability> capabilities = Sets.newHashSet();
308 for (final Module module : schemaContext.getModules()) {
309 for (final Module subModule : module.getSubmodules()) {
310 addModuleCapability(consumer, capabilities, subModule);
312 addModuleCapability(consumer, capabilities, module);
317 private void addModuleCapability(SharedSchemaRepository consumer, Set<Capability> capabilities, Module module) {
318 final SourceIdentifier moduleSourceIdentifier = SourceIdentifier.create(module.getName(),
319 (SimpleDateFormatUtil.DEFAULT_DATE_REV == module.getRevision() ? Optional.<String>absent() :
320 Optional.of(SimpleDateFormatUtil.getRevisionFormat().format(module.getRevision()))));
322 String moduleContent = new String(consumer.getSchemaSource(moduleSourceIdentifier, YangTextSchemaSource.class)
323 .checkedGet().read());
324 capabilities.add(new YangModuleCapability(module, moduleContent));
325 //IOException would be thrown in creating SchemaContext already
326 } catch (SchemaSourceException |IOException e) {
327 throw new RuntimeException("Cannot retrieve schema source for module " + moduleSourceIdentifier.toString() + " from schema repository", e);
331 private void addDefaultSchemas(final SharedSchemaRepository consumer) {
332 SourceIdentifier sId = new SourceIdentifier("ietf-netconf-monitoring", "2010-10-04");
333 registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring.yang", sId);
335 sId = new SourceIdentifier("ietf-netconf-monitoring-extension", "2013-12-10");
336 registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring-extension.yang", sId);
338 sId = new SourceIdentifier("ietf-yang-types", "2010-09-24");
339 registerSource(consumer, "/META-INF/yang/ietf-yang-types.yang", sId);
341 sId = new SourceIdentifier("ietf-inet-types", "2010-09-24");
342 registerSource(consumer, "/META-INF/yang/ietf-inet-types.yang", sId);
345 private void registerSource(final SharedSchemaRepository consumer, final String resource, final SourceIdentifier sourceId) {
346 consumer.registerSchemaSource(new SchemaSourceProvider<SchemaSourceRepresentation>() {
348 public CheckedFuture<? extends SchemaSourceRepresentation, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
349 return Futures.immediateCheckedFuture(new YangTextSchemaSource(sourceId) {
351 protected MoreObjects.ToStringHelper addToStringAttributes(final MoreObjects.ToStringHelper toStringHelper) {
352 return toStringHelper;
356 public InputStream openStream() throws IOException {
357 return getClass().getResourceAsStream(resource);
361 }, PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
364 private static InetSocketAddress getAddress(final int port) {
366 // TODO make address configurable
367 return new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), port);
368 } catch (final UnknownHostException e) {
369 throw new RuntimeException(e);
374 public void close() {
375 for (final SshProxyServer sshWrapper : sshWrappers) {
378 for (final Channel deviceCh : devicesChannels) {
381 nettyThreadgroup.shutdownGracefully();
382 minaTimerExecutor.shutdownNow();
383 nioExecutor.shutdownNow();