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(final int ThreadPoolSize) {
92 this(new NioEventLoopGroup(), new HashedWheelTimer(),
93 Executors.newScheduledThreadPool(ThreadPoolSize, new ThreadFactoryBuilder().setNameFormat("netconf-ssh-server-mina-timers-%d").build()),
94 ThreadUtils.newFixedThreadPool("netconf-ssh-server-nio-group", ThreadPoolSize));
97 private NetconfDeviceSimulator(final NioEventLoopGroup eventExecutors, final HashedWheelTimer hashedWheelTimer, final ScheduledExecutorService minaTimerExecutor, final ExecutorService nioExecutor) {
98 this.nettyThreadgroup = eventExecutors;
99 this.hashedWheelTimer = hashedWheelTimer;
100 this.minaTimerExecutor = minaTimerExecutor;
101 this.nioExecutor = nioExecutor;
104 private NetconfServerDispatcherImpl createDispatcher(final Set<Capability> capabilities, final boolean exi, final int generateConfigsTimeout,
105 final Optional<File> notificationsFile, final boolean mdSal, final Optional<File> initialConfigXMLFile,
106 final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
108 final Set<Capability> transformedCapabilities = Sets.newHashSet(Collections2.transform(capabilities, new Function<Capability, Capability>() {
110 public Capability apply(final Capability input) {
111 if (sendFakeSchema) {
112 sendFakeSchema = false;
113 return new FakeCapability((YangModuleCapability) input);
120 final SessionIdProvider idProvider = new SessionIdProvider();
122 final AggregatedNetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory = new AggregatedNetconfOperationServiceFactory();
123 final NetconfOperationServiceFactory operationProvider = mdSal ? new MdsalOperationProvider(idProvider, transformedCapabilities, schemaContext, sourceProvider) :
124 new SimulatedOperationProvider(idProvider, transformedCapabilities, notificationsFile, initialConfigXMLFile);
126 transformedCapabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0"));
128 final NetconfMonitoringService monitoringService1 = new DummyMonitoringService(transformedCapabilities);
130 final NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory monitoringService =
131 new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(
132 new NetconfMonitoringOperationService(monitoringService1));
133 aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(operationProvider);
134 aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(monitoringService);
136 final Set<String> serverCapabilities = exi
137 ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES
138 : Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0, XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
140 final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new TesttoolNegotiationFactory(
141 hashedWheelTimer, aggregatedNetconfOperationServiceFactory, idProvider, generateConfigsTimeout, monitoringService1, serverCapabilities);
143 final NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(
144 serverNegotiatorFactory);
145 return new NetconfServerDispatcherImpl(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
148 public List<Integer> start(final TesttoolParameters params) {
149 LOG.info("Starting {}, {} simulated devices starting on port {}", params.deviceCount, params.ssh ? "SSH" : "TCP", params.startingPort);
151 final SharedSchemaRepository schemaRepo = new SharedSchemaRepository("netconf-simulator");
152 final Set<Capability> capabilities = parseSchemasToModuleCapabilities(params, schemaRepo);
154 final NetconfServerDispatcherImpl dispatcher = createDispatcher(capabilities, params.exi, params.generateConfigsTimeout,
155 Optional.fromNullable(params.notificationFile), params.mdSal, Optional.fromNullable(params.initialConfigXMLFile),
156 new SchemaSourceProvider<YangTextSchemaSource>() {
158 public CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
159 return schemaRepo.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class);
163 int currentPort = params.startingPort;
165 final List<Integer> openDevices = Lists.newArrayList();
167 // Generate key to temp folder
168 final PEMGeneratorHostKeyProvider keyPairProvider = getPemGeneratorHostKeyProvider();
170 for (int i = 0; i < params.deviceCount; i++) {
171 if (currentPort > 65535) {
172 LOG.warn("Port cannot be greater than 65535, stopping further attempts.");
175 final InetSocketAddress address = getAddress(params.ip, currentPort);
177 final ChannelFuture server;
179 final InetSocketAddress bindingAddress = InetSocketAddress.createUnresolved("0.0.0.0", currentPort);
180 final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());
182 server = dispatcher.createLocalServer(tcpLocalAddress);
184 final SshProxyServer sshServer = new SshProxyServer(minaTimerExecutor, nettyThreadgroup, nioExecutor);
185 sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress, keyPairProvider));
186 sshWrappers.add(sshServer);
187 } catch (final BindException e) {
188 LOG.warn("Cannot start simulated device on {}, port already in use. Skipping.", address);
189 // Close local server and continue
191 if(server.isDone()) {
192 server.channel().close();
195 } catch (final IOException e) {
196 LOG.warn("Cannot start simulated device on {} due to IOException.", address, e);
204 } catch (final InterruptedException e) {
205 throw new RuntimeException(e);
206 } catch (final ExecutionException e) {
207 LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
211 LOG.debug("Simulated SSH device started on {}", address);
214 server = dispatcher.createServer(address);
219 } catch (final InterruptedException e) {
220 throw new RuntimeException(e);
221 } catch (final ExecutionException e) {
222 LOG.warn("Cannot start tcp simulated device on {}, skipping", address, e);
226 LOG.debug("Simulated TCP device started on {}", address);
229 devicesChannels.add(server.channel());
230 openDevices.add(currentPort - 1);
233 if(openDevices.size() == params.deviceCount) {
234 LOG.info("All simulated devices started successfully from port {} to {}", params.startingPort, currentPort - 1);
235 } else if (openDevices.size() == 0) {
236 LOG.warn("No simulated devices started.");
238 LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
244 private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress, final LocalAddress tcpLocalAddress, final PEMGeneratorHostKeyProvider keyPairProvider) throws IOException {
245 return new SshProxyServerConfigurationBuilder()
246 .setBindingAddress(bindingAddress)
247 .setLocalAddress(tcpLocalAddress)
248 .setAuthenticator(new AuthProvider() {
250 public boolean authenticated(final String username, final String password) {
254 .setKeyPairProvider(keyPairProvider)
255 .setIdleTimeout(Integer.MAX_VALUE)
256 .createSshProxyServerConfiguration();
259 private PEMGeneratorHostKeyProvider getPemGeneratorHostKeyProvider() {
261 final Path tempFile = Files.createTempFile("tempKeyNetconfTest", "suffix");
262 return new PEMGeneratorHostKeyProvider(tempFile.toAbsolutePath().toString());
263 } catch (final IOException e) {
264 LOG.error("Unable to generate PEM key", e);
265 throw new RuntimeException(e);
269 private Set<Capability> parseSchemasToModuleCapabilities(final TesttoolParameters params, final SharedSchemaRepository consumer) {
270 final Set<SourceIdentifier> loadedSources = Sets.newHashSet();
272 consumer.registerSchemaSourceListener(TextToASTTransformer.create(consumer, consumer));
274 consumer.registerSchemaSourceListener(new SchemaSourceListener() {
276 public void schemaSourceEncountered(final SchemaSourceRepresentation schemaSourceRepresentation) {}
279 public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> potentialSchemaSources) {
280 for (final PotentialSchemaSource<?> potentialSchemaSource : potentialSchemaSources) {
281 loadedSources.add(potentialSchemaSource.getSourceIdentifier());
286 public void schemaSourceUnregistered(final PotentialSchemaSource<?> potentialSchemaSource) {}
289 if(params.schemasDir != null) {
290 final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(consumer, YangTextSchemaSource.class, params.schemasDir);
291 consumer.registerSchemaSourceListener(cache);
294 addDefaultSchemas(consumer);
297 //necessary for creating mdsal data stores and operations
298 this.schemaContext = consumer.createSchemaContextFactory(
299 SchemaSourceFilter.ALWAYS_ACCEPT)
300 .createSchemaContext(loadedSources).checkedGet();
301 } catch (final SchemaResolutionException e) {
302 throw new RuntimeException("Cannot parse schema context", e);
305 final Set<Capability> capabilities = Sets.newHashSet();
307 for (final Module module : schemaContext.getModules()) {
308 for (final Module subModule : module.getSubmodules()) {
309 addModuleCapability(consumer, capabilities, subModule);
311 addModuleCapability(consumer, capabilities, module);
316 private void addModuleCapability(SharedSchemaRepository consumer, Set<Capability> capabilities, Module module) {
317 final SourceIdentifier moduleSourceIdentifier = SourceIdentifier.create(module.getName(),
318 (SimpleDateFormatUtil.DEFAULT_DATE_REV == module.getRevision() ? Optional.<String>absent() :
319 Optional.of(SimpleDateFormatUtil.getRevisionFormat().format(module.getRevision()))));
321 String moduleContent = new String(consumer.getSchemaSource(moduleSourceIdentifier, YangTextSchemaSource.class)
322 .checkedGet().read());
323 capabilities.add(new YangModuleCapability(module, moduleContent));
324 //IOException would be thrown in creating SchemaContext already
325 } catch (SchemaSourceException |IOException e) {
326 throw new RuntimeException("Cannot retrieve schema source for module " + moduleSourceIdentifier.toString() + " from schema repository", e);
330 private void addDefaultSchemas(final SharedSchemaRepository consumer) {
331 SourceIdentifier sId = new SourceIdentifier("ietf-netconf-monitoring", "2010-10-04");
332 registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring.yang", sId);
334 sId = new SourceIdentifier("ietf-netconf-monitoring-extension", "2013-12-10");
335 registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring-extension.yang", sId);
337 sId = new SourceIdentifier("ietf-yang-types", "2010-09-24");
338 registerSource(consumer, "/META-INF/yang/ietf-yang-types.yang", sId);
340 sId = new SourceIdentifier("ietf-inet-types", "2010-09-24");
341 registerSource(consumer, "/META-INF/yang/ietf-inet-types.yang", sId);
344 private void registerSource(final SharedSchemaRepository consumer, final String resource, final SourceIdentifier sourceId) {
345 consumer.registerSchemaSource(new SchemaSourceProvider<SchemaSourceRepresentation>() {
347 public CheckedFuture<? extends SchemaSourceRepresentation, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
348 return Futures.immediateCheckedFuture(new YangTextSchemaSource(sourceId) {
350 protected MoreObjects.ToStringHelper addToStringAttributes(final MoreObjects.ToStringHelper toStringHelper) {
351 return toStringHelper;
355 public InputStream openStream() throws IOException {
356 return getClass().getResourceAsStream(resource);
360 }, PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
363 private static InetSocketAddress getAddress(final String ip, final int port) {
365 return new InetSocketAddress(Inet4Address.getByName(ip), port);
366 } catch (final UnknownHostException e) {
367 throw new RuntimeException(e);
372 public void close() {
373 for (final SshProxyServer sshWrapper : sshWrappers) {
376 for (final Channel deviceCh : devicesChannels) {
379 nettyThreadgroup.shutdownGracefully();
380 minaTimerExecutor.shutdownNow();
381 nioExecutor.shutdownNow();