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.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.Collections;
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.config.util.capability.Capability;
59 import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
60 import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
61 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
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.NetconfOperation;
67 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
68 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
69 import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringActivator;
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.controller.netconf.test.tool.rpc.DataList;
75 import org.opendaylight.controller.netconf.test.tool.rpc.SimulatedCommit;
76 import org.opendaylight.controller.netconf.test.tool.rpc.SimulatedCreateSubscription;
77 import org.opendaylight.controller.netconf.test.tool.rpc.SimulatedEditConfig;
78 import org.opendaylight.controller.netconf.test.tool.rpc.SimulatedGet;
79 import org.opendaylight.controller.netconf.test.tool.rpc.SimulatedGetConfig;
80 import org.opendaylight.controller.netconf.test.tool.rpc.SimulatedLock;
81 import org.opendaylight.controller.netconf.test.tool.rpc.SimulatedUnLock;
82 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
83 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
84 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
85 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
86 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
87 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
88 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
89 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
90 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
91 import org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils;
92 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
93 import org.opendaylight.yangtools.yang.parser.impl.YangParserListenerImpl;
94 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
95 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
96 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
97 import org.slf4j.Logger;
98 import org.slf4j.LoggerFactory;
100 public class NetconfDeviceSimulator implements Closeable {
102 private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSimulator.class);
104 private final NioEventLoopGroup nettyThreadgroup;
105 private final HashedWheelTimer hashedWheelTimer;
106 private final List<Channel> devicesChannels = Lists.newArrayList();
107 private final List<SshProxyServer> sshWrappers = Lists.newArrayList();
108 private final ScheduledExecutorService minaTimerExecutor;
109 private final ExecutorService nioExecutor;
111 private boolean sendFakeSchema = false;
113 public NetconfDeviceSimulator() {
114 // TODO make pool size configurable
115 this(new NioEventLoopGroup(), new HashedWheelTimer(),
116 Executors.newScheduledThreadPool(8, new ThreadFactoryBuilder().setNameFormat("netconf-ssh-server-mina-timers-%d").build()),
117 ThreadUtils.newFixedThreadPool("netconf-ssh-server-nio-group", 8));
120 private NetconfDeviceSimulator(final NioEventLoopGroup eventExecutors, final HashedWheelTimer hashedWheelTimer, final ScheduledExecutorService minaTimerExecutor, final ExecutorService nioExecutor) {
121 this.nettyThreadgroup = eventExecutors;
122 this.hashedWheelTimer = hashedWheelTimer;
123 this.minaTimerExecutor = minaTimerExecutor;
124 this.nioExecutor = nioExecutor;
127 private NetconfServerDispatcherImpl createDispatcher(final Map<ModuleBuilder, String> moduleBuilders, final boolean exi, final int generateConfigsTimeout, final Optional<File> notificationsFile) {
129 final Set<Capability> capabilities = Sets.newHashSet(Collections2.transform(moduleBuilders.keySet(), new Function<ModuleBuilder, Capability>() {
131 public Capability apply(final ModuleBuilder input) {
132 if (sendFakeSchema) {
133 sendFakeSchema = false;
134 return new FakeModuleBuilderCapability(input, moduleBuilders.get(input));
136 return new ModuleBuilderCapability(input, moduleBuilders.get(input));
141 final SessionIdProvider idProvider = new SessionIdProvider();
143 final AggregatedNetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory = new AggregatedNetconfOperationServiceFactory();
144 final SimulatedOperationProvider simulatedOperationProvider = new SimulatedOperationProvider(idProvider, capabilities, notificationsFile);
146 final NetconfMonitoringService monitoringService1 = new DummyMonitoringService(capabilities);
148 final NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory monitoringService =
149 new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(
150 new NetconfMonitoringOperationService(monitoringService1));
151 aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(simulatedOperationProvider);
152 aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(monitoringService);
154 final Set<String> serverCapabilities = exi
155 ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES
156 : Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0, XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
158 final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
159 hashedWheelTimer, aggregatedNetconfOperationServiceFactory, idProvider, generateConfigsTimeout, monitoringService1, serverCapabilities);
161 final NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(
162 serverNegotiatorFactory);
163 return new NetconfServerDispatcherImpl(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
166 private Map<ModuleBuilder, String> toModuleBuilders(final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> sources) {
167 final Map<SourceIdentifier, ParserRuleContext> asts = Maps.transformValues(sources, new Function<Map.Entry<ASTSchemaSource, YangTextSchemaSource>, ParserRuleContext>() {
169 public ParserRuleContext apply(final Map.Entry<ASTSchemaSource, YangTextSchemaSource> input) {
170 return input.getKey().getAST();
173 final Map<String, NavigableMap<Date, URI>> namespaceContext = BuilderUtils.createYangNamespaceContext(
174 asts.values(), Optional.<SchemaContext>absent());
176 final ParseTreeWalker walker = new ParseTreeWalker();
177 final Map<ModuleBuilder, String> sourceToBuilder = new HashMap<>();
179 for (final Map.Entry<SourceIdentifier, ParserRuleContext> entry : asts.entrySet()) {
180 final ModuleBuilder moduleBuilder = YangParserListenerImpl.create(namespaceContext, entry.getKey().getName(),
181 walker, entry.getValue()).getModuleBuilder();
183 try(InputStreamReader stream = new InputStreamReader(sources.get(entry.getKey()).getValue().openStream(), Charsets.UTF_8)) {
184 sourceToBuilder.put(moduleBuilder, CharStreams.toString(stream));
185 } catch (final IOException e) {
186 throw new RuntimeException(e);
190 return sourceToBuilder;
194 public List<Integer> start(final Main.Params params) {
195 LOG.info("Starting {}, {} simulated devices starting on port {}", params.deviceCount, params.ssh ? "SSH" : "TCP", params.startingPort);
197 final Map<ModuleBuilder, String> moduleBuilders = parseSchemasToModuleBuilders(params);
199 final NetconfServerDispatcherImpl dispatcher = createDispatcher(moduleBuilders, params.exi, params.generateConfigsTimeout, Optional.fromNullable(params.notificationFile));
201 int currentPort = params.startingPort;
203 final List<Integer> openDevices = Lists.newArrayList();
205 // Generate key to temp folder
206 final PEMGeneratorHostKeyProvider keyPairProvider = getPemGeneratorHostKeyProvider();
208 for (int i = 0; i < params.deviceCount; i++) {
209 if (currentPort > 65535) {
210 LOG.warn("Port cannot be greater than 65535, stopping further attempts.");
213 final InetSocketAddress address = getAddress(currentPort);
215 final ChannelFuture server;
217 final InetSocketAddress bindingAddress = InetSocketAddress.createUnresolved("0.0.0.0", currentPort);
218 final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());
220 server = dispatcher.createLocalServer(tcpLocalAddress);
222 final SshProxyServer sshServer = new SshProxyServer(minaTimerExecutor, nettyThreadgroup, nioExecutor);
223 sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress, keyPairProvider));
224 sshWrappers.add(sshServer);
225 } catch (final BindException e) {
226 LOG.warn("Cannot start simulated device on {}, port already in use. Skipping.", address);
227 // Close local server and continue
229 if(server.isDone()) {
230 server.channel().close();
233 } catch (final IOException e) {
234 LOG.warn("Cannot start simulated device on {} due to IOException.", address, e);
242 } catch (final InterruptedException e) {
243 throw new RuntimeException(e);
244 } catch (final ExecutionException e) {
245 LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
249 LOG.debug("Simulated SSH device started on {}", address);
252 server = dispatcher.createServer(address);
257 } catch (final InterruptedException e) {
258 throw new RuntimeException(e);
259 } catch (final ExecutionException e) {
260 LOG.warn("Cannot start tcp simulated device on {}, skipping", address, e);
264 LOG.debug("Simulated TCP device started on {}", address);
267 devicesChannels.add(server.channel());
268 openDevices.add(currentPort - 1);
271 if(openDevices.size() == params.deviceCount) {
272 LOG.info("All simulated devices started successfully from port {} to {}", params.startingPort, currentPort - 1);
273 } else if (openDevices.size() == 0) {
274 LOG.warn("No simulated devices started.");
276 LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
282 private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress, final LocalAddress tcpLocalAddress, final PEMGeneratorHostKeyProvider keyPairProvider) throws IOException {
283 return new SshProxyServerConfigurationBuilder()
284 .setBindingAddress(bindingAddress)
285 .setLocalAddress(tcpLocalAddress)
286 .setAuthenticator(new PasswordAuthenticator() {
288 public boolean authenticate(final String username, final String password, final ServerSession session) {
292 .setKeyPairProvider(keyPairProvider)
293 .setIdleTimeout(Integer.MAX_VALUE)
294 .createSshProxyServerConfiguration();
297 private PEMGeneratorHostKeyProvider getPemGeneratorHostKeyProvider() {
299 final Path tempFile = Files.createTempFile("tempKeyNetconfTest", "suffix");
300 return new PEMGeneratorHostKeyProvider(tempFile.toAbsolutePath().toString());
301 } catch (final IOException e) {
302 LOG.error("Unable to generate PEM key", e);
303 throw new RuntimeException(e);
307 private Map<ModuleBuilder, String> parseSchemasToModuleBuilders(final Main.Params params) {
308 final SharedSchemaRepository consumer = new SharedSchemaRepository("netconf-simulator");
309 consumer.registerSchemaSourceListener(TextToASTTransformer.create(consumer, consumer));
311 final Set<SourceIdentifier> loadedSources = Sets.newHashSet();
313 consumer.registerSchemaSourceListener(new SchemaSourceListener() {
315 public void schemaSourceEncountered(final SchemaSourceRepresentation schemaSourceRepresentation) {}
318 public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> potentialSchemaSources) {
319 for (final PotentialSchemaSource<?> potentialSchemaSource : potentialSchemaSources) {
320 loadedSources.add(potentialSchemaSource.getSourceIdentifier());
325 public void schemaSourceUnregistered(final PotentialSchemaSource<?> potentialSchemaSource) {}
328 if(params.schemasDir != null) {
329 final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(consumer, YangTextSchemaSource.class, params.schemasDir);
330 consumer.registerSchemaSourceListener(cache);
333 addDefaultSchemas(consumer);
335 final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> asts = Maps.newHashMap();
336 for (final SourceIdentifier loadedSource : loadedSources) {
338 final CheckedFuture<ASTSchemaSource, SchemaSourceException> ast = consumer.getSchemaSource(loadedSource, ASTSchemaSource.class);
339 final CheckedFuture<YangTextSchemaSource, SchemaSourceException> text = consumer.getSchemaSource(loadedSource, YangTextSchemaSource.class);
340 asts.put(loadedSource, new AbstractMap.SimpleEntry<>(ast.get(), text.get()));
341 } catch (final InterruptedException e) {
342 throw new RuntimeException(e);
343 } catch (final ExecutionException e) {
344 throw new RuntimeException("Cannot parse schema context", e);
347 return toModuleBuilders(asts);
350 private void addDefaultSchemas(final SharedSchemaRepository consumer) {
351 SourceIdentifier sId = new SourceIdentifier("ietf-netconf-monitoring", "2010-10-04");
352 registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring.yang", sId);
354 sId = new SourceIdentifier("ietf-netconf-monitoring-extension", "2013-12-10");
355 registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring-extension.yang", sId);
357 sId = new SourceIdentifier("ietf-yang-types", "2010-09-24");
358 registerSource(consumer, "/META-INF/yang/ietf-yang-types.yang", sId);
360 sId = new SourceIdentifier("ietf-inet-types", "2010-09-24");
361 registerSource(consumer, "/META-INF/yang/ietf-inet-types.yang", sId);
364 private void registerSource(final SharedSchemaRepository consumer, final String resource, final SourceIdentifier sourceId) {
365 consumer.registerSchemaSource(new SchemaSourceProvider<SchemaSourceRepresentation>() {
367 public CheckedFuture<? extends SchemaSourceRepresentation, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
368 return Futures.immediateCheckedFuture(new YangTextSchemaSource(sourceId) {
370 protected MoreObjects.ToStringHelper addToStringAttributes(final MoreObjects.ToStringHelper toStringHelper) {
371 return toStringHelper;
375 public InputStream openStream() throws IOException {
376 return getClass().getResourceAsStream(resource);
380 }, PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
383 private static InetSocketAddress getAddress(final int port) {
385 // TODO make address configurable
386 return new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), port);
387 } catch (final UnknownHostException e) {
388 throw new RuntimeException(e);
393 public void close() {
394 for (final SshProxyServer sshWrapper : sshWrappers) {
397 for (final Channel deviceCh : devicesChannels) {
400 nettyThreadgroup.shutdownGracefully();
401 minaTimerExecutor.shutdownNow();
402 nioExecutor.shutdownNow();
406 private static class SimulatedOperationProvider implements NetconfOperationServiceFactory {
407 private final Set<Capability> caps;
408 private final SimulatedOperationService simulatedOperationService;
411 public SimulatedOperationProvider(final SessionIdProvider idProvider, final Set<Capability> caps, final Optional<File> notificationsFile) {
413 simulatedOperationService = new SimulatedOperationService(idProvider.getCurrentSessionId(), notificationsFile);
417 public Set<Capability> getCapabilities() {
422 public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
423 listener.onCapabilitiesChanged(caps, Collections.<Capability>emptySet());
424 return new AutoCloseable() {
426 public void close() throws Exception {}
431 public NetconfOperationService createService(final String netconfSessionIdForReporting) {
432 return simulatedOperationService;
435 static class SimulatedOperationService implements NetconfOperationService {
436 private final long currentSessionId;
437 private final Optional<File> notificationsFile;
439 public SimulatedOperationService(final long currentSessionId, final Optional<File> notificationsFile) {
440 this.currentSessionId = currentSessionId;
441 this.notificationsFile = notificationsFile;
445 public Set<NetconfOperation> getNetconfOperations() {
446 final DataList storage = new DataList();
447 final SimulatedGet sGet = new SimulatedGet(String.valueOf(currentSessionId), storage);
448 final SimulatedEditConfig sEditConfig = new SimulatedEditConfig(String.valueOf(currentSessionId), storage);
449 final SimulatedGetConfig sGetConfig = new SimulatedGetConfig(String.valueOf(currentSessionId), storage);
450 final SimulatedCommit sCommit = new SimulatedCommit(String.valueOf(currentSessionId));
451 final SimulatedLock sLock = new SimulatedLock(String.valueOf(currentSessionId));
452 final SimulatedUnLock sUnlock = new SimulatedUnLock(String.valueOf(currentSessionId));
453 final SimulatedCreateSubscription sCreateSubs = new SimulatedCreateSubscription(String.valueOf(currentSessionId), notificationsFile);
454 return Sets.<NetconfOperation>newHashSet(sGet, sGetConfig, sEditConfig, sCommit, sLock, sUnlock, sCreateSubs);
458 public void close() {