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.Inet4Address;
34 import java.net.InetSocketAddress;
36 import java.net.UnknownHostException;
37 import java.nio.file.Files;
38 import java.nio.file.Path;
39 import java.util.AbstractMap;
40 import java.util.Date;
41 import java.util.HashMap;
42 import java.util.List;
45 import java.util.TreeMap;
46 import java.util.concurrent.ExecutionException;
47 import java.util.concurrent.ExecutorService;
48 import java.util.concurrent.Executors;
49 import java.util.concurrent.ScheduledExecutorService;
50 import org.antlr.v4.runtime.ParserRuleContext;
51 import org.antlr.v4.runtime.tree.ParseTreeWalker;
52 import org.apache.sshd.common.util.ThreadUtils;
53 import org.apache.sshd.server.PasswordAuthenticator;
54 import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
55 import org.apache.sshd.server.session.ServerSession;
56 import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession;
57 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
58 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
59 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
60 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
61 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
62 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
63 import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
64 import org.opendaylight.controller.netconf.mapping.api.Capability;
65 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
66 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
67 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
68 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceSnapshot;
69 import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringOperationService;
70 import org.opendaylight.controller.netconf.ssh.SshProxyServer;
71 import org.opendaylight.controller.netconf.ssh.SshProxyServerConfiguration;
72 import org.opendaylight.controller.netconf.ssh.SshProxyServerConfigurationBuilder;
73 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
74 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
75 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
76 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
77 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
78 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
79 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
80 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
81 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
82 import org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils;
83 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
84 import org.opendaylight.yangtools.yang.parser.impl.YangParserListenerImpl;
85 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
86 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
87 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
88 import org.slf4j.Logger;
89 import org.slf4j.LoggerFactory;
91 public class NetconfDeviceSimulator implements Closeable {
93 private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSimulator.class);
95 private final NioEventLoopGroup nettyThreadgroup;
96 private final HashedWheelTimer hashedWheelTimer;
97 private final List<Channel> devicesChannels = Lists.newArrayList();
98 private final List<SshProxyServer> sshWrappers = Lists.newArrayList();
99 private final ScheduledExecutorService minaTimerExecutor;
100 private final ExecutorService nioExecutor;
102 public NetconfDeviceSimulator() {
103 // TODO make pool size configurable
104 this(new NioEventLoopGroup(), new HashedWheelTimer(),
105 Executors.newScheduledThreadPool(8, new ThreadFactoryBuilder().setNameFormat("netconf-ssh-server-mina-timers-%d").build()),
106 ThreadUtils.newFixedThreadPool("netconf-ssh-server-nio-group", 8));
109 private NetconfDeviceSimulator(final NioEventLoopGroup eventExecutors, final HashedWheelTimer hashedWheelTimer, final ScheduledExecutorService minaTimerExecutor, final ExecutorService nioExecutor) {
110 this.nettyThreadgroup = eventExecutors;
111 this.hashedWheelTimer = hashedWheelTimer;
112 this.minaTimerExecutor = minaTimerExecutor;
113 this.nioExecutor = nioExecutor;
116 private NetconfServerDispatcher createDispatcher(final Map<ModuleBuilder, String> moduleBuilders, final boolean exi, final int generateConfigsTimeout) {
118 final Set<Capability> capabilities = Sets.newHashSet(Collections2.transform(moduleBuilders.keySet(), new Function<ModuleBuilder, Capability>() {
120 public Capability apply(final ModuleBuilder input) {
121 return new ModuleBuilderCapability(input, moduleBuilders.get(input));
125 final SessionIdProvider idProvider = new SessionIdProvider();
127 final SimulatedOperationProvider simulatedOperationProvider = new SimulatedOperationProvider(idProvider, capabilities);
128 final NetconfMonitoringOperationService monitoringService = new NetconfMonitoringOperationService(new NetconfMonitoringServiceImpl(simulatedOperationProvider));
129 simulatedOperationProvider.addService(monitoringService);
131 final DefaultCommitNotificationProducer commitNotifier = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
133 final Set<String> serverCapabilities = exi
134 ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES
135 : Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0, XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
137 final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
138 hashedWheelTimer, simulatedOperationProvider, idProvider, generateConfigsTimeout, commitNotifier, new LoggingMonitoringService(), serverCapabilities);
140 final NetconfServerDispatcher.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerChannelInitializer(
141 serverNegotiatorFactory);
142 return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
145 private Map<ModuleBuilder, String> toModuleBuilders(final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> sources) {
146 final Map<SourceIdentifier, ParserRuleContext> asts = Maps.transformValues(sources, new Function<Map.Entry<ASTSchemaSource, YangTextSchemaSource>, ParserRuleContext>() {
148 public ParserRuleContext apply(final Map.Entry<ASTSchemaSource, YangTextSchemaSource> input) {
149 return input.getKey().getAST();
152 final Map<String, TreeMap<Date, URI>> namespaceContext = BuilderUtils.createYangNamespaceContext(
153 asts.values(), Optional.<SchemaContext>absent());
155 final ParseTreeWalker walker = new ParseTreeWalker();
156 final Map<ModuleBuilder, String> sourceToBuilder = new HashMap<>();
158 for (final Map.Entry<SourceIdentifier, ParserRuleContext> entry : asts.entrySet()) {
159 final ModuleBuilder moduleBuilder = YangParserListenerImpl.create(namespaceContext, entry.getKey().getName(),
160 walker, entry.getValue()).getModuleBuilder();
162 try(InputStreamReader stream = new InputStreamReader(sources.get(entry.getKey()).getValue().openStream(), Charsets.UTF_8)) {
163 sourceToBuilder.put(moduleBuilder, CharStreams.toString(stream));
164 } catch (final IOException e) {
165 throw new RuntimeException(e);
169 return sourceToBuilder;
173 public List<Integer> start(final Main.Params params) {
174 LOG.info("Starting {}, {} simulated devices starting on port {}", params.deviceCount, params.ssh ? "SSH" : "TCP", params.startingPort);
176 final Map<ModuleBuilder, String> moduleBuilders = parseSchemasToModuleBuilders(params);
178 final NetconfServerDispatcher dispatcher = createDispatcher(moduleBuilders, params.exi, params.generateConfigsTimeout);
180 int currentPort = params.startingPort;
182 final List<Integer> openDevices = Lists.newArrayList();
184 // Generate key to temp folder
185 final PEMGeneratorHostKeyProvider keyPairProvider = getPemGeneratorHostKeyProvider();
187 for (int i = 0; i < params.deviceCount; i++) {
188 final InetSocketAddress address = getAddress(currentPort);
190 final ChannelFuture server;
192 final InetSocketAddress bindingAddress = InetSocketAddress.createUnresolved("0.0.0.0", currentPort);
193 final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());
195 server = dispatcher.createLocalServer(tcpLocalAddress);
197 final SshProxyServer sshServer = new SshProxyServer(minaTimerExecutor, nettyThreadgroup, nioExecutor);
198 sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress));
199 sshWrappers.add(sshServer);
200 } catch (final Exception e) {
201 LOG.warn("Cannot start simulated device on {}, skipping", address, e);
202 // Close local server and continue
204 if(server.isDone()) {
205 server.channel().close();
214 } catch (final InterruptedException e) {
215 throw new RuntimeException(e);
216 } catch (final ExecutionException e) {
217 LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
221 LOG.debug("Simulated SSH device started on {}", address);
224 server = dispatcher.createServer(address);
229 } catch (final InterruptedException e) {
230 throw new RuntimeException(e);
231 } catch (final ExecutionException e) {
232 LOG.warn("Cannot start tcp simulated device on {}, skipping", address, e);
236 LOG.debug("Simulated TCP device started on {}", address);
239 devicesChannels.add(server.channel());
240 openDevices.add(currentPort - 1);
243 if(openDevices.size() == params.deviceCount) {
244 LOG.info("All simulated devices started successfully from port {} to {}", params.startingPort, currentPort - 1);
246 LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
252 private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress, final LocalAddress tcpLocalAddress) throws IOException {
253 return new SshProxyServerConfigurationBuilder()
254 .setBindingAddress(bindingAddress)
255 .setLocalAddress(tcpLocalAddress)
256 .setAuthenticator(new PasswordAuthenticator() {
258 public boolean authenticate(final String username, final String password, final ServerSession session) {
262 .setKeyPairProvider(new PEMGeneratorHostKeyProvider(Files.createTempFile("prefix", "suffix").toAbsolutePath().toString()))
263 .setIdleTimeout(Integer.MAX_VALUE)
264 .createSshProxyServerConfiguration();
267 private PEMGeneratorHostKeyProvider getPemGeneratorHostKeyProvider() {
269 final Path tempFile = Files.createTempFile("tempKeyNetconfTest", "suffix");
270 return new PEMGeneratorHostKeyProvider(tempFile.toAbsolutePath().toString());
271 } catch (final IOException e) {
272 LOG.error("Unable to generate PEM key", e);
273 throw new RuntimeException(e);
277 private Map<ModuleBuilder, String> parseSchemasToModuleBuilders(final Main.Params params) {
278 final SharedSchemaRepository consumer = new SharedSchemaRepository("netconf-simulator");
279 consumer.registerSchemaSourceListener(TextToASTTransformer.create(consumer, consumer));
281 final Set<SourceIdentifier> loadedSources = Sets.newHashSet();
283 consumer.registerSchemaSourceListener(new SchemaSourceListener() {
285 public void schemaSourceEncountered(final SchemaSourceRepresentation schemaSourceRepresentation) {}
288 public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> potentialSchemaSources) {
289 for (final PotentialSchemaSource<?> potentialSchemaSource : potentialSchemaSources) {
290 loadedSources.add(potentialSchemaSource.getSourceIdentifier());
295 public void schemaSourceUnregistered(final PotentialSchemaSource<?> potentialSchemaSource) {}
298 if(params.schemasDir != null) {
299 final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(consumer, YangTextSchemaSource.class, params.schemasDir);
300 consumer.registerSchemaSourceListener(cache);
303 addDefaultSchemas(consumer);
305 final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> asts = Maps.newHashMap();
306 for (final SourceIdentifier loadedSource : loadedSources) {
308 final CheckedFuture<ASTSchemaSource, SchemaSourceException> ast = consumer.getSchemaSource(loadedSource, ASTSchemaSource.class);
309 final CheckedFuture<YangTextSchemaSource, SchemaSourceException> text = consumer.getSchemaSource(loadedSource, YangTextSchemaSource.class);
310 asts.put(loadedSource, new AbstractMap.SimpleEntry<>(ast.get(), text.get()));
311 } catch (final InterruptedException e) {
312 throw new RuntimeException(e);
313 } catch (final ExecutionException e) {
314 throw new RuntimeException("Cannot parse schema context", e);
317 return toModuleBuilders(asts);
320 private void addDefaultSchemas(final SharedSchemaRepository consumer) {
321 SourceIdentifier sId = new SourceIdentifier("ietf-netconf-monitoring", "2010-10-04");
322 registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring.yang", sId);
324 sId = new SourceIdentifier("ietf-yang-types", "2013-07-15");
325 registerSource(consumer, "/META-INF/yang/ietf-yang-types@2013-07-15.yang", sId);
327 sId = new SourceIdentifier("ietf-inet-types", "2010-09-24");
328 registerSource(consumer, "/META-INF/yang/ietf-inet-types.yang", sId);
331 private void registerSource(final SharedSchemaRepository consumer, final String resource, final SourceIdentifier sourceId) {
332 consumer.registerSchemaSource(new SchemaSourceProvider<SchemaSourceRepresentation>() {
334 public CheckedFuture<? extends SchemaSourceRepresentation, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
335 return Futures.immediateCheckedFuture(new YangTextSchemaSource(sourceId) {
337 protected Objects.ToStringHelper addToStringAttributes(final Objects.ToStringHelper toStringHelper) {
338 return toStringHelper;
342 public InputStream openStream() throws IOException {
343 return getClass().getResourceAsStream(resource);
347 }, PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
350 private static InetSocketAddress getAddress(final int port) {
352 // TODO make address configurable
353 return new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), port);
354 } catch (final UnknownHostException e) {
355 throw new RuntimeException(e);
360 public void close() {
361 for (final SshProxyServer sshWrapper : sshWrappers) {
364 for (final Channel deviceCh : devicesChannels) {
367 nettyThreadgroup.shutdownGracefully();
368 minaTimerExecutor.shutdownNow();
369 nioExecutor.shutdownNow();
373 private static class SimulatedOperationProvider implements NetconfOperationProvider {
374 private final SessionIdProvider idProvider;
375 private final Set<NetconfOperationService> netconfOperationServices;
378 public SimulatedOperationProvider(final SessionIdProvider idProvider, final Set<Capability> caps) {
379 this.idProvider = idProvider;
380 final SimulatedOperationService simulatedOperationService = new SimulatedOperationService(caps, idProvider.getCurrentSessionId());
381 this.netconfOperationServices = Sets.<NetconfOperationService>newHashSet(simulatedOperationService);
385 public NetconfOperationServiceSnapshot openSnapshot(final String sessionIdForReporting) {
386 return new SimulatedServiceSnapshot(idProvider, netconfOperationServices);
389 public void addService(final NetconfOperationService monitoringService) {
390 netconfOperationServices.add(monitoringService);
393 private static class SimulatedServiceSnapshot implements NetconfOperationServiceSnapshot {
394 private final SessionIdProvider idProvider;
395 private final Set<NetconfOperationService> netconfOperationServices;
397 public SimulatedServiceSnapshot(final SessionIdProvider idProvider, final Set<NetconfOperationService> netconfOperationServices) {
398 this.idProvider = idProvider;
399 this.netconfOperationServices = netconfOperationServices;
403 public String getNetconfSessionIdForReporting() {
404 return String.valueOf(idProvider.getCurrentSessionId());
408 public Set<NetconfOperationService> getServices() {
409 return netconfOperationServices;
413 public void close() throws Exception {}
416 static class SimulatedOperationService implements NetconfOperationService {
417 private final Set<Capability> capabilities;
418 private final long currentSessionId;
420 public SimulatedOperationService(final Set<Capability> capabilities, final long currentSessionId) {
421 this.capabilities = capabilities;
422 this.currentSessionId = currentSessionId;
426 public Set<Capability> getCapabilities() {
431 public Set<NetconfOperation> getNetconfOperations() {
432 final DataList storage = new DataList();
433 final SimulatedGet sGet = new SimulatedGet(String.valueOf(currentSessionId), storage);
434 final SimulatedEditConfig sEditConfig = new SimulatedEditConfig(String.valueOf(currentSessionId), storage);
435 final SimulatedGetConfig sGetConfig = new SimulatedGetConfig(String.valueOf(currentSessionId), storage);
436 final SimulatedCommit sCommit = new SimulatedCommit(String.valueOf(currentSessionId));
437 return Sets.<NetconfOperation>newHashSet(sGet, sGetConfig, sEditConfig, sCommit);
441 public void close() {
447 private class LoggingMonitoringService implements SessionMonitoringService {
449 public void onSessionUp(final NetconfManagementSession session) {
450 LOG.debug("Session {} established", session);
454 public void onSessionDown(final NetconfManagementSession session) {
455 LOG.debug("Session {} down", session);