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.controller.netconf.test.tool;
11 import com.google.common.base.Charsets;
12 import com.google.common.base.Function;
13 import com.google.common.base.MoreObjects;
14 import com.google.common.base.Optional;
15 import com.google.common.collect.Collections2;
16 import com.google.common.collect.Lists;
17 import com.google.common.collect.Maps;
18 import com.google.common.collect.Sets;
19 import com.google.common.io.CharStreams;
20 import com.google.common.util.concurrent.CheckedFuture;
21 import com.google.common.util.concurrent.Futures;
22 import com.google.common.util.concurrent.ThreadFactoryBuilder;
23 import io.netty.channel.Channel;
24 import io.netty.channel.ChannelFuture;
25 import io.netty.channel.local.LocalAddress;
26 import io.netty.channel.nio.NioEventLoopGroup;
27 import io.netty.util.HashedWheelTimer;
28 import java.io.Closeable;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.io.InputStreamReader;
33 import java.lang.management.ManagementFactory;
34 import java.net.BindException;
35 import java.net.Inet4Address;
36 import java.net.InetSocketAddress;
38 import java.net.UnknownHostException;
39 import java.nio.file.Files;
40 import java.nio.file.Path;
41 import java.util.AbstractMap;
42 import java.util.Date;
43 import java.util.HashMap;
44 import java.util.List;
46 import java.util.NavigableMap;
48 import java.util.concurrent.ExecutionException;
49 import java.util.concurrent.ExecutorService;
50 import java.util.concurrent.Executors;
51 import java.util.concurrent.ScheduledExecutorService;
52 import org.antlr.v4.runtime.ParserRuleContext;
53 import org.antlr.v4.runtime.tree.ParseTreeWalker;
54 import org.apache.sshd.common.util.ThreadUtils;
55 import org.apache.sshd.server.PasswordAuthenticator;
56 import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
57 import org.apache.sshd.server.session.ServerSession;
58 import org.opendaylight.controller.netconf.api.Capability;
59 import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
60 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
61 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
62 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcherImpl;
63 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
64 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
65 import org.opendaylight.controller.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
66 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
67 import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringActivator;
68 import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringOperationService;
69 import org.opendaylight.controller.netconf.ssh.SshProxyServer;
70 import org.opendaylight.controller.netconf.ssh.SshProxyServerConfiguration;
71 import org.opendaylight.controller.netconf.ssh.SshProxyServerConfigurationBuilder;
72 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
73 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
74 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
75 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
76 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
77 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
78 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
79 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
80 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
81 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
82 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
83 import org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils;
84 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
85 import org.opendaylight.yangtools.yang.parser.impl.YangParserListenerImpl;
86 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
87 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
88 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
92 public class NetconfDeviceSimulator implements Closeable {
94 private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSimulator.class);
96 private final NioEventLoopGroup nettyThreadgroup;
97 private final HashedWheelTimer hashedWheelTimer;
98 private final List<Channel> devicesChannels = Lists.newArrayList();
99 private final List<SshProxyServer> sshWrappers = Lists.newArrayList();
100 private final ScheduledExecutorService minaTimerExecutor;
101 private final ExecutorService nioExecutor;
102 private SchemaContext schemaContext;
104 private boolean sendFakeSchema = false;
106 public NetconfDeviceSimulator() {
107 // TODO make pool size configurable
108 this(new NioEventLoopGroup(), new HashedWheelTimer(),
109 Executors.newScheduledThreadPool(8, new ThreadFactoryBuilder().setNameFormat("netconf-ssh-server-mina-timers-%d").build()),
110 ThreadUtils.newFixedThreadPool("netconf-ssh-server-nio-group", 8));
113 private NetconfDeviceSimulator(final NioEventLoopGroup eventExecutors, final HashedWheelTimer hashedWheelTimer, final ScheduledExecutorService minaTimerExecutor, final ExecutorService nioExecutor) {
114 this.nettyThreadgroup = eventExecutors;
115 this.hashedWheelTimer = hashedWheelTimer;
116 this.minaTimerExecutor = minaTimerExecutor;
117 this.nioExecutor = nioExecutor;
120 private NetconfServerDispatcherImpl createDispatcher(final Map<ModuleBuilder, String> moduleBuilders, final boolean exi, final int generateConfigsTimeout, final Optional<File> notificationsFile, final boolean mdSal) {
122 final Set<Capability> capabilities = Sets.newHashSet(Collections2.transform(moduleBuilders.keySet(), new Function<ModuleBuilder, Capability>() {
124 public Capability apply(final ModuleBuilder input) {
125 if (sendFakeSchema) {
126 sendFakeSchema = false;
127 return new FakeModuleBuilderCapability(input, moduleBuilders.get(input));
129 return new ModuleBuilderCapability(input, moduleBuilders.get(input));
134 final SessionIdProvider idProvider = new SessionIdProvider();
136 final AggregatedNetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory = new AggregatedNetconfOperationServiceFactory();
137 final NetconfOperationServiceFactory operationProvider = mdSal ? new MdsalOperationProvider(idProvider, capabilities, schemaContext) :
138 new SimulatedOperationProvider(idProvider, capabilities, notificationsFile);
140 final NetconfMonitoringService monitoringService1 = new DummyMonitoringService(capabilities);
142 final NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory monitoringService =
143 new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(
144 new NetconfMonitoringOperationService(monitoringService1));
145 aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(operationProvider);
146 aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(monitoringService);
148 final DefaultCommitNotificationProducer commitNotifier = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
150 final Set<String> serverCapabilities = exi
151 ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES
152 : Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0, XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
154 final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
155 hashedWheelTimer, aggregatedNetconfOperationServiceFactory, idProvider, generateConfigsTimeout, commitNotifier, monitoringService1, serverCapabilities);
157 final NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(
158 serverNegotiatorFactory);
159 return new NetconfServerDispatcherImpl(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
162 private Map<ModuleBuilder, String> toModuleBuilders(final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> sources) {
163 final Map<SourceIdentifier, ParserRuleContext> asts = Maps.transformValues(sources, new Function<Map.Entry<ASTSchemaSource, YangTextSchemaSource>, ParserRuleContext>() {
165 public ParserRuleContext apply(final Map.Entry<ASTSchemaSource, YangTextSchemaSource> input) {
166 return input.getKey().getAST();
169 final Map<String, NavigableMap<Date, URI>> namespaceContext = BuilderUtils.createYangNamespaceContext(
170 asts.values(), Optional.<SchemaContext>absent());
172 final ParseTreeWalker walker = new ParseTreeWalker();
173 final Map<ModuleBuilder, String> sourceToBuilder = new HashMap<>();
175 for (final Map.Entry<SourceIdentifier, ParserRuleContext> entry : asts.entrySet()) {
176 final ModuleBuilder moduleBuilder = YangParserListenerImpl.create(namespaceContext, entry.getKey().getName(),
177 walker, entry.getValue()).getModuleBuilder();
179 try(InputStreamReader stream = new InputStreamReader(sources.get(entry.getKey()).getValue().openStream(), Charsets.UTF_8)) {
180 sourceToBuilder.put(moduleBuilder, CharStreams.toString(stream));
181 } catch (final IOException e) {
182 throw new RuntimeException(e);
186 return sourceToBuilder;
190 public List<Integer> start(final Main.Params params) {
191 LOG.info("Starting {}, {} simulated devices starting on port {}", params.deviceCount, params.ssh ? "SSH" : "TCP", params.startingPort);
193 final Map<ModuleBuilder, String> moduleBuilders = parseSchemasToModuleBuilders(params);
195 final NetconfServerDispatcherImpl dispatcher = createDispatcher(moduleBuilders, params.exi, params.generateConfigsTimeout, Optional.fromNullable(params.notificationFile), params.mdSal);
197 int currentPort = params.startingPort;
199 final List<Integer> openDevices = Lists.newArrayList();
201 // Generate key to temp folder
202 final PEMGeneratorHostKeyProvider keyPairProvider = getPemGeneratorHostKeyProvider();
204 for (int i = 0; i < params.deviceCount; i++) {
205 if (currentPort > 65535) {
206 LOG.warn("Port cannot be greater than 65535, stopping further attempts.");
209 final InetSocketAddress address = getAddress(currentPort);
211 final ChannelFuture server;
213 final InetSocketAddress bindingAddress = InetSocketAddress.createUnresolved("0.0.0.0", currentPort);
214 final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());
216 server = dispatcher.createLocalServer(tcpLocalAddress);
218 final SshProxyServer sshServer = new SshProxyServer(minaTimerExecutor, nettyThreadgroup, nioExecutor);
219 sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress, keyPairProvider));
220 sshWrappers.add(sshServer);
221 } catch (final BindException e) {
222 LOG.warn("Cannot start simulated device on {}, port already in use. Skipping.", address);
223 // Close local server and continue
225 if(server.isDone()) {
226 server.channel().close();
229 } catch (final IOException e) {
230 LOG.warn("Cannot start simulated device on {} due to IOException.", address, e);
238 } catch (final InterruptedException e) {
239 throw new RuntimeException(e);
240 } catch (final ExecutionException e) {
241 LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
245 LOG.debug("Simulated SSH device started on {}", address);
248 server = dispatcher.createServer(address);
253 } catch (final InterruptedException e) {
254 throw new RuntimeException(e);
255 } catch (final ExecutionException e) {
256 LOG.warn("Cannot start tcp simulated device on {}, skipping", address, e);
260 LOG.debug("Simulated TCP device started on {}", address);
263 devicesChannels.add(server.channel());
264 openDevices.add(currentPort - 1);
267 if(openDevices.size() == params.deviceCount) {
268 LOG.info("All simulated devices started successfully from port {} to {}", params.startingPort, currentPort - 1);
269 } else if (openDevices.size() == 0) {
270 LOG.warn("No simulated devices started.");
272 LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
278 private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress, final LocalAddress tcpLocalAddress, final PEMGeneratorHostKeyProvider keyPairProvider) throws IOException {
279 return new SshProxyServerConfigurationBuilder()
280 .setBindingAddress(bindingAddress)
281 .setLocalAddress(tcpLocalAddress)
282 .setAuthenticator(new PasswordAuthenticator() {
284 public boolean authenticate(final String username, final String password, final ServerSession session) {
288 .setKeyPairProvider(keyPairProvider)
289 .setIdleTimeout(Integer.MAX_VALUE)
290 .createSshProxyServerConfiguration();
293 private PEMGeneratorHostKeyProvider getPemGeneratorHostKeyProvider() {
295 final Path tempFile = Files.createTempFile("tempKeyNetconfTest", "suffix");
296 return new PEMGeneratorHostKeyProvider(tempFile.toAbsolutePath().toString());
297 } catch (final IOException e) {
298 LOG.error("Unable to generate PEM key", e);
299 throw new RuntimeException(e);
303 private Map<ModuleBuilder, String> parseSchemasToModuleBuilders(final Main.Params params) {
304 final SharedSchemaRepository consumer = new SharedSchemaRepository("netconf-simulator");
305 consumer.registerSchemaSourceListener(TextToASTTransformer.create(consumer, consumer));
307 final Set<SourceIdentifier> loadedSources = Sets.newHashSet();
309 consumer.registerSchemaSourceListener(new SchemaSourceListener() {
311 public void schemaSourceEncountered(final SchemaSourceRepresentation schemaSourceRepresentation) {}
314 public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> potentialSchemaSources) {
315 for (final PotentialSchemaSource<?> potentialSchemaSource : potentialSchemaSources) {
316 loadedSources.add(potentialSchemaSource.getSourceIdentifier());
321 public void schemaSourceUnregistered(final PotentialSchemaSource<?> potentialSchemaSource) {}
324 if(params.schemasDir != null) {
325 final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(consumer, YangTextSchemaSource.class, params.schemasDir);
326 consumer.registerSchemaSourceListener(cache);
329 addDefaultSchemas(consumer);
331 final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> asts = Maps.newHashMap();
334 //necessary for creating mdsal datastores and operations
335 schemaContext = consumer.createSchemaContextFactory(
336 SchemaSourceFilter.ALWAYS_ACCEPT)
337 .createSchemaContext(loadedSources).checkedGet();
338 } catch (final SchemaResolutionException e) {
339 throw new RuntimeException("Cannot parse schema context", e);
342 for (final SourceIdentifier loadedSource : loadedSources) {
344 final CheckedFuture<ASTSchemaSource, SchemaSourceException> ast = consumer.getSchemaSource(loadedSource, ASTSchemaSource.class);
345 final CheckedFuture<YangTextSchemaSource, SchemaSourceException> text = consumer.getSchemaSource(loadedSource, YangTextSchemaSource.class);
346 asts.put(loadedSource, new AbstractMap.SimpleEntry<>(ast.get(), text.get()));
347 } catch (final InterruptedException e) {
348 throw new RuntimeException(e);
349 } catch (final ExecutionException e) {
350 throw new RuntimeException("Cannot parse schema context", e);
353 return toModuleBuilders(asts);
356 private void addDefaultSchemas(final SharedSchemaRepository consumer) {
357 SourceIdentifier sId = new SourceIdentifier("ietf-netconf-monitoring", "2010-10-04");
358 registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring.yang", sId);
360 sId = new SourceIdentifier("ietf-netconf-monitoring-extension", "2013-12-10");
361 registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring-extension.yang", sId);
363 sId = new SourceIdentifier("ietf-yang-types", "2010-09-24");
364 registerSource(consumer, "/META-INF/yang/ietf-yang-types.yang", sId);
366 sId = new SourceIdentifier("ietf-inet-types", "2010-09-24");
367 registerSource(consumer, "/META-INF/yang/ietf-inet-types.yang", sId);
370 private void registerSource(final SharedSchemaRepository consumer, final String resource, final SourceIdentifier sourceId) {
371 consumer.registerSchemaSource(new SchemaSourceProvider<SchemaSourceRepresentation>() {
373 public CheckedFuture<? extends SchemaSourceRepresentation, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
374 return Futures.immediateCheckedFuture(new YangTextSchemaSource(sourceId) {
376 protected MoreObjects.ToStringHelper addToStringAttributes(final MoreObjects.ToStringHelper toStringHelper) {
377 return toStringHelper;
381 public InputStream openStream() throws IOException {
382 return getClass().getResourceAsStream(resource);
386 }, PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
389 private static InetSocketAddress getAddress(final int port) {
391 // TODO make address configurable
392 return new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), port);
393 } catch (final UnknownHostException e) {
394 throw new RuntimeException(e);
399 public void close() {
400 for (final SshProxyServer sshWrapper : sshWrappers) {
403 for (final Channel deviceCh : devicesChannels) {
406 nettyThreadgroup.shutdownGracefully();
407 minaTimerExecutor.shutdownNow();
408 nioExecutor.shutdownNow();