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;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.net.BindException;
29 import java.net.Inet4Address;
30 import java.net.InetSocketAddress;
31 import java.net.UnknownHostException;
32 import java.nio.file.Files;
33 import java.nio.file.Path;
34 import java.util.List;
36 import java.util.concurrent.ExecutionException;
37 import java.util.concurrent.ExecutorService;
38 import java.util.concurrent.Executors;
39 import java.util.concurrent.ScheduledExecutorService;
40 import org.apache.sshd.common.util.ThreadUtils;
41 import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
42 import org.opendaylight.controller.config.util.capability.BasicCapability;
43 import org.opendaylight.controller.config.util.capability.Capability;
44 import org.opendaylight.controller.config.util.capability.YangModuleCapability;
45 import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
46 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
47 import org.opendaylight.netconf.auth.AuthProvider;
48 import org.opendaylight.netconf.impl.NetconfServerDispatcherImpl;
49 import org.opendaylight.netconf.impl.NetconfServerSessionNegotiatorFactory;
50 import org.opendaylight.netconf.impl.SessionIdProvider;
51 import org.opendaylight.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
52 import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactory;
53 import org.opendaylight.netconf.monitoring.osgi.NetconfMonitoringActivator;
54 import org.opendaylight.netconf.monitoring.osgi.NetconfMonitoringOperationService;
55 import org.opendaylight.netconf.ssh.SshProxyServer;
56 import org.opendaylight.netconf.ssh.SshProxyServerConfiguration;
57 import org.opendaylight.netconf.ssh.SshProxyServerConfigurationBuilder;
58 import org.opendaylight.netconf.test.tool.customrpc.SettableOperationProvider;
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.RevisionSourceIdentifier;
63 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
64 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
65 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
66 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
67 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
68 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
69 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
70 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
71 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
72 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
73 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
74 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
78 public class NetconfDeviceSimulator implements Closeable {
80 private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSimulator.class);
82 private final NioEventLoopGroup nettyThreadgroup;
83 private final HashedWheelTimer hashedWheelTimer;
84 private final List<Channel> devicesChannels = Lists.newArrayList();
85 private final List<SshProxyServer> sshWrappers = Lists.newArrayList();
86 private final ScheduledExecutorService minaTimerExecutor;
87 private final ExecutorService nioExecutor;
88 private SchemaContext schemaContext;
90 private boolean sendFakeSchema = false;
92 public NetconfDeviceSimulator(final int ThreadPoolSize) {
93 this(new NioEventLoopGroup(), new HashedWheelTimer(),
94 Executors.newScheduledThreadPool(ThreadPoolSize, new ThreadFactoryBuilder().setNameFormat("netconf-ssh-server-mina-timers-%d").build()),
95 ThreadUtils.newFixedThreadPool("netconf-ssh-server-nio-group", ThreadPoolSize));
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,
106 final SchemaSourceProvider<YangTextSchemaSource> sourceProvider,
107 final TesttoolParameters params) {
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);
120 transformedCapabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0"));
121 final NetconfMonitoringService monitoringService1 = new DummyMonitoringService(transformedCapabilities);
122 final SessionIdProvider idProvider = new SessionIdProvider();
124 final NetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory = createOperationServiceFactory(sourceProvider, params, transformedCapabilities, monitoringService1, idProvider);
126 final Set<String> serverCapabilities = params.exi
127 ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES
128 : Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0, XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
130 final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new TesttoolNegotiationFactory(
131 hashedWheelTimer, aggregatedNetconfOperationServiceFactory, idProvider, params.generateConfigsTimeout, monitoringService1, serverCapabilities);
133 final NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(
134 serverNegotiatorFactory);
135 return new NetconfServerDispatcherImpl(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
138 private NetconfOperationServiceFactory createOperationServiceFactory(final SchemaSourceProvider<YangTextSchemaSource> sourceProvider,
139 final TesttoolParameters params,
140 final Set<Capability> transformedCapabilities,
141 final NetconfMonitoringService monitoringService1,
142 final SessionIdProvider idProvider) {
143 final AggregatedNetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory = new AggregatedNetconfOperationServiceFactory();
145 final NetconfOperationServiceFactory operationProvider;
147 operationProvider = new MdsalOperationProvider(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 {}", params.deviceCount, params.ssh ? "SSH" : "TCP", params.startingPort);
170 final SharedSchemaRepository schemaRepo = new SharedSchemaRepository("netconf-simulator");
171 final Set<Capability> capabilities = parseSchemasToModuleCapabilities(params, schemaRepo);
173 final NetconfServerDispatcherImpl dispatcher = createDispatcher(capabilities,
174 new SchemaSourceProvider<YangTextSchemaSource>() {
176 public CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
177 return schemaRepo.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class);
181 int currentPort = params.startingPort;
183 final List<Integer> openDevices = Lists.newArrayList();
185 // Generate key to temp folder
186 final PEMGeneratorHostKeyProvider keyPairProvider = getPemGeneratorHostKeyProvider();
188 for (int i = 0; i < params.deviceCount; i++) {
189 if (currentPort > 65535) {
190 LOG.warn("Port cannot be greater than 65535, stopping further attempts.");
193 final InetSocketAddress address = getAddress(params.ip, currentPort);
195 final ChannelFuture server;
197 final InetSocketAddress bindingAddress = InetSocketAddress.createUnresolved("0.0.0.0", currentPort);
198 final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());
200 server = dispatcher.createLocalServer(tcpLocalAddress);
202 final SshProxyServer sshServer = new SshProxyServer(minaTimerExecutor, nettyThreadgroup, nioExecutor);
203 sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress, keyPairProvider));
204 sshWrappers.add(sshServer);
205 } catch (final BindException e) {
206 LOG.warn("Cannot start simulated device on {}, port already in use. Skipping.", address);
207 // Close local server and continue
209 if(server.isDone()) {
210 server.channel().close();
213 } catch (final IOException e) {
214 LOG.warn("Cannot start simulated device on {} due to IOException.", address, e);
222 } catch (final InterruptedException e) {
223 throw new RuntimeException(e);
224 } catch (final ExecutionException e) {
225 LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
229 LOG.debug("Simulated SSH device started on {}", address);
232 server = dispatcher.createServer(address);
237 } catch (final InterruptedException e) {
238 throw new RuntimeException(e);
239 } catch (final ExecutionException e) {
240 LOG.warn("Cannot start tcp simulated device on {}, skipping", address, e);
244 LOG.debug("Simulated TCP device started on {}", address);
247 devicesChannels.add(server.channel());
248 openDevices.add(currentPort - 1);
251 if(openDevices.size() == params.deviceCount) {
252 LOG.info("All simulated devices started successfully from port {} to {}", params.startingPort, currentPort - 1);
253 } else if (openDevices.size() == 0) {
254 LOG.warn("No simulated devices started.");
256 LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
262 private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress, final LocalAddress tcpLocalAddress, final PEMGeneratorHostKeyProvider keyPairProvider) throws IOException {
263 return new SshProxyServerConfigurationBuilder()
264 .setBindingAddress(bindingAddress)
265 .setLocalAddress(tcpLocalAddress)
266 .setAuthenticator(new AuthProvider() {
268 public boolean authenticated(final String username, final String password) {
272 .setKeyPairProvider(keyPairProvider)
273 .setIdleTimeout(Integer.MAX_VALUE)
274 .createSshProxyServerConfiguration();
277 private PEMGeneratorHostKeyProvider getPemGeneratorHostKeyProvider() {
279 final Path tempFile = Files.createTempFile("tempKeyNetconfTest", "suffix");
280 return new PEMGeneratorHostKeyProvider(tempFile.toAbsolutePath().toString());
281 } catch (final IOException e) {
282 LOG.error("Unable to generate PEM key", e);
283 throw new RuntimeException(e);
287 private Set<Capability> parseSchemasToModuleCapabilities(final TesttoolParameters params, final SharedSchemaRepository consumer) {
288 final Set<SourceIdentifier> loadedSources = Sets.newHashSet();
290 consumer.registerSchemaSourceListener(TextToASTTransformer.create(consumer, consumer));
292 consumer.registerSchemaSourceListener(new SchemaSourceListener() {
294 public void schemaSourceEncountered(final SchemaSourceRepresentation schemaSourceRepresentation) {}
297 public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> potentialSchemaSources) {
298 for (final PotentialSchemaSource<?> potentialSchemaSource : potentialSchemaSources) {
299 loadedSources.add(potentialSchemaSource.getSourceIdentifier());
304 public void schemaSourceUnregistered(final PotentialSchemaSource<?> potentialSchemaSource) {}
307 if(params.schemasDir != null) {
308 final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(consumer, YangTextSchemaSource.class, params.schemasDir);
309 consumer.registerSchemaSourceListener(cache);
312 addDefaultSchemas(consumer);
315 //necessary for creating mdsal data stores and operations
316 this.schemaContext = consumer.createSchemaContextFactory(
317 SchemaSourceFilter.ALWAYS_ACCEPT)
318 .createSchemaContext(loadedSources).checkedGet();
319 } catch (final SchemaResolutionException e) {
320 throw new RuntimeException("Cannot parse schema context", e);
323 final Set<Capability> capabilities = Sets.newHashSet();
325 for (final Module module : schemaContext.getModules()) {
326 for (final Module subModule : module.getSubmodules()) {
327 addModuleCapability(consumer, capabilities, subModule);
329 addModuleCapability(consumer, capabilities, module);
334 private void addModuleCapability(final SharedSchemaRepository consumer, final Set<Capability> capabilities, final Module module) {
335 final SourceIdentifier moduleSourceIdentifier = SourceIdentifier.create(module.getName(),
336 (SimpleDateFormatUtil.DEFAULT_DATE_REV == module.getRevision() ? Optional.<String>absent() :
337 Optional.of(module.getQNameModule().getFormattedRevision())));
339 final String moduleContent = new String(consumer.getSchemaSource(moduleSourceIdentifier, YangTextSchemaSource.class)
340 .checkedGet().read());
341 capabilities.add(new YangModuleCapability(module, moduleContent));
342 //IOException would be thrown in creating SchemaContext already
343 } catch (SchemaSourceException |IOException e) {
344 throw new RuntimeException("Cannot retrieve schema source for module " + moduleSourceIdentifier.toString() + " from schema repository", e);
348 private void addDefaultSchemas(final SharedSchemaRepository consumer) {
349 SourceIdentifier sId = RevisionSourceIdentifier.create("ietf-netconf-monitoring", "2010-10-04");
350 registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring.yang", sId);
352 sId = RevisionSourceIdentifier.create("ietf-netconf-monitoring-extension", "2013-12-10");
353 registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring-extension.yang", sId);
355 sId = RevisionSourceIdentifier.create("ietf-yang-types", "2013-07-15");
356 registerSource(consumer, "/META-INF/yang/ietf-yang-types@2013-07-15.yang", sId);
358 sId = RevisionSourceIdentifier.create("ietf-inet-types", "2013-07-15");
359 registerSource(consumer, "/META-INF/yang/ietf-inet-types@2013-07-15.yang", sId);
362 private void registerSource(final SharedSchemaRepository consumer, final String resource, final SourceIdentifier sourceId) {
363 consumer.registerSchemaSource(new SchemaSourceProvider<SchemaSourceRepresentation>() {
365 public CheckedFuture<? extends SchemaSourceRepresentation, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
366 return Futures.immediateCheckedFuture(new YangTextSchemaSource(sourceId) {
368 protected MoreObjects.ToStringHelper addToStringAttributes(final MoreObjects.ToStringHelper toStringHelper) {
369 return toStringHelper;
373 public InputStream openStream() throws IOException {
374 return getClass().getResourceAsStream(resource);
378 }, PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
381 private static InetSocketAddress getAddress(final String ip, final int port) {
383 return new InetSocketAddress(Inet4Address.getByName(ip), port);
384 } catch (final UnknownHostException e) {
385 throw new RuntimeException(e);
390 public void close() {
391 for (final SshProxyServer sshWrapper : sshWrappers) {
394 for (final Channel deviceCh : devicesChannels) {
397 nettyThreadgroup.shutdownGracefully();
398 minaTimerExecutor.shutdownNow();
399 nioExecutor.shutdownNow();