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.Objects;
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;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.InputStreamReader;
32 import java.lang.management.ManagementFactory;
33 import java.net.BindException;
34 import java.net.Inet4Address;
35 import java.net.InetSocketAddress;
37 import java.net.UnknownHostException;
38 import java.nio.file.Files;
39 import java.nio.file.Path;
40 import java.util.AbstractMap;
41 import java.util.Date;
42 import java.util.HashMap;
43 import java.util.List;
46 import java.util.TreeMap;
47 import java.util.concurrent.ExecutionException;
48 import java.util.concurrent.ExecutorService;
49 import java.util.concurrent.Executors;
50 import java.util.concurrent.ScheduledExecutorService;
51 import org.antlr.v4.runtime.ParserRuleContext;
52 import org.antlr.v4.runtime.tree.ParseTreeWalker;
53 import org.apache.sshd.common.util.ThreadUtils;
54 import org.apache.sshd.server.PasswordAuthenticator;
55 import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
56 import org.apache.sshd.server.session.ServerSession;
57 import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession;
58 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
59 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
60 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
61 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
62 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
63 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
64 import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
65 import org.opendaylight.controller.netconf.mapping.api.Capability;
66 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
67 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
68 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
69 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceSnapshot;
70 import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringOperationService;
71 import org.opendaylight.controller.netconf.ssh.SshProxyServer;
72 import org.opendaylight.controller.netconf.ssh.SshProxyServerConfiguration;
73 import org.opendaylight.controller.netconf.ssh.SshProxyServerConfigurationBuilder;
74 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
75 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
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;
103 public NetconfDeviceSimulator() {
104 // TODO make pool size configurable
105 this(new NioEventLoopGroup(), new HashedWheelTimer(),
106 Executors.newScheduledThreadPool(8, new ThreadFactoryBuilder().setNameFormat("netconf-ssh-server-mina-timers-%d").build()),
107 ThreadUtils.newFixedThreadPool("netconf-ssh-server-nio-group", 8));
110 private NetconfDeviceSimulator(final NioEventLoopGroup eventExecutors, final HashedWheelTimer hashedWheelTimer, final ScheduledExecutorService minaTimerExecutor, final ExecutorService nioExecutor) {
111 this.nettyThreadgroup = eventExecutors;
112 this.hashedWheelTimer = hashedWheelTimer;
113 this.minaTimerExecutor = minaTimerExecutor;
114 this.nioExecutor = nioExecutor;
117 private NetconfServerDispatcher createDispatcher(final Map<ModuleBuilder, String> moduleBuilders, final boolean exi, final int generateConfigsTimeout) {
119 final Set<Capability> capabilities = Sets.newHashSet(Collections2.transform(moduleBuilders.keySet(), new Function<ModuleBuilder, Capability>() {
121 public Capability apply(final ModuleBuilder input) {
122 return new ModuleBuilderCapability(input, moduleBuilders.get(input));
126 final SessionIdProvider idProvider = new SessionIdProvider();
128 final SimulatedOperationProvider simulatedOperationProvider = new SimulatedOperationProvider(idProvider, capabilities);
129 final NetconfMonitoringOperationService monitoringService = new NetconfMonitoringOperationService(new NetconfMonitoringServiceImpl(simulatedOperationProvider));
130 simulatedOperationProvider.addService(monitoringService);
132 final DefaultCommitNotificationProducer commitNotifier = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
134 final Set<String> serverCapabilities = exi
135 ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES
136 : Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0, XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
138 final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
139 hashedWheelTimer, simulatedOperationProvider, idProvider, generateConfigsTimeout, commitNotifier, new LoggingMonitoringService(), serverCapabilities);
141 final NetconfServerDispatcher.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerChannelInitializer(
142 serverNegotiatorFactory);
143 return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
146 private Map<ModuleBuilder, String> toModuleBuilders(final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> sources) {
147 final Map<SourceIdentifier, ParserRuleContext> asts = Maps.transformValues(sources, new Function<Map.Entry<ASTSchemaSource, YangTextSchemaSource>, ParserRuleContext>() {
149 public ParserRuleContext apply(final Map.Entry<ASTSchemaSource, YangTextSchemaSource> input) {
150 return input.getKey().getAST();
153 final Map<String, TreeMap<Date, URI>> namespaceContext = BuilderUtils.createYangNamespaceContext(
154 asts.values(), Optional.<SchemaContext>absent());
156 final ParseTreeWalker walker = new ParseTreeWalker();
157 final Map<ModuleBuilder, String> sourceToBuilder = new HashMap<>();
159 for (final Map.Entry<SourceIdentifier, ParserRuleContext> entry : asts.entrySet()) {
160 final ModuleBuilder moduleBuilder = YangParserListenerImpl.create(namespaceContext, entry.getKey().getName(),
161 walker, entry.getValue()).getModuleBuilder();
163 try(InputStreamReader stream = new InputStreamReader(sources.get(entry.getKey()).getValue().openStream(), Charsets.UTF_8)) {
164 sourceToBuilder.put(moduleBuilder, CharStreams.toString(stream));
165 } catch (final IOException e) {
166 throw new RuntimeException(e);
170 return sourceToBuilder;
174 public List<Integer> start(final Main.Params params) {
175 LOG.info("Starting {}, {} simulated devices starting on port {}", params.deviceCount, params.ssh ? "SSH" : "TCP", params.startingPort);
177 final Map<ModuleBuilder, String> moduleBuilders = parseSchemasToModuleBuilders(params);
179 final NetconfServerDispatcher dispatcher = createDispatcher(moduleBuilders, params.exi, params.generateConfigsTimeout);
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(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 PasswordAuthenticator() {
268 public boolean authenticate(final String username, final String password, final ServerSession session) {
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 Map<ModuleBuilder, String> parseSchemasToModuleBuilders(final Main.Params params) {
288 final SharedSchemaRepository consumer = new SharedSchemaRepository("netconf-simulator");
289 consumer.registerSchemaSourceListener(TextToASTTransformer.create(consumer, consumer));
291 final Set<SourceIdentifier> loadedSources = Sets.newHashSet();
293 consumer.registerSchemaSourceListener(new SchemaSourceListener() {
295 public void schemaSourceEncountered(final SchemaSourceRepresentation schemaSourceRepresentation) {}
298 public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> potentialSchemaSources) {
299 for (final PotentialSchemaSource<?> potentialSchemaSource : potentialSchemaSources) {
300 loadedSources.add(potentialSchemaSource.getSourceIdentifier());
305 public void schemaSourceUnregistered(final PotentialSchemaSource<?> potentialSchemaSource) {}
308 if(params.schemasDir != null) {
309 final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(consumer, YangTextSchemaSource.class, params.schemasDir);
310 consumer.registerSchemaSourceListener(cache);
313 addDefaultSchemas(consumer);
315 final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> asts = Maps.newHashMap();
316 for (final SourceIdentifier loadedSource : loadedSources) {
318 final CheckedFuture<ASTSchemaSource, SchemaSourceException> ast = consumer.getSchemaSource(loadedSource, ASTSchemaSource.class);
319 final CheckedFuture<YangTextSchemaSource, SchemaSourceException> text = consumer.getSchemaSource(loadedSource, YangTextSchemaSource.class);
320 asts.put(loadedSource, new AbstractMap.SimpleEntry<>(ast.get(), text.get()));
321 } catch (final InterruptedException e) {
322 throw new RuntimeException(e);
323 } catch (final ExecutionException e) {
324 throw new RuntimeException("Cannot parse schema context", e);
327 return toModuleBuilders(asts);
330 private void addDefaultSchemas(final SharedSchemaRepository consumer) {
331 SourceIdentifier sId = new SourceIdentifier("ietf-netconf-monitoring", "2010-10-04");
332 registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring.yang", sId);
334 sId = new SourceIdentifier("ietf-yang-types", "2013-07-15");
335 registerSource(consumer, "/META-INF/yang/ietf-yang-types@2013-07-15.yang", sId);
337 sId = new SourceIdentifier("ietf-inet-types", "2010-09-24");
338 registerSource(consumer, "/META-INF/yang/ietf-inet-types.yang", sId);
341 private void registerSource(final SharedSchemaRepository consumer, final String resource, final SourceIdentifier sourceId) {
342 consumer.registerSchemaSource(new SchemaSourceProvider<SchemaSourceRepresentation>() {
344 public CheckedFuture<? extends SchemaSourceRepresentation, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
345 return Futures.immediateCheckedFuture(new YangTextSchemaSource(sourceId) {
347 protected Objects.ToStringHelper addToStringAttributes(final Objects.ToStringHelper toStringHelper) {
348 return toStringHelper;
352 public InputStream openStream() throws IOException {
353 return getClass().getResourceAsStream(resource);
357 }, PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
360 private static InetSocketAddress getAddress(final int port) {
362 // TODO make address configurable
363 return new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), port);
364 } catch (final UnknownHostException e) {
365 throw new RuntimeException(e);
370 public void close() {
371 for (final SshProxyServer sshWrapper : sshWrappers) {
374 for (final Channel deviceCh : devicesChannels) {
377 nettyThreadgroup.shutdownGracefully();
378 minaTimerExecutor.shutdownNow();
379 nioExecutor.shutdownNow();
383 private static class SimulatedOperationProvider implements NetconfOperationProvider {
384 private final SessionIdProvider idProvider;
385 private final Set<NetconfOperationService> netconfOperationServices;
388 public SimulatedOperationProvider(final SessionIdProvider idProvider, final Set<Capability> caps) {
389 this.idProvider = idProvider;
390 final SimulatedOperationService simulatedOperationService = new SimulatedOperationService(caps, idProvider.getCurrentSessionId());
391 this.netconfOperationServices = Sets.<NetconfOperationService>newHashSet(simulatedOperationService);
395 public NetconfOperationServiceSnapshot openSnapshot(final String sessionIdForReporting) {
396 return new SimulatedServiceSnapshot(idProvider, netconfOperationServices);
399 public void addService(final NetconfOperationService monitoringService) {
400 netconfOperationServices.add(monitoringService);
403 private static class SimulatedServiceSnapshot implements NetconfOperationServiceSnapshot {
404 private final SessionIdProvider idProvider;
405 private final Set<NetconfOperationService> netconfOperationServices;
407 public SimulatedServiceSnapshot(final SessionIdProvider idProvider, final Set<NetconfOperationService> netconfOperationServices) {
408 this.idProvider = idProvider;
409 this.netconfOperationServices = netconfOperationServices;
413 public String getNetconfSessionIdForReporting() {
414 return String.valueOf(idProvider.getCurrentSessionId());
418 public Set<NetconfOperationService> getServices() {
419 return netconfOperationServices;
423 public void close() throws Exception {}
426 static class SimulatedOperationService implements NetconfOperationService {
427 private final Set<Capability> capabilities;
428 private final long currentSessionId;
430 public SimulatedOperationService(final Set<Capability> capabilities, final long currentSessionId) {
431 this.capabilities = capabilities;
432 this.currentSessionId = currentSessionId;
436 public Set<Capability> getCapabilities() {
441 public Set<NetconfOperation> getNetconfOperations() {
442 final DataList storage = new DataList();
443 final SimulatedGet sGet = new SimulatedGet(String.valueOf(currentSessionId), storage);
444 final SimulatedEditConfig sEditConfig = new SimulatedEditConfig(String.valueOf(currentSessionId), storage);
445 final SimulatedGetConfig sGetConfig = new SimulatedGetConfig(String.valueOf(currentSessionId), storage);
446 final SimulatedCommit sCommit = new SimulatedCommit(String.valueOf(currentSessionId));
447 return Sets.<NetconfOperation>newHashSet(sGet, sGetConfig, sEditConfig, sCommit);
451 public void close() {
457 private class LoggingMonitoringService implements SessionMonitoringService {
459 public void onSessionUp(final NetconfManagementSession session) {
460 LOG.debug("Session {} established", session);
464 public void onSessionDown(final NetconfManagementSession session) {
465 LOG.debug("Session {} down", session);