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.MoreObjects;
12 import com.google.common.base.Optional;
13 import com.google.common.collect.Collections2;
14 import com.google.common.collect.Lists;
15 import com.google.common.collect.Sets;
16 import com.google.common.util.concurrent.CheckedFuture;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ThreadFactoryBuilder;
19 import io.netty.channel.Channel;
20 import io.netty.channel.ChannelFuture;
21 import io.netty.channel.local.LocalAddress;
22 import io.netty.channel.nio.NioEventLoopGroup;
23 import io.netty.util.HashedWheelTimer;
24 import java.io.Closeable;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.net.BindException;
28 import java.net.Inet4Address;
29 import java.net.InetSocketAddress;
30 import java.net.UnknownHostException;
31 import java.nio.file.Files;
32 import java.nio.file.Path;
33 import java.util.List;
35 import java.util.concurrent.ExecutionException;
36 import java.util.concurrent.ExecutorService;
37 import java.util.concurrent.Executors;
38 import java.util.concurrent.ScheduledExecutorService;
39 import org.apache.sshd.common.util.ThreadUtils;
40 import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
41 import org.opendaylight.controller.config.util.capability.BasicCapability;
42 import org.opendaylight.controller.config.util.capability.Capability;
43 import org.opendaylight.controller.config.util.capability.YangModuleCapability;
44 import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
45 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
46 import org.opendaylight.netconf.impl.NetconfServerDispatcherImpl;
47 import org.opendaylight.netconf.impl.NetconfServerSessionNegotiatorFactory;
48 import org.opendaylight.netconf.impl.SessionIdProvider;
49 import org.opendaylight.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
50 import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactory;
51 import org.opendaylight.netconf.monitoring.osgi.NetconfMonitoringActivator;
52 import org.opendaylight.netconf.monitoring.osgi.NetconfMonitoringOperationService;
53 import org.opendaylight.netconf.ssh.SshProxyServer;
54 import org.opendaylight.netconf.ssh.SshProxyServerConfiguration;
55 import org.opendaylight.netconf.ssh.SshProxyServerConfigurationBuilder;
56 import org.opendaylight.netconf.test.tool.customrpc.SettableOperationProvider;
57 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
58 import org.opendaylight.yangtools.yang.model.api.Module;
59 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
60 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
61 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
62 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
63 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
64 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
65 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
66 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
67 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
68 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
69 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
70 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
71 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
72 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
76 public class NetconfDeviceSimulator implements Closeable {
78 private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSimulator.class);
80 private final NioEventLoopGroup nettyThreadgroup;
81 private final HashedWheelTimer hashedWheelTimer;
82 private final List<Channel> devicesChannels = Lists.newArrayList();
83 private final List<SshProxyServer> sshWrappers = Lists.newArrayList();
84 private final ScheduledExecutorService minaTimerExecutor;
85 private final ExecutorService nioExecutor;
86 private SchemaContext schemaContext;
88 private boolean sendFakeSchema = false;
90 public NetconfDeviceSimulator(final int threadPoolSize) {
91 this(new NioEventLoopGroup(), new HashedWheelTimer(),
92 Executors.newScheduledThreadPool(threadPoolSize,
93 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,
98 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,
106 final SchemaSourceProvider<YangTextSchemaSource> sourceProvider, final TesttoolParameters params) {
108 final Set<Capability> transformedCapabilities = Sets.newHashSet(Collections2.transform(capabilities, input -> {
109 if (sendFakeSchema) {
110 sendFakeSchema = false;
111 return new FakeCapability((YangModuleCapability) input);
116 transformedCapabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0"));
117 final NetconfMonitoringService monitoringService1 = new DummyMonitoringService(transformedCapabilities);
118 final SessionIdProvider idProvider = new SessionIdProvider();
120 final NetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory = createOperationServiceFactory(
121 sourceProvider, params, transformedCapabilities, monitoringService1, idProvider);
123 final Set<String> serverCapabilities = params.exi
124 ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES
125 : Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
126 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
128 final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new TesttoolNegotiationFactory(
129 hashedWheelTimer, aggregatedNetconfOperationServiceFactory, idProvider, params.generateConfigsTimeout,
130 monitoringService1, serverCapabilities);
132 final NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer =
133 new NetconfServerDispatcherImpl.ServerChannelInitializer(serverNegotiatorFactory);
134 return new NetconfServerDispatcherImpl(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
137 private NetconfOperationServiceFactory createOperationServiceFactory(
138 final SchemaSourceProvider<YangTextSchemaSource> sourceProvider, final TesttoolParameters params,
139 final Set<Capability> transformedCapabilities, final NetconfMonitoringService monitoringService1,
140 final SessionIdProvider idProvider) {
141 final AggregatedNetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory =
142 new AggregatedNetconfOperationServiceFactory();
144 final NetconfOperationServiceFactory operationProvider;
146 operationProvider = new MdsalOperationProvider(
147 idProvider, transformedCapabilities, schemaContext, sourceProvider);
149 operationProvider = new SimulatedOperationProvider(idProvider, transformedCapabilities,
150 Optional.fromNullable(params.notificationFile),
151 Optional.fromNullable(params.initialConfigXMLFile));
155 final NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory monitoringService =
156 new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(
157 new NetconfMonitoringOperationService(monitoringService1));
158 aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(operationProvider);
159 aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(monitoringService);
160 if (params.rpcConfig != null) {
161 final SettableOperationProvider settableService = new SettableOperationProvider(params.rpcConfig);
162 aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(settableService);
164 return aggregatedNetconfOperationServiceFactory;
167 public List<Integer> start(final TesttoolParameters params) {
168 LOG.info("Starting {}, {} simulated devices starting on port {}",
169 params.deviceCount, params.ssh ? "SSH" : "TCP", params.startingPort);
171 final SharedSchemaRepository schemaRepo = new SharedSchemaRepository("netconf-simulator");
172 final Set<Capability> capabilities = parseSchemasToModuleCapabilities(params, schemaRepo);
174 final NetconfServerDispatcherImpl dispatcher = createDispatcher(capabilities,
175 sourceIdentifier -> schemaRepo.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class), params);
177 int currentPort = params.startingPort;
179 final List<Integer> openDevices = Lists.newArrayList();
181 // Generate key to temp folder
182 final PEMGeneratorHostKeyProvider keyPairProvider = getPemGeneratorHostKeyProvider();
184 for (int i = 0; i < params.deviceCount; i++) {
185 if (currentPort > 65535) {
186 LOG.warn("Port cannot be greater than 65535, stopping further attempts.");
189 final InetSocketAddress address = getAddress(params.ip, currentPort);
191 final ChannelFuture server;
193 final InetSocketAddress bindingAddress = InetSocketAddress.createUnresolved("0.0.0.0", currentPort);
194 final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());
196 server = dispatcher.createLocalServer(tcpLocalAddress);
198 final SshProxyServer sshServer = new SshProxyServer(
199 minaTimerExecutor, nettyThreadgroup, nioExecutor);
200 sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress, keyPairProvider));
201 sshWrappers.add(sshServer);
202 } catch (final BindException e) {
203 LOG.warn("Cannot start simulated device on {}, port already in use. Skipping.", address);
204 // Close local server and continue
206 if (server.isDone()) {
207 server.channel().close();
210 } catch (final IOException e) {
211 LOG.warn("Cannot start simulated device on {} due to IOException.", address, e);
219 } catch (final InterruptedException e) {
220 throw new RuntimeException(e);
221 } catch (final ExecutionException e) {
222 LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
226 LOG.debug("Simulated SSH device started on {}", address);
229 server = dispatcher.createServer(address);
234 } catch (final InterruptedException e) {
235 throw new RuntimeException(e);
236 } catch (final ExecutionException e) {
237 LOG.warn("Cannot start tcp simulated device on {}, skipping", address, e);
241 LOG.debug("Simulated TCP device started on {}", address);
244 devicesChannels.add(server.channel());
245 openDevices.add(currentPort - 1);
248 if (openDevices.size() == params.deviceCount) {
249 LOG.info("All simulated devices started successfully from port {} to {}",
250 params.startingPort, currentPort - 1);
251 } else if (openDevices.size() == 0) {
252 LOG.warn("No simulated devices started.");
254 LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
260 private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress,
261 final LocalAddress tcpLocalAddress, final PEMGeneratorHostKeyProvider keyPairProvider) throws IOException {
262 return new SshProxyServerConfigurationBuilder()
263 .setBindingAddress(bindingAddress)
264 .setLocalAddress(tcpLocalAddress)
265 .setAuthenticator((username, password) -> true)
266 .setKeyPairProvider(keyPairProvider)
267 .setIdleTimeout(Integer.MAX_VALUE)
268 .createSshProxyServerConfiguration();
271 private PEMGeneratorHostKeyProvider getPemGeneratorHostKeyProvider() {
273 final Path tempFile = Files.createTempFile("tempKeyNetconfTest", "suffix");
274 return new PEMGeneratorHostKeyProvider(tempFile.toAbsolutePath().toString(), "RSA", 4096);
275 } catch (final IOException e) {
276 LOG.error("Unable to generate PEM key", e);
277 throw new RuntimeException(e);
281 private Set<Capability> parseSchemasToModuleCapabilities(final TesttoolParameters params,
282 final SharedSchemaRepository consumer) {
283 final Set<SourceIdentifier> loadedSources = Sets.newHashSet();
285 consumer.registerSchemaSourceListener(TextToASTTransformer.create(consumer, consumer));
287 consumer.registerSchemaSourceListener(new SchemaSourceListener() {
289 public void schemaSourceEncountered(final SchemaSourceRepresentation schemaSourceRepresentation) {}
292 public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> potentialSchemaSources) {
293 for (final PotentialSchemaSource<?> potentialSchemaSource : potentialSchemaSources) {
294 loadedSources.add(potentialSchemaSource.getSourceIdentifier());
299 public void schemaSourceUnregistered(final PotentialSchemaSource<?> potentialSchemaSource) {}
302 if (params.schemasDir != null) {
303 final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(
304 consumer, YangTextSchemaSource.class, params.schemasDir);
305 consumer.registerSchemaSourceListener(cache);
308 addDefaultSchemas(consumer);
311 //necessary for creating mdsal data stores and operations
312 this.schemaContext = consumer.createSchemaContextFactory(
313 SchemaSourceFilter.ALWAYS_ACCEPT)
314 .createSchemaContext(loadedSources).checkedGet();
315 } catch (final SchemaResolutionException e) {
316 throw new RuntimeException("Cannot parse schema context", e);
319 final Set<Capability> capabilities = Sets.newHashSet();
321 for (final Module module : schemaContext.getModules()) {
322 for (final Module subModule : module.getSubmodules()) {
323 addModuleCapability(consumer, capabilities, subModule);
325 addModuleCapability(consumer, capabilities, module);
330 private void addModuleCapability(final SharedSchemaRepository consumer, final Set<Capability> capabilities,
331 final Module module) {
332 final SourceIdentifier moduleSourceIdentifier = SourceIdentifier.create(module.getName(),
333 (SimpleDateFormatUtil.DEFAULT_DATE_REV == module.getRevision() ? Optional.absent() :
334 Optional.of(module.getQNameModule().getFormattedRevision())));
336 final String moduleContent = new String(
337 consumer.getSchemaSource(moduleSourceIdentifier, YangTextSchemaSource.class).checkedGet().read());
338 capabilities.add(new YangModuleCapability(module, moduleContent));
339 //IOException would be thrown in creating SchemaContext already
340 } catch (SchemaSourceException | IOException e) {
341 throw new RuntimeException("Cannot retrieve schema source for module "
342 + moduleSourceIdentifier.toString() + " from schema repository", e);
346 private void addDefaultSchemas(final SharedSchemaRepository consumer) {
347 SourceIdentifier srcId = RevisionSourceIdentifier.create("ietf-netconf-monitoring", "2010-10-04");
348 registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring.yang", srcId);
350 srcId = RevisionSourceIdentifier.create("ietf-netconf-monitoring-extension", "2013-12-10");
351 registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring-extension.yang", srcId);
353 srcId = RevisionSourceIdentifier.create("ietf-yang-types", "2013-07-15");
354 registerSource(consumer, "/META-INF/yang/ietf-yang-types@2013-07-15.yang", srcId);
356 srcId = RevisionSourceIdentifier.create("ietf-inet-types", "2013-07-15");
357 registerSource(consumer, "/META-INF/yang/ietf-inet-types@2013-07-15.yang", srcId);
360 private void registerSource(final SharedSchemaRepository consumer, final String resource,
361 final SourceIdentifier sourceId) {
362 consumer.registerSchemaSource(new SchemaSourceProvider<SchemaSourceRepresentation>() {
364 public CheckedFuture<? extends SchemaSourceRepresentation, SchemaSourceException> getSource(
365 final SourceIdentifier sourceIdentifier) {
366 return Futures.immediateCheckedFuture(new YangTextSchemaSource(sourceId) {
368 protected MoreObjects.ToStringHelper addToStringAttributes(
369 final MoreObjects.ToStringHelper toStringHelper) {
370 return toStringHelper;
374 public InputStream openStream() throws IOException {
375 return getClass().getResourceAsStream(resource);
379 }, PotentialSchemaSource.create(
380 sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
383 private static InetSocketAddress getAddress(final String ip, final int port) {
385 return new InetSocketAddress(Inet4Address.getByName(ip), port);
386 } catch (final UnknownHostException e) {
387 throw new RuntimeException(e);
392 public void close() {
393 for (final SshProxyServer sshWrapper : sshWrappers) {
396 for (final Channel deviceCh : devicesChannels) {
399 nettyThreadgroup.shutdownGracefully();
400 minaTimerExecutor.shutdownNow();
401 nioExecutor.shutdownNow();