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
8 package org.opendaylight.netconf.test.tool;
10 import com.google.common.collect.Collections2;
11 import com.google.common.util.concurrent.Futures;
12 import com.google.common.util.concurrent.ThreadFactoryBuilder;
13 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
14 import io.netty.channel.Channel;
15 import io.netty.channel.ChannelFuture;
16 import io.netty.channel.local.LocalAddress;
17 import io.netty.channel.nio.NioEventLoopGroup;
18 import io.netty.util.HashedWheelTimer;
19 import java.io.Closeable;
20 import java.io.IOException;
21 import java.net.BindException;
22 import java.net.Inet4Address;
23 import java.net.InetSocketAddress;
24 import java.net.UnknownHostException;
25 import java.nio.channels.AsynchronousChannelGroup;
26 import java.util.ArrayList;
27 import java.util.HashSet;
28 import java.util.List;
29 import java.util.Optional;
31 import java.util.concurrent.ExecutionException;
32 import java.util.concurrent.ExecutorService;
33 import java.util.concurrent.Executors;
34 import java.util.concurrent.ScheduledExecutorService;
35 import org.opendaylight.netconf.api.capability.BasicCapability;
36 import org.opendaylight.netconf.api.capability.Capability;
37 import org.opendaylight.netconf.api.capability.YangModuleCapability;
38 import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
39 import org.opendaylight.netconf.impl.NetconfServerDispatcherImpl;
40 import org.opendaylight.netconf.impl.NetconfServerSessionNegotiatorFactory;
41 import org.opendaylight.netconf.impl.ServerChannelInitializer;
42 import org.opendaylight.netconf.impl.SessionIdProvider;
43 import org.opendaylight.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
44 import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactory;
45 import org.opendaylight.netconf.shaded.sshd.common.keyprovider.KeyPairProvider;
46 import org.opendaylight.netconf.shaded.sshd.common.util.threads.ThreadUtils;
47 import org.opendaylight.netconf.ssh.SshProxyServer;
48 import org.opendaylight.netconf.ssh.SshProxyServerConfiguration;
49 import org.opendaylight.netconf.ssh.SshProxyServerConfigurationBuilder;
50 import org.opendaylight.netconf.test.tool.config.Configuration;
51 import org.opendaylight.netconf.test.tool.customrpc.SettableOperationProvider;
52 import org.opendaylight.netconf.test.tool.monitoring.NetconfMonitoringOperationService;
53 import org.opendaylight.netconf.test.tool.monitoring.NetconfMonitoringOperationServiceFactory;
54 import org.opendaylight.netconf.test.tool.operations.DefaultOperationsCreator;
55 import org.opendaylight.netconf.test.tool.operations.OperationsProvider;
56 import org.opendaylight.netconf.test.tool.rpchandler.SettableOperationRpcProvider;
57 import org.opendaylight.netconf.test.tool.schemacache.SchemaSourceCache;
58 import org.opendaylight.yangtools.yang.common.Revision;
59 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
60 import org.opendaylight.yangtools.yang.model.api.Module;
61 import org.opendaylight.yangtools.yang.model.api.ModuleLike;
62 import org.opendaylight.yangtools.yang.model.api.Submodule;
63 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
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.fs.FilesystemSchemaSourceCache;
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.parser.repo.SharedSchemaRepository;
72 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToIRTransformer;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
76 @SuppressFBWarnings("DM_DEFAULT_ENCODING")
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 = new ArrayList<>();
84 private final List<SshProxyServer> sshWrappers = new ArrayList<>();
85 private final ScheduledExecutorService minaTimerExecutor;
86 private final ExecutorService nioExecutor;
87 private final Configuration configuration;
88 private EffectiveModelContext schemaContext;
90 private boolean sendFakeSchema = false;
92 public NetconfDeviceSimulator(final Configuration configuration) {
93 this.configuration = configuration;
94 this.nettyThreadgroup = new NioEventLoopGroup();
95 this.hashedWheelTimer = new HashedWheelTimer();
96 this.minaTimerExecutor = Executors.newScheduledThreadPool(configuration.getThreadPoolSize(),
97 new ThreadFactoryBuilder().setNameFormat("netconf-ssh-server-mina-timers-%d").build());
98 this.nioExecutor = ThreadUtils
99 .newFixedThreadPool("netconf-ssh-server-nio-group", configuration.getThreadPoolSize());
102 private NetconfServerDispatcherImpl createDispatcher(final Set<Capability> capabilities,
103 final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
105 final Set<Capability> transformedCapabilities = new HashSet<>(Collections2.transform(capabilities, input -> {
106 if (sendFakeSchema) {
107 sendFakeSchema = false;
108 return new FakeCapability((YangModuleCapability) input);
113 transformedCapabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0"));
114 final NetconfMonitoringService monitoringService1 = new DummyMonitoringService(transformedCapabilities);
115 final SessionIdProvider idProvider = new SessionIdProvider();
117 final NetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory = createOperationServiceFactory(
118 sourceProvider, transformedCapabilities, monitoringService1, idProvider);
120 final Set<String> serverCapabilities = configuration.getCapabilities();
122 final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new TesttoolNegotiationFactory(
123 hashedWheelTimer, aggregatedNetconfOperationServiceFactory, idProvider,
124 configuration.getGenerateConfigsTimeout(),
125 monitoringService1, serverCapabilities);
127 final ServerChannelInitializer serverChannelInitializer =
128 new ServerChannelInitializer(serverNegotiatorFactory);
129 return new NetconfServerDispatcherImpl(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
132 private NetconfOperationServiceFactory createOperationServiceFactory(
133 final SchemaSourceProvider<YangTextSchemaSource> sourceProvider,
134 final Set<Capability> transformedCapabilities, final NetconfMonitoringService monitoringService1,
135 final SessionIdProvider idProvider) {
136 final AggregatedNetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory =
137 new AggregatedNetconfOperationServiceFactory();
139 final NetconfOperationServiceFactory operationProvider;
140 if (configuration.isMdSal()) {
141 LOG.info("using MdsalOperationProvider.");
142 operationProvider = new MdsalOperationProvider(
143 idProvider, transformedCapabilities, schemaContext, sourceProvider);
144 } else if (configuration.isXmlConfigurationProvided()) {
145 LOG.info("using SimulatedOperationProvider.");
146 operationProvider = new SimulatedOperationProvider(idProvider, transformedCapabilities,
147 Optional.ofNullable(configuration.getNotificationFile()),
148 Optional.ofNullable(configuration.getInitialConfigXMLFile()));
150 LOG.info("using OperationsProvider.");
151 operationProvider = new OperationsProvider(idProvider, transformedCapabilities,
152 configuration.getOperationsCreator() != null ? configuration.getOperationsCreator()
153 : DefaultOperationsCreator.getDefaultOperationServiceCreator(idProvider.getCurrentSessionId()));
157 final NetconfMonitoringOperationServiceFactory monitoringService =
158 new NetconfMonitoringOperationServiceFactory(
159 new NetconfMonitoringOperationService(monitoringService1));
160 aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(operationProvider);
161 aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(monitoringService);
162 if (configuration.getRpcConfigFile() != null) {
163 final SettableOperationProvider settableService =
164 new SettableOperationProvider(configuration.getRpcConfigFile());
165 aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(settableService);
167 final SettableOperationRpcProvider settableService =
168 new SettableOperationRpcProvider(configuration.getRpcHandler());
169 aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(settableService);
171 return aggregatedNetconfOperationServiceFactory;
174 public List<Integer> start() {
175 LOG.info("Starting {}, {} simulated devices starting on port {}",
176 configuration.getDeviceCount(), configuration.isSsh() ? "SSH" : "TCP", configuration.getStartingPort());
178 final SharedSchemaRepository schemaRepo = new SharedSchemaRepository("netconf-simulator");
179 final Set<Capability> capabilities = parseSchemasToModuleCapabilities(schemaRepo);
181 final NetconfServerDispatcherImpl dispatcher = createDispatcher(capabilities,
182 sourceIdentifier -> schemaRepo.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class));
184 int currentPort = configuration.getStartingPort();
186 final List<Integer> openDevices = new ArrayList<>();
188 // Generate key to temp folder
189 final KeyPairProvider keyPairProvider = new VirtualKeyPairProvider();
191 final AsynchronousChannelGroup group;
193 group = AsynchronousChannelGroup.withThreadPool(nioExecutor);
194 } catch (final IOException e) {
195 throw new IllegalStateException("Failed to create group", e);
198 for (int i = 0; i < configuration.getDeviceCount(); i++) {
199 if (currentPort > 65535) {
200 LOG.warn("Port cannot be greater than 65535, stopping further attempts.");
203 final InetSocketAddress address = getAddress(configuration.getIp(), currentPort);
205 final ChannelFuture server;
206 if (configuration.isSsh()) {
207 final InetSocketAddress bindingAddress = InetSocketAddress.createUnresolved("0.0.0.0", currentPort);
208 final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());
210 server = dispatcher.createLocalServer(tcpLocalAddress);
212 final SshProxyServer sshServer = new SshProxyServer(
213 minaTimerExecutor, nettyThreadgroup, group);
214 sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress, keyPairProvider));
215 sshWrappers.add(sshServer);
216 } catch (final BindException e) {
217 LOG.warn("Cannot start simulated device on {}, port already in use. Skipping.", address);
218 // Close local server and continue
220 if (server.isDone()) {
221 server.channel().close();
224 } catch (final IOException e) {
225 LOG.warn("Cannot start simulated device on {} due to IOException.", address, e);
233 } catch (final InterruptedException e) {
234 throw new RuntimeException(e);
235 } catch (final ExecutionException e) {
236 LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
240 LOG.debug("Simulated SSH device started on {}", address);
243 server = dispatcher.createServer(address);
248 } catch (final InterruptedException e) {
249 throw new RuntimeException(e);
250 } catch (final ExecutionException e) {
251 LOG.warn("Cannot start tcp simulated device on {}, skipping", address, e);
255 LOG.debug("Simulated TCP device started on {}", server.channel().localAddress());
258 devicesChannels.add(server.channel());
259 openDevices.add(currentPort - 1);
262 if (openDevices.size() == configuration.getDeviceCount()) {
263 LOG.info("All simulated devices started successfully from port {} to {}",
264 configuration.getStartingPort(), currentPort - 1);
265 } else if (openDevices.size() == 0) {
266 LOG.warn("No simulated devices started.");
268 LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
274 private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress,
275 final LocalAddress tcpLocalAddress, final KeyPairProvider keyPairProvider) {
276 return new SshProxyServerConfigurationBuilder()
277 .setBindingAddress(bindingAddress)
278 .setLocalAddress(tcpLocalAddress)
279 .setAuthenticator(configuration.getAuthProvider())
280 .setPublickeyAuthenticator(configuration.getPublickeyAuthenticator())
281 .setKeyPairProvider(keyPairProvider)
282 .setIdleTimeout(Integer.MAX_VALUE)
283 .createSshProxyServerConfiguration();
286 private Set<Capability> parseSchemasToModuleCapabilities(final SharedSchemaRepository consumer) {
287 final Set<SourceIdentifier> loadedSources = new HashSet<>();
288 consumer.registerSchemaSourceListener(TextToIRTransformer.create(consumer, consumer));
289 consumer.registerSchemaSourceListener(new SchemaSourceListener() {
291 public void schemaSourceEncountered(final SchemaSourceRepresentation schemaSourceRepresentation) {
296 public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> potentialSchemaSources) {
297 for (final PotentialSchemaSource<?> potentialSchemaSource : potentialSchemaSources) {
298 loadedSources.add(potentialSchemaSource.getSourceIdentifier());
303 public void schemaSourceUnregistered(final PotentialSchemaSource<?> potentialSchemaSource) {
308 if (configuration.getSchemasDir() != null) {
309 LOG.info("Loading models from directory.");
310 final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(
311 consumer, YangTextSchemaSource.class, configuration.getSchemasDir());
312 consumer.registerSchemaSourceListener(cache);
313 } else if (configuration.getModels() != null) {
314 LOG.info("Loading models from classpath.");
315 final SchemaSourceCache<YangTextSchemaSource> cache = new SchemaSourceCache<>(
316 consumer, YangTextSchemaSource.class, configuration.getModels());
317 consumer.registerSchemaSourceListener(cache);
319 LOG.info("Custom module loading skipped.");
322 configuration.getDefaultYangResources().forEach(r -> {
323 final SourceIdentifier sourceIdentifier = RevisionSourceIdentifier.create(r.getModuleName(),
324 Revision.ofNullable(r.getRevision()));
325 registerSource(consumer, r.getResourcePath(), sourceIdentifier);
329 //necessary for creating mdsal data stores and operations
330 this.schemaContext = consumer.createEffectiveModelContextFactory()
331 .createEffectiveModelContext(loadedSources).get();
332 } catch (final InterruptedException | ExecutionException e) {
333 throw new RuntimeException("Cannot parse schema context", e);
336 final Set<Capability> capabilities = new HashSet<>();
338 for (final Module module : schemaContext.getModules()) {
339 for (final Submodule subModule : module.getSubmodules()) {
340 addModuleCapability(consumer, capabilities, subModule);
342 addModuleCapability(consumer, capabilities, module);
347 private static void addModuleCapability(final SharedSchemaRepository consumer, final Set<Capability> capabilities,
348 final ModuleLike module) {
349 final SourceIdentifier moduleSourceIdentifier = RevisionSourceIdentifier.create(module.getName(),
350 module.getRevision());
352 final String moduleContent = new String(
353 consumer.getSchemaSource(moduleSourceIdentifier, YangTextSchemaSource.class).get().read());
354 capabilities.add(new YangModuleCapability(module, moduleContent));
355 //IOException would be thrown in creating SchemaContext already
356 } catch (final ExecutionException | InterruptedException | IOException e) {
357 throw new RuntimeException("Cannot retrieve schema source for module "
358 + moduleSourceIdentifier.toString() + " from schema repository", e);
362 private static void registerSource(final SharedSchemaRepository consumer, final String resource,
363 final SourceIdentifier sourceId) {
364 consumer.registerSchemaSource(sourceIdentifier -> Futures.immediateFuture(
365 YangTextSchemaSource.forResource(NetconfDeviceSimulator.class, resource)),
366 PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class,
367 PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
370 private static InetSocketAddress getAddress(final String ip, final int port) {
372 return new InetSocketAddress(Inet4Address.getByName(ip), port);
373 } catch (final UnknownHostException e) {
374 throw new RuntimeException(e);
379 public void close() {
380 for (final SshProxyServer sshWrapper : sshWrappers) {
383 } catch (final IOException e) {
384 LOG.debug("Wrapper {} failed to close", sshWrapper, e);
387 for (final Channel deviceCh : devicesChannels) {
390 nettyThreadgroup.shutdownGracefully();
391 minaTimerExecutor.shutdownNow();
392 nioExecutor.shutdownNow();