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 private boolean sendFakeSchema = false;
105 public NetconfDeviceSimulator() {
106 // TODO make pool size configurable
107 this(new NioEventLoopGroup(), new HashedWheelTimer(),
108 Executors.newScheduledThreadPool(8, new ThreadFactoryBuilder().setNameFormat("netconf-ssh-server-mina-timers-%d").build()),
109 ThreadUtils.newFixedThreadPool("netconf-ssh-server-nio-group", 8));
112 private NetconfDeviceSimulator(final NioEventLoopGroup eventExecutors, final HashedWheelTimer hashedWheelTimer, final ScheduledExecutorService minaTimerExecutor, final ExecutorService nioExecutor) {
113 this.nettyThreadgroup = eventExecutors;
114 this.hashedWheelTimer = hashedWheelTimer;
115 this.minaTimerExecutor = minaTimerExecutor;
116 this.nioExecutor = nioExecutor;
119 private NetconfServerDispatcher createDispatcher(final Map<ModuleBuilder, String> moduleBuilders, final boolean exi, final int generateConfigsTimeout) {
121 final Set<Capability> capabilities = Sets.newHashSet(Collections2.transform(moduleBuilders.keySet(), new Function<ModuleBuilder, Capability>() {
123 public Capability apply(final ModuleBuilder input) {
124 if (sendFakeSchema) {
125 sendFakeSchema = false;
126 return new FakeModuleBuilderCapability(input, moduleBuilders.get(input));
128 return new ModuleBuilderCapability(input, moduleBuilders.get(input));
133 final SessionIdProvider idProvider = new SessionIdProvider();
135 final SimulatedOperationProvider simulatedOperationProvider = new SimulatedOperationProvider(idProvider, capabilities);
136 final NetconfMonitoringOperationService monitoringService = new NetconfMonitoringOperationService(new NetconfMonitoringServiceImpl(simulatedOperationProvider));
137 simulatedOperationProvider.addService(monitoringService);
139 final DefaultCommitNotificationProducer commitNotifier = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
141 final Set<String> serverCapabilities = exi
142 ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES
143 : Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0, XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
145 final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
146 hashedWheelTimer, simulatedOperationProvider, idProvider, generateConfigsTimeout, commitNotifier, new LoggingMonitoringService(), serverCapabilities);
148 final NetconfServerDispatcher.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerChannelInitializer(
149 serverNegotiatorFactory);
150 return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
153 private Map<ModuleBuilder, String> toModuleBuilders(final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> sources) {
154 final Map<SourceIdentifier, ParserRuleContext> asts = Maps.transformValues(sources, new Function<Map.Entry<ASTSchemaSource, YangTextSchemaSource>, ParserRuleContext>() {
156 public ParserRuleContext apply(final Map.Entry<ASTSchemaSource, YangTextSchemaSource> input) {
157 return input.getKey().getAST();
160 final Map<String, TreeMap<Date, URI>> namespaceContext = BuilderUtils.createYangNamespaceContext(
161 asts.values(), Optional.<SchemaContext>absent());
163 final ParseTreeWalker walker = new ParseTreeWalker();
164 final Map<ModuleBuilder, String> sourceToBuilder = new HashMap<>();
166 for (final Map.Entry<SourceIdentifier, ParserRuleContext> entry : asts.entrySet()) {
167 final ModuleBuilder moduleBuilder = YangParserListenerImpl.create(namespaceContext, entry.getKey().getName(),
168 walker, entry.getValue()).getModuleBuilder();
170 try(InputStreamReader stream = new InputStreamReader(sources.get(entry.getKey()).getValue().openStream(), Charsets.UTF_8)) {
171 sourceToBuilder.put(moduleBuilder, CharStreams.toString(stream));
172 } catch (final IOException e) {
173 throw new RuntimeException(e);
177 return sourceToBuilder;
181 public List<Integer> start(final Main.Params params) {
182 LOG.info("Starting {}, {} simulated devices starting on port {}", params.deviceCount, params.ssh ? "SSH" : "TCP", params.startingPort);
184 final Map<ModuleBuilder, String> moduleBuilders = parseSchemasToModuleBuilders(params);
186 final NetconfServerDispatcher dispatcher = createDispatcher(moduleBuilders, params.exi, params.generateConfigsTimeout);
188 int currentPort = params.startingPort;
190 final List<Integer> openDevices = Lists.newArrayList();
192 // Generate key to temp folder
193 final PEMGeneratorHostKeyProvider keyPairProvider = getPemGeneratorHostKeyProvider();
195 for (int i = 0; i < params.deviceCount; i++) {
196 if (currentPort > 65535) {
197 LOG.warn("Port cannot be greater than 65535, stopping further attempts.");
200 final InetSocketAddress address = getAddress(currentPort);
202 final ChannelFuture server;
204 final InetSocketAddress bindingAddress = InetSocketAddress.createUnresolved("0.0.0.0", currentPort);
205 final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());
207 server = dispatcher.createLocalServer(tcpLocalAddress);
209 final SshProxyServer sshServer = new SshProxyServer(minaTimerExecutor, nettyThreadgroup, nioExecutor);
210 sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress, keyPairProvider));
211 sshWrappers.add(sshServer);
212 } catch (final BindException e) {
213 LOG.warn("Cannot start simulated device on {}, port already in use. Skipping.", address);
214 // Close local server and continue
216 if(server.isDone()) {
217 server.channel().close();
220 } catch (final IOException e) {
221 LOG.warn("Cannot start simulated device on {} due to IOException.", address, e);
229 } catch (final InterruptedException e) {
230 throw new RuntimeException(e);
231 } catch (final ExecutionException e) {
232 LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
236 LOG.debug("Simulated SSH device started on {}", address);
239 server = dispatcher.createServer(address);
244 } catch (final InterruptedException e) {
245 throw new RuntimeException(e);
246 } catch (final ExecutionException e) {
247 LOG.warn("Cannot start tcp simulated device on {}, skipping", address, e);
251 LOG.debug("Simulated TCP device started on {}", address);
254 devicesChannels.add(server.channel());
255 openDevices.add(currentPort - 1);
258 if(openDevices.size() == params.deviceCount) {
259 LOG.info("All simulated devices started successfully from port {} to {}", params.startingPort, currentPort - 1);
260 } else if (openDevices.size() == 0) {
261 LOG.warn("No simulated devices started.");
263 LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
269 private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress, final LocalAddress tcpLocalAddress, final PEMGeneratorHostKeyProvider keyPairProvider) throws IOException {
270 return new SshProxyServerConfigurationBuilder()
271 .setBindingAddress(bindingAddress)
272 .setLocalAddress(tcpLocalAddress)
273 .setAuthenticator(new PasswordAuthenticator() {
275 public boolean authenticate(final String username, final String password, final ServerSession session) {
279 .setKeyPairProvider(keyPairProvider)
280 .setIdleTimeout(Integer.MAX_VALUE)
281 .createSshProxyServerConfiguration();
284 private PEMGeneratorHostKeyProvider getPemGeneratorHostKeyProvider() {
286 final Path tempFile = Files.createTempFile("tempKeyNetconfTest", "suffix");
287 return new PEMGeneratorHostKeyProvider(tempFile.toAbsolutePath().toString());
288 } catch (final IOException e) {
289 LOG.error("Unable to generate PEM key", e);
290 throw new RuntimeException(e);
294 private Map<ModuleBuilder, String> parseSchemasToModuleBuilders(final Main.Params params) {
295 final SharedSchemaRepository consumer = new SharedSchemaRepository("netconf-simulator");
296 consumer.registerSchemaSourceListener(TextToASTTransformer.create(consumer, consumer));
298 final Set<SourceIdentifier> loadedSources = Sets.newHashSet();
300 consumer.registerSchemaSourceListener(new SchemaSourceListener() {
302 public void schemaSourceEncountered(final SchemaSourceRepresentation schemaSourceRepresentation) {}
305 public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> potentialSchemaSources) {
306 for (final PotentialSchemaSource<?> potentialSchemaSource : potentialSchemaSources) {
307 loadedSources.add(potentialSchemaSource.getSourceIdentifier());
312 public void schemaSourceUnregistered(final PotentialSchemaSource<?> potentialSchemaSource) {}
315 if(params.schemasDir != null) {
316 final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(consumer, YangTextSchemaSource.class, params.schemasDir);
317 consumer.registerSchemaSourceListener(cache);
320 addDefaultSchemas(consumer);
322 final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> asts = Maps.newHashMap();
323 for (final SourceIdentifier loadedSource : loadedSources) {
325 final CheckedFuture<ASTSchemaSource, SchemaSourceException> ast = consumer.getSchemaSource(loadedSource, ASTSchemaSource.class);
326 final CheckedFuture<YangTextSchemaSource, SchemaSourceException> text = consumer.getSchemaSource(loadedSource, YangTextSchemaSource.class);
327 asts.put(loadedSource, new AbstractMap.SimpleEntry<>(ast.get(), text.get()));
328 } catch (final InterruptedException e) {
329 throw new RuntimeException(e);
330 } catch (final ExecutionException e) {
331 throw new RuntimeException("Cannot parse schema context", e);
334 return toModuleBuilders(asts);
337 private void addDefaultSchemas(final SharedSchemaRepository consumer) {
338 SourceIdentifier sId = new SourceIdentifier("ietf-netconf-monitoring", "2010-10-04");
339 registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring.yang", sId);
341 sId = new SourceIdentifier("ietf-yang-types", "2013-07-15");
342 registerSource(consumer, "/META-INF/yang/ietf-yang-types@2013-07-15.yang", sId);
344 sId = new SourceIdentifier("ietf-inet-types", "2010-09-24");
345 registerSource(consumer, "/META-INF/yang/ietf-inet-types.yang", sId);
348 private void registerSource(final SharedSchemaRepository consumer, final String resource, final SourceIdentifier sourceId) {
349 consumer.registerSchemaSource(new SchemaSourceProvider<SchemaSourceRepresentation>() {
351 public CheckedFuture<? extends SchemaSourceRepresentation, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
352 return Futures.immediateCheckedFuture(new YangTextSchemaSource(sourceId) {
354 protected Objects.ToStringHelper addToStringAttributes(final Objects.ToStringHelper toStringHelper) {
355 return toStringHelper;
359 public InputStream openStream() throws IOException {
360 return getClass().getResourceAsStream(resource);
364 }, PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
367 private static InetSocketAddress getAddress(final int port) {
369 // TODO make address configurable
370 return new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), port);
371 } catch (final UnknownHostException e) {
372 throw new RuntimeException(e);
377 public void close() {
378 for (final SshProxyServer sshWrapper : sshWrappers) {
381 for (final Channel deviceCh : devicesChannels) {
384 nettyThreadgroup.shutdownGracefully();
385 minaTimerExecutor.shutdownNow();
386 nioExecutor.shutdownNow();
390 private static class SimulatedOperationProvider implements NetconfOperationProvider {
391 private final SessionIdProvider idProvider;
392 private final Set<NetconfOperationService> netconfOperationServices;
395 public SimulatedOperationProvider(final SessionIdProvider idProvider, final Set<Capability> caps) {
396 this.idProvider = idProvider;
397 final SimulatedOperationService simulatedOperationService = new SimulatedOperationService(caps, idProvider.getCurrentSessionId());
398 this.netconfOperationServices = Sets.<NetconfOperationService>newHashSet(simulatedOperationService);
402 public NetconfOperationServiceSnapshot openSnapshot(final String sessionIdForReporting) {
403 return new SimulatedServiceSnapshot(idProvider, netconfOperationServices);
406 public void addService(final NetconfOperationService monitoringService) {
407 netconfOperationServices.add(monitoringService);
410 private static class SimulatedServiceSnapshot implements NetconfOperationServiceSnapshot {
411 private final SessionIdProvider idProvider;
412 private final Set<NetconfOperationService> netconfOperationServices;
414 public SimulatedServiceSnapshot(final SessionIdProvider idProvider, final Set<NetconfOperationService> netconfOperationServices) {
415 this.idProvider = idProvider;
416 this.netconfOperationServices = netconfOperationServices;
420 public String getNetconfSessionIdForReporting() {
421 return String.valueOf(idProvider.getCurrentSessionId());
425 public Set<NetconfOperationService> getServices() {
426 return netconfOperationServices;
430 public void close() throws Exception {}
433 static class SimulatedOperationService implements NetconfOperationService {
434 private final Set<Capability> capabilities;
435 private final long currentSessionId;
437 public SimulatedOperationService(final Set<Capability> capabilities, final long currentSessionId) {
438 this.capabilities = capabilities;
439 this.currentSessionId = currentSessionId;
443 public Set<Capability> getCapabilities() {
448 public Set<NetconfOperation> getNetconfOperations() {
449 final DataList storage = new DataList();
450 final SimulatedGet sGet = new SimulatedGet(String.valueOf(currentSessionId), storage);
451 final SimulatedEditConfig sEditConfig = new SimulatedEditConfig(String.valueOf(currentSessionId), storage);
452 final SimulatedGetConfig sGetConfig = new SimulatedGetConfig(String.valueOf(currentSessionId), storage);
453 final SimulatedCommit sCommit = new SimulatedCommit(String.valueOf(currentSessionId));
454 final SimulatedLock sLock = new SimulatedLock(String.valueOf(currentSessionId));
455 final SimulatedUnLock sUnlock = new SimulatedUnLock(String.valueOf(currentSessionId));
456 return Sets.<NetconfOperation>newHashSet(sGet, sGetConfig, sEditConfig, sCommit, sLock, sUnlock);
460 public void close() {
466 private class LoggingMonitoringService implements SessionMonitoringService {
468 public void onSessionUp(final NetconfManagementSession session) {
469 LOG.debug("Session {} established", session);
473 public void onSessionDown(final NetconfManagementSession session) {
474 LOG.debug("Session {} down", session);