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;
47 import java.util.TreeMap;
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.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.DefaultCommitNotificationProducer;
63 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcherImpl;
64 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
65 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
66 import org.opendaylight.controller.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
67 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
68 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
69 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
70 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
71 import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringActivator;
72 import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringOperationService;
73 import org.opendaylight.controller.netconf.ssh.SshProxyServer;
74 import org.opendaylight.controller.netconf.ssh.SshProxyServerConfiguration;
75 import org.opendaylight.controller.netconf.ssh.SshProxyServerConfigurationBuilder;
76 import org.opendaylight.controller.netconf.test.tool.rpc.DataList;
77 import org.opendaylight.controller.netconf.test.tool.rpc.SimulatedCommit;
78 import org.opendaylight.controller.netconf.test.tool.rpc.SimulatedCreateSubscription;
79 import org.opendaylight.controller.netconf.test.tool.rpc.SimulatedEditConfig;
80 import org.opendaylight.controller.netconf.test.tool.rpc.SimulatedGet;
81 import org.opendaylight.controller.netconf.test.tool.rpc.SimulatedGetConfig;
82 import org.opendaylight.controller.netconf.test.tool.rpc.SimulatedLock;
83 import org.opendaylight.controller.netconf.test.tool.rpc.SimulatedUnLock;
84 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
85 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
86 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
87 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
88 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
89 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
90 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
91 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
92 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
93 import org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils;
94 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
95 import org.opendaylight.yangtools.yang.parser.impl.YangParserListenerImpl;
96 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
97 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
98 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
99 import org.slf4j.Logger;
100 import org.slf4j.LoggerFactory;
102 public class NetconfDeviceSimulator implements Closeable {
104 private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSimulator.class);
106 private final NioEventLoopGroup nettyThreadgroup;
107 private final HashedWheelTimer hashedWheelTimer;
108 private final List<Channel> devicesChannels = Lists.newArrayList();
109 private final List<SshProxyServer> sshWrappers = Lists.newArrayList();
110 private final ScheduledExecutorService minaTimerExecutor;
111 private final ExecutorService nioExecutor;
113 private boolean sendFakeSchema = false;
115 public NetconfDeviceSimulator() {
116 // TODO make pool size configurable
117 this(new NioEventLoopGroup(), new HashedWheelTimer(),
118 Executors.newScheduledThreadPool(8, new ThreadFactoryBuilder().setNameFormat("netconf-ssh-server-mina-timers-%d").build()),
119 ThreadUtils.newFixedThreadPool("netconf-ssh-server-nio-group", 8));
122 private NetconfDeviceSimulator(final NioEventLoopGroup eventExecutors, final HashedWheelTimer hashedWheelTimer, final ScheduledExecutorService minaTimerExecutor, final ExecutorService nioExecutor) {
123 this.nettyThreadgroup = eventExecutors;
124 this.hashedWheelTimer = hashedWheelTimer;
125 this.minaTimerExecutor = minaTimerExecutor;
126 this.nioExecutor = nioExecutor;
129 private NetconfServerDispatcherImpl createDispatcher(final Map<ModuleBuilder, String> moduleBuilders, final boolean exi, final int generateConfigsTimeout, final Optional<File> notificationsFile) {
131 final Set<Capability> capabilities = Sets.newHashSet(Collections2.transform(moduleBuilders.keySet(), new Function<ModuleBuilder, Capability>() {
133 public Capability apply(final ModuleBuilder input) {
134 if (sendFakeSchema) {
135 sendFakeSchema = false;
136 return new FakeModuleBuilderCapability(input, moduleBuilders.get(input));
138 return new ModuleBuilderCapability(input, moduleBuilders.get(input));
143 final SessionIdProvider idProvider = new SessionIdProvider();
146 final AggregatedNetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory = new AggregatedNetconfOperationServiceFactory();
147 final SimulatedOperationProvider simulatedOperationProvider = new SimulatedOperationProvider(idProvider, capabilities, notificationsFile);
149 final NetconfMonitoringService monitoringService1 = new NetconfMonitoringServiceImpl(aggregatedNetconfOperationServiceFactory);
150 final NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory monitoringService =
151 new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(new NetconfMonitoringOperationService(monitoringService1));
152 aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(simulatedOperationProvider);
153 aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(monitoringService);
155 final DefaultCommitNotificationProducer commitNotifier = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
157 final Set<String> serverCapabilities = exi
158 ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES
159 : Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0, XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
161 final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
162 hashedWheelTimer, aggregatedNetconfOperationServiceFactory, idProvider, generateConfigsTimeout, commitNotifier, monitoringService1, serverCapabilities);
164 final NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(
165 serverNegotiatorFactory);
166 return new NetconfServerDispatcherImpl(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
169 private Map<ModuleBuilder, String> toModuleBuilders(final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> sources) {
170 final Map<SourceIdentifier, ParserRuleContext> asts = Maps.transformValues(sources, new Function<Map.Entry<ASTSchemaSource, YangTextSchemaSource>, ParserRuleContext>() {
172 public ParserRuleContext apply(final Map.Entry<ASTSchemaSource, YangTextSchemaSource> input) {
173 return input.getKey().getAST();
176 final Map<String, TreeMap<Date, URI>> namespaceContext = BuilderUtils.createYangNamespaceContext(
177 asts.values(), Optional.<SchemaContext>absent());
179 final ParseTreeWalker walker = new ParseTreeWalker();
180 final Map<ModuleBuilder, String> sourceToBuilder = new HashMap<>();
182 for (final Map.Entry<SourceIdentifier, ParserRuleContext> entry : asts.entrySet()) {
183 final ModuleBuilder moduleBuilder = YangParserListenerImpl.create(namespaceContext, entry.getKey().getName(),
184 walker, entry.getValue()).getModuleBuilder();
186 try(InputStreamReader stream = new InputStreamReader(sources.get(entry.getKey()).getValue().openStream(), Charsets.UTF_8)) {
187 sourceToBuilder.put(moduleBuilder, CharStreams.toString(stream));
188 } catch (final IOException e) {
189 throw new RuntimeException(e);
193 return sourceToBuilder;
197 public List<Integer> start(final Main.Params params) {
198 LOG.info("Starting {}, {} simulated devices starting on port {}", params.deviceCount, params.ssh ? "SSH" : "TCP", params.startingPort);
200 final Map<ModuleBuilder, String> moduleBuilders = parseSchemasToModuleBuilders(params);
202 final NetconfServerDispatcherImpl dispatcher = createDispatcher(moduleBuilders, params.exi, params.generateConfigsTimeout, Optional.fromNullable(params.notificationFile));
204 int currentPort = params.startingPort;
206 final List<Integer> openDevices = Lists.newArrayList();
208 // Generate key to temp folder
209 final PEMGeneratorHostKeyProvider keyPairProvider = getPemGeneratorHostKeyProvider();
211 for (int i = 0; i < params.deviceCount; i++) {
212 if (currentPort > 65535) {
213 LOG.warn("Port cannot be greater than 65535, stopping further attempts.");
216 final InetSocketAddress address = getAddress(currentPort);
218 final ChannelFuture server;
220 final InetSocketAddress bindingAddress = InetSocketAddress.createUnresolved("0.0.0.0", currentPort);
221 final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());
223 server = dispatcher.createLocalServer(tcpLocalAddress);
225 final SshProxyServer sshServer = new SshProxyServer(minaTimerExecutor, nettyThreadgroup, nioExecutor);
226 sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress, keyPairProvider));
227 sshWrappers.add(sshServer);
228 } catch (final BindException e) {
229 LOG.warn("Cannot start simulated device on {}, port already in use. Skipping.", address);
230 // Close local server and continue
232 if(server.isDone()) {
233 server.channel().close();
236 } catch (final IOException e) {
237 LOG.warn("Cannot start simulated device on {} due to IOException.", address, e);
245 } catch (final InterruptedException e) {
246 throw new RuntimeException(e);
247 } catch (final ExecutionException e) {
248 LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
252 LOG.debug("Simulated SSH device started on {}", address);
255 server = dispatcher.createServer(address);
260 } catch (final InterruptedException e) {
261 throw new RuntimeException(e);
262 } catch (final ExecutionException e) {
263 LOG.warn("Cannot start tcp simulated device on {}, skipping", address, e);
267 LOG.debug("Simulated TCP device started on {}", address);
270 devicesChannels.add(server.channel());
271 openDevices.add(currentPort - 1);
274 if(openDevices.size() == params.deviceCount) {
275 LOG.info("All simulated devices started successfully from port {} to {}", params.startingPort, currentPort - 1);
276 } else if (openDevices.size() == 0) {
277 LOG.warn("No simulated devices started.");
279 LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
285 private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress, final LocalAddress tcpLocalAddress, final PEMGeneratorHostKeyProvider keyPairProvider) throws IOException {
286 return new SshProxyServerConfigurationBuilder()
287 .setBindingAddress(bindingAddress)
288 .setLocalAddress(tcpLocalAddress)
289 .setAuthenticator(new PasswordAuthenticator() {
291 public boolean authenticate(final String username, final String password, final ServerSession session) {
295 .setKeyPairProvider(keyPairProvider)
296 .setIdleTimeout(Integer.MAX_VALUE)
297 .createSshProxyServerConfiguration();
300 private PEMGeneratorHostKeyProvider getPemGeneratorHostKeyProvider() {
302 final Path tempFile = Files.createTempFile("tempKeyNetconfTest", "suffix");
303 return new PEMGeneratorHostKeyProvider(tempFile.toAbsolutePath().toString());
304 } catch (final IOException e) {
305 LOG.error("Unable to generate PEM key", e);
306 throw new RuntimeException(e);
310 private Map<ModuleBuilder, String> parseSchemasToModuleBuilders(final Main.Params params) {
311 final SharedSchemaRepository consumer = new SharedSchemaRepository("netconf-simulator");
312 consumer.registerSchemaSourceListener(TextToASTTransformer.create(consumer, consumer));
314 final Set<SourceIdentifier> loadedSources = Sets.newHashSet();
316 consumer.registerSchemaSourceListener(new SchemaSourceListener() {
318 public void schemaSourceEncountered(final SchemaSourceRepresentation schemaSourceRepresentation) {}
321 public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> potentialSchemaSources) {
322 for (final PotentialSchemaSource<?> potentialSchemaSource : potentialSchemaSources) {
323 loadedSources.add(potentialSchemaSource.getSourceIdentifier());
328 public void schemaSourceUnregistered(final PotentialSchemaSource<?> potentialSchemaSource) {}
331 if(params.schemasDir != null) {
332 final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(consumer, YangTextSchemaSource.class, params.schemasDir);
333 consumer.registerSchemaSourceListener(cache);
336 addDefaultSchemas(consumer);
338 final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> asts = Maps.newHashMap();
339 for (final SourceIdentifier loadedSource : loadedSources) {
341 final CheckedFuture<ASTSchemaSource, SchemaSourceException> ast = consumer.getSchemaSource(loadedSource, ASTSchemaSource.class);
342 final CheckedFuture<YangTextSchemaSource, SchemaSourceException> text = consumer.getSchemaSource(loadedSource, YangTextSchemaSource.class);
343 asts.put(loadedSource, new AbstractMap.SimpleEntry<>(ast.get(), text.get()));
344 } catch (final InterruptedException e) {
345 throw new RuntimeException(e);
346 } catch (final ExecutionException e) {
347 throw new RuntimeException("Cannot parse schema context", e);
350 return toModuleBuilders(asts);
353 private void addDefaultSchemas(final SharedSchemaRepository consumer) {
354 SourceIdentifier sId = new SourceIdentifier("ietf-netconf-monitoring", "2010-10-04");
355 registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring.yang", sId);
357 sId = new SourceIdentifier("ietf-netconf-monitoring-extension", "2013-12-10");
358 registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring-extension.yang", sId);
360 sId = new SourceIdentifier("ietf-yang-types", "2010-09-24");
361 registerSource(consumer, "/META-INF/yang/ietf-yang-types.yang", sId);
363 sId = new SourceIdentifier("ietf-inet-types", "2010-09-24");
364 registerSource(consumer, "/META-INF/yang/ietf-inet-types.yang", sId);
367 private void registerSource(final SharedSchemaRepository consumer, final String resource, final SourceIdentifier sourceId) {
368 consumer.registerSchemaSource(new SchemaSourceProvider<SchemaSourceRepresentation>() {
370 public CheckedFuture<? extends SchemaSourceRepresentation, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
371 return Futures.immediateCheckedFuture(new YangTextSchemaSource(sourceId) {
373 protected MoreObjects.ToStringHelper addToStringAttributes(final MoreObjects.ToStringHelper toStringHelper) {
374 return toStringHelper;
378 public InputStream openStream() throws IOException {
379 return getClass().getResourceAsStream(resource);
383 }, PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
386 private static InetSocketAddress getAddress(final int port) {
388 // TODO make address configurable
389 return new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), port);
390 } catch (final UnknownHostException e) {
391 throw new RuntimeException(e);
396 public void close() {
397 for (final SshProxyServer sshWrapper : sshWrappers) {
400 for (final Channel deviceCh : devicesChannels) {
403 nettyThreadgroup.shutdownGracefully();
404 minaTimerExecutor.shutdownNow();
405 nioExecutor.shutdownNow();
409 private static class SimulatedOperationProvider implements NetconfOperationServiceFactory {
410 private final Set<Capability> caps;
411 private final SimulatedOperationService simulatedOperationService;
414 public SimulatedOperationProvider(final SessionIdProvider idProvider, final Set<Capability> caps, final Optional<File> notificationsFile) {
416 simulatedOperationService = new SimulatedOperationService(idProvider.getCurrentSessionId(), notificationsFile);
420 public Set<Capability> getCapabilities() {
425 public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
426 listener.onCapabilitiesAdded(caps);
427 return new AutoCloseable() {
429 public void close() throws Exception {}
434 public NetconfOperationService createService(final String netconfSessionIdForReporting) {
435 return simulatedOperationService;
438 static class SimulatedOperationService implements NetconfOperationService {
439 private final long currentSessionId;
440 private final Optional<File> notificationsFile;
442 public SimulatedOperationService(final long currentSessionId, final Optional<File> notificationsFile) {
443 this.currentSessionId = currentSessionId;
444 this.notificationsFile = notificationsFile;
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 final SimulatedCreateSubscription sCreateSubs = new SimulatedCreateSubscription(String.valueOf(currentSessionId), notificationsFile);
457 return Sets.<NetconfOperation>newHashSet(sGet, sGetConfig, sEditConfig, sCommit, sLock, sUnlock, sCreateSubs);
461 public void close() {