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, final Optional<File> notificationsFile, final boolean mdSal, final Optional<File> initialConfigXMLFile) {
107 final Set<Capability> transformedCapabilities = Sets.newHashSet(Collections2.transform(capabilities, new Function<Capability, Capability>() {
109 public Capability apply(final Capability input) {
110 if (sendFakeSchema) {
111 sendFakeSchema = false;
112 return new FakeCapability((YangModuleCapability) input);
119 final SessionIdProvider idProvider = new SessionIdProvider();
121 final AggregatedNetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory = new AggregatedNetconfOperationServiceFactory();
122 final NetconfOperationServiceFactory operationProvider = mdSal ? new MdsalOperationProvider(idProvider, transformedCapabilities, schemaContext) :
123 new SimulatedOperationProvider(idProvider, transformedCapabilities, notificationsFile, initialConfigXMLFile);
125 transformedCapabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0"));
127 final NetconfMonitoringService monitoringService1 = new DummyMonitoringService(transformedCapabilities);
129 final NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory monitoringService =
130 new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(
131 new NetconfMonitoringOperationService(monitoringService1));
132 aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(operationProvider);
133 aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(monitoringService);
135 final Set<String> serverCapabilities = exi
136 ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES
137 : Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0, XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
139 final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new TesttoolNegotiationFactory(
140 hashedWheelTimer, aggregatedNetconfOperationServiceFactory, idProvider, generateConfigsTimeout, monitoringService1, serverCapabilities);
142 final NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(
143 serverNegotiatorFactory);
144 return new NetconfServerDispatcherImpl(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
147 public List<Integer> start(final Main.Params params) {
148 LOG.info("Starting {}, {} simulated devices starting on port {}", params.deviceCount, params.ssh ? "SSH" : "TCP", params.startingPort);
150 final Set<Capability> capabilities = parseSchemasToModuleCapabilities(params);
152 final NetconfServerDispatcherImpl dispatcher = createDispatcher(capabilities, params.exi, params.generateConfigsTimeout,
153 Optional.fromNullable(params.notificationFile), params.mdSal, Optional.fromNullable(params.initialConfigXMLFile));
155 int currentPort = params.startingPort;
157 final List<Integer> openDevices = Lists.newArrayList();
159 // Generate key to temp folder
160 final PEMGeneratorHostKeyProvider keyPairProvider = getPemGeneratorHostKeyProvider();
162 for (int i = 0; i < params.deviceCount; i++) {
163 if (currentPort > 65535) {
164 LOG.warn("Port cannot be greater than 65535, stopping further attempts.");
167 final InetSocketAddress address = getAddress(currentPort);
169 final ChannelFuture server;
171 final InetSocketAddress bindingAddress = InetSocketAddress.createUnresolved("0.0.0.0", currentPort);
172 final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());
174 server = dispatcher.createLocalServer(tcpLocalAddress);
176 final SshProxyServer sshServer = new SshProxyServer(minaTimerExecutor, nettyThreadgroup, nioExecutor);
177 sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress, keyPairProvider));
178 sshWrappers.add(sshServer);
179 } catch (final BindException e) {
180 LOG.warn("Cannot start simulated device on {}, port already in use. Skipping.", address);
181 // Close local server and continue
183 if(server.isDone()) {
184 server.channel().close();
187 } catch (final IOException e) {
188 LOG.warn("Cannot start simulated device on {} due to IOException.", address, e);
196 } catch (final InterruptedException e) {
197 throw new RuntimeException(e);
198 } catch (final ExecutionException e) {
199 LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
203 LOG.debug("Simulated SSH device started on {}", address);
206 server = dispatcher.createServer(address);
211 } catch (final InterruptedException e) {
212 throw new RuntimeException(e);
213 } catch (final ExecutionException e) {
214 LOG.warn("Cannot start tcp simulated device on {}, skipping", address, e);
218 LOG.debug("Simulated TCP device started on {}", address);
221 devicesChannels.add(server.channel());
222 openDevices.add(currentPort - 1);
225 if(openDevices.size() == params.deviceCount) {
226 LOG.info("All simulated devices started successfully from port {} to {}", params.startingPort, currentPort - 1);
227 } else if (openDevices.size() == 0) {
228 LOG.warn("No simulated devices started.");
230 LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
236 private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress, final LocalAddress tcpLocalAddress, final PEMGeneratorHostKeyProvider keyPairProvider) throws IOException {
237 return new SshProxyServerConfigurationBuilder()
238 .setBindingAddress(bindingAddress)
239 .setLocalAddress(tcpLocalAddress)
240 .setAuthenticator(new AuthProvider() {
242 public boolean authenticated(final String username, final String password) {
246 .setKeyPairProvider(keyPairProvider)
247 .setIdleTimeout(Integer.MAX_VALUE)
248 .createSshProxyServerConfiguration();
251 private PEMGeneratorHostKeyProvider getPemGeneratorHostKeyProvider() {
253 final Path tempFile = Files.createTempFile("tempKeyNetconfTest", "suffix");
254 return new PEMGeneratorHostKeyProvider(tempFile.toAbsolutePath().toString());
255 } catch (final IOException e) {
256 LOG.error("Unable to generate PEM key", e);
257 throw new RuntimeException(e);
261 private Set<Capability> parseSchemasToModuleCapabilities(final Main.Params params) {
262 final SharedSchemaRepository consumer = new SharedSchemaRepository("netconf-simulator");
263 final Set<SourceIdentifier> loadedSources = Sets.newHashSet();
265 consumer.registerSchemaSourceListener(TextToASTTransformer.create(consumer, consumer));
267 consumer.registerSchemaSourceListener(new SchemaSourceListener() {
269 public void schemaSourceEncountered(final SchemaSourceRepresentation schemaSourceRepresentation) {}
272 public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> potentialSchemaSources) {
273 for (final PotentialSchemaSource<?> potentialSchemaSource : potentialSchemaSources) {
274 loadedSources.add(potentialSchemaSource.getSourceIdentifier());
279 public void schemaSourceUnregistered(final PotentialSchemaSource<?> potentialSchemaSource) {}
282 if(params.schemasDir != null) {
283 final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(consumer, YangTextSchemaSource.class, params.schemasDir);
284 consumer.registerSchemaSourceListener(cache);
287 addDefaultSchemas(consumer);
290 //necessary for creating mdsal data stores and operations
291 this.schemaContext = consumer.createSchemaContextFactory(
292 SchemaSourceFilter.ALWAYS_ACCEPT)
293 .createSchemaContext(loadedSources).checkedGet();
294 } catch (final SchemaResolutionException e) {
295 throw new RuntimeException("Cannot parse schema context", e);
298 final Set<Capability> capabilities = Sets.newHashSet();
300 for (final Module module : schemaContext.getModules()) {
301 for (final Module subModule : module.getSubmodules()) {
302 addModuleCapability(consumer, capabilities, subModule);
304 addModuleCapability(consumer, capabilities, module);
309 private void addModuleCapability(SharedSchemaRepository consumer, Set<Capability> capabilities, Module module) {
310 final SourceIdentifier moduleSourceIdentifier = SourceIdentifier.create(module.getName(),
311 (SimpleDateFormatUtil.DEFAULT_DATE_REV == module.getRevision() ? Optional.<String>absent() :
312 Optional.of(SimpleDateFormatUtil.getRevisionFormat().format(module.getRevision()))));
314 String moduleContent = new String(consumer.getSchemaSource(moduleSourceIdentifier, YangTextSchemaSource.class)
315 .checkedGet().read());
316 capabilities.add(new YangModuleCapability(module, moduleContent));
317 //IOException would be thrown in creating SchemaContext already
318 } catch (SchemaSourceException |IOException e) {
319 throw new RuntimeException("Cannot retrieve schema source for module " + moduleSourceIdentifier.toString() + " from schema repository", e);
323 private void addDefaultSchemas(final SharedSchemaRepository consumer) {
324 SourceIdentifier sId = new SourceIdentifier("ietf-netconf-monitoring", "2010-10-04");
325 registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring.yang", sId);
327 sId = new SourceIdentifier("ietf-netconf-monitoring-extension", "2013-12-10");
328 registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring-extension.yang", sId);
330 sId = new SourceIdentifier("ietf-yang-types", "2010-09-24");
331 registerSource(consumer, "/META-INF/yang/ietf-yang-types.yang", sId);
333 sId = new SourceIdentifier("ietf-inet-types", "2010-09-24");
334 registerSource(consumer, "/META-INF/yang/ietf-inet-types.yang", sId);
337 private void registerSource(final SharedSchemaRepository consumer, final String resource, final SourceIdentifier sourceId) {
338 consumer.registerSchemaSource(new SchemaSourceProvider<SchemaSourceRepresentation>() {
340 public CheckedFuture<? extends SchemaSourceRepresentation, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
341 return Futures.immediateCheckedFuture(new YangTextSchemaSource(sourceId) {
343 protected MoreObjects.ToStringHelper addToStringAttributes(final MoreObjects.ToStringHelper toStringHelper) {
344 return toStringHelper;
348 public InputStream openStream() throws IOException {
349 return getClass().getResourceAsStream(resource);
353 }, PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
356 private static InetSocketAddress getAddress(final int port) {
358 // TODO make address configurable
359 return new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), port);
360 } catch (final UnknownHostException e) {
361 throw new RuntimeException(e);
366 public void close() {
367 for (final SshProxyServer sshWrapper : sshWrappers) {
370 for (final Channel deviceCh : devicesChannels) {
373 nettyThreadgroup.shutdownGracefully();
374 minaTimerExecutor.shutdownNow();
375 nioExecutor.shutdownNow();