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.monitoring.NetconfManagementSession;
59 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
60 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
61 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcherImpl;
62 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
63 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
64 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
65 import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
66 import org.opendaylight.controller.netconf.mapping.api.Capability;
67 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
68 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
69 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
70 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceSnapshot;
71 import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringOperationService;
72 import org.opendaylight.controller.netconf.ssh.SshProxyServer;
73 import org.opendaylight.controller.netconf.ssh.SshProxyServerConfiguration;
74 import org.opendaylight.controller.netconf.ssh.SshProxyServerConfigurationBuilder;
75 import org.opendaylight.controller.netconf.test.tool.rpc.DataList;
76 import org.opendaylight.controller.netconf.test.tool.rpc.SimulatedCommit;
77 import org.opendaylight.controller.netconf.test.tool.rpc.SimulatedCreateSubscription;
78 import org.opendaylight.controller.netconf.test.tool.rpc.SimulatedEditConfig;
79 import org.opendaylight.controller.netconf.test.tool.rpc.SimulatedGet;
80 import org.opendaylight.controller.netconf.test.tool.rpc.SimulatedGetConfig;
81 import org.opendaylight.controller.netconf.test.tool.rpc.SimulatedLock;
82 import org.opendaylight.controller.netconf.test.tool.rpc.SimulatedUnLock;
83 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
84 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
85 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
86 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
87 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
88 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
89 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
90 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
91 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
92 import org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils;
93 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
94 import org.opendaylight.yangtools.yang.parser.impl.YangParserListenerImpl;
95 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
96 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
97 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
98 import org.slf4j.Logger;
99 import org.slf4j.LoggerFactory;
101 public class NetconfDeviceSimulator implements Closeable {
103 private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSimulator.class);
105 private final NioEventLoopGroup nettyThreadgroup;
106 private final HashedWheelTimer hashedWheelTimer;
107 private final List<Channel> devicesChannels = Lists.newArrayList();
108 private final List<SshProxyServer> sshWrappers = Lists.newArrayList();
109 private final ScheduledExecutorService minaTimerExecutor;
110 private final ExecutorService nioExecutor;
112 private boolean sendFakeSchema = false;
114 public NetconfDeviceSimulator() {
115 // TODO make pool size configurable
116 this(new NioEventLoopGroup(), new HashedWheelTimer(),
117 Executors.newScheduledThreadPool(8, new ThreadFactoryBuilder().setNameFormat("netconf-ssh-server-mina-timers-%d").build()),
118 ThreadUtils.newFixedThreadPool("netconf-ssh-server-nio-group", 8));
121 private NetconfDeviceSimulator(final NioEventLoopGroup eventExecutors, final HashedWheelTimer hashedWheelTimer, final ScheduledExecutorService minaTimerExecutor, final ExecutorService nioExecutor) {
122 this.nettyThreadgroup = eventExecutors;
123 this.hashedWheelTimer = hashedWheelTimer;
124 this.minaTimerExecutor = minaTimerExecutor;
125 this.nioExecutor = nioExecutor;
128 private NetconfServerDispatcherImpl createDispatcher(final Map<ModuleBuilder, String> moduleBuilders, final boolean exi, final int generateConfigsTimeout, final Optional<File> notificationsFile) {
130 final Set<Capability> capabilities = Sets.newHashSet(Collections2.transform(moduleBuilders.keySet(), new Function<ModuleBuilder, Capability>() {
132 public Capability apply(final ModuleBuilder input) {
133 if (sendFakeSchema) {
134 sendFakeSchema = false;
135 return new FakeModuleBuilderCapability(input, moduleBuilders.get(input));
137 return new ModuleBuilderCapability(input, moduleBuilders.get(input));
142 final SessionIdProvider idProvider = new SessionIdProvider();
144 final SimulatedOperationProvider simulatedOperationProvider = new SimulatedOperationProvider(idProvider, capabilities, notificationsFile);
145 final NetconfMonitoringOperationService monitoringService = new NetconfMonitoringOperationService(new NetconfMonitoringServiceImpl(simulatedOperationProvider));
146 simulatedOperationProvider.addService(monitoringService);
148 final DefaultCommitNotificationProducer commitNotifier = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
150 final Set<String> serverCapabilities = exi
151 ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES
152 : Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0, XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
154 final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
155 hashedWheelTimer, simulatedOperationProvider, idProvider, generateConfigsTimeout, commitNotifier, new LoggingMonitoringService(), serverCapabilities);
157 final NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(
158 serverNegotiatorFactory);
159 return new NetconfServerDispatcherImpl(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
162 private Map<ModuleBuilder, String> toModuleBuilders(final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> sources) {
163 final Map<SourceIdentifier, ParserRuleContext> asts = Maps.transformValues(sources, new Function<Map.Entry<ASTSchemaSource, YangTextSchemaSource>, ParserRuleContext>() {
165 public ParserRuleContext apply(final Map.Entry<ASTSchemaSource, YangTextSchemaSource> input) {
166 return input.getKey().getAST();
169 final Map<String, TreeMap<Date, URI>> namespaceContext = BuilderUtils.createYangNamespaceContext(
170 asts.values(), Optional.<SchemaContext>absent());
172 final ParseTreeWalker walker = new ParseTreeWalker();
173 final Map<ModuleBuilder, String> sourceToBuilder = new HashMap<>();
175 for (final Map.Entry<SourceIdentifier, ParserRuleContext> entry : asts.entrySet()) {
176 final ModuleBuilder moduleBuilder = YangParserListenerImpl.create(namespaceContext, entry.getKey().getName(),
177 walker, entry.getValue()).getModuleBuilder();
179 try(InputStreamReader stream = new InputStreamReader(sources.get(entry.getKey()).getValue().openStream(), Charsets.UTF_8)) {
180 sourceToBuilder.put(moduleBuilder, CharStreams.toString(stream));
181 } catch (final IOException e) {
182 throw new RuntimeException(e);
186 return sourceToBuilder;
190 public List<Integer> start(final Main.Params params) {
191 LOG.info("Starting {}, {} simulated devices starting on port {}", params.deviceCount, params.ssh ? "SSH" : "TCP", params.startingPort);
193 final Map<ModuleBuilder, String> moduleBuilders = parseSchemasToModuleBuilders(params);
195 final NetconfServerDispatcherImpl dispatcher = createDispatcher(moduleBuilders, params.exi, params.generateConfigsTimeout, Optional.fromNullable(params.notificationFile));
197 int currentPort = params.startingPort;
199 final List<Integer> openDevices = Lists.newArrayList();
201 // Generate key to temp folder
202 final PEMGeneratorHostKeyProvider keyPairProvider = getPemGeneratorHostKeyProvider();
204 for (int i = 0; i < params.deviceCount; i++) {
205 if (currentPort > 65535) {
206 LOG.warn("Port cannot be greater than 65535, stopping further attempts.");
209 final InetSocketAddress address = getAddress(currentPort);
211 final ChannelFuture server;
213 final InetSocketAddress bindingAddress = InetSocketAddress.createUnresolved("0.0.0.0", currentPort);
214 final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());
216 server = dispatcher.createLocalServer(tcpLocalAddress);
218 final SshProxyServer sshServer = new SshProxyServer(minaTimerExecutor, nettyThreadgroup, nioExecutor);
219 sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress, keyPairProvider));
220 sshWrappers.add(sshServer);
221 } catch (final BindException e) {
222 LOG.warn("Cannot start simulated device on {}, port already in use. Skipping.", address);
223 // Close local server and continue
225 if(server.isDone()) {
226 server.channel().close();
229 } catch (final IOException e) {
230 LOG.warn("Cannot start simulated device on {} due to IOException.", address, e);
238 } catch (final InterruptedException e) {
239 throw new RuntimeException(e);
240 } catch (final ExecutionException e) {
241 LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
245 LOG.debug("Simulated SSH device started on {}", address);
248 server = dispatcher.createServer(address);
253 } catch (final InterruptedException e) {
254 throw new RuntimeException(e);
255 } catch (final ExecutionException e) {
256 LOG.warn("Cannot start tcp simulated device on {}, skipping", address, e);
260 LOG.debug("Simulated TCP device started on {}", address);
263 devicesChannels.add(server.channel());
264 openDevices.add(currentPort - 1);
267 if(openDevices.size() == params.deviceCount) {
268 LOG.info("All simulated devices started successfully from port {} to {}", params.startingPort, currentPort - 1);
269 } else if (openDevices.size() == 0) {
270 LOG.warn("No simulated devices started.");
272 LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
278 private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress, final LocalAddress tcpLocalAddress, final PEMGeneratorHostKeyProvider keyPairProvider) throws IOException {
279 return new SshProxyServerConfigurationBuilder()
280 .setBindingAddress(bindingAddress)
281 .setLocalAddress(tcpLocalAddress)
282 .setAuthenticator(new PasswordAuthenticator() {
284 public boolean authenticate(final String username, final String password, final ServerSession session) {
288 .setKeyPairProvider(keyPairProvider)
289 .setIdleTimeout(Integer.MAX_VALUE)
290 .createSshProxyServerConfiguration();
293 private PEMGeneratorHostKeyProvider getPemGeneratorHostKeyProvider() {
295 final Path tempFile = Files.createTempFile("tempKeyNetconfTest", "suffix");
296 return new PEMGeneratorHostKeyProvider(tempFile.toAbsolutePath().toString());
297 } catch (final IOException e) {
298 LOG.error("Unable to generate PEM key", e);
299 throw new RuntimeException(e);
303 private Map<ModuleBuilder, String> parseSchemasToModuleBuilders(final Main.Params params) {
304 final SharedSchemaRepository consumer = new SharedSchemaRepository("netconf-simulator");
305 consumer.registerSchemaSourceListener(TextToASTTransformer.create(consumer, consumer));
307 final Set<SourceIdentifier> loadedSources = Sets.newHashSet();
309 consumer.registerSchemaSourceListener(new SchemaSourceListener() {
311 public void schemaSourceEncountered(final SchemaSourceRepresentation schemaSourceRepresentation) {}
314 public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> potentialSchemaSources) {
315 for (final PotentialSchemaSource<?> potentialSchemaSource : potentialSchemaSources) {
316 loadedSources.add(potentialSchemaSource.getSourceIdentifier());
321 public void schemaSourceUnregistered(final PotentialSchemaSource<?> potentialSchemaSource) {}
324 if(params.schemasDir != null) {
325 final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(consumer, YangTextSchemaSource.class, params.schemasDir);
326 consumer.registerSchemaSourceListener(cache);
329 addDefaultSchemas(consumer);
331 final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> asts = Maps.newHashMap();
332 for (final SourceIdentifier loadedSource : loadedSources) {
334 final CheckedFuture<ASTSchemaSource, SchemaSourceException> ast = consumer.getSchemaSource(loadedSource, ASTSchemaSource.class);
335 final CheckedFuture<YangTextSchemaSource, SchemaSourceException> text = consumer.getSchemaSource(loadedSource, YangTextSchemaSource.class);
336 asts.put(loadedSource, new AbstractMap.SimpleEntry<>(ast.get(), text.get()));
337 } catch (final InterruptedException e) {
338 throw new RuntimeException(e);
339 } catch (final ExecutionException e) {
340 throw new RuntimeException("Cannot parse schema context", e);
343 return toModuleBuilders(asts);
346 private void addDefaultSchemas(final SharedSchemaRepository consumer) {
347 SourceIdentifier sId = new SourceIdentifier("ietf-netconf-monitoring", "2010-10-04");
348 registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring.yang", sId);
350 sId = new SourceIdentifier("ietf-yang-types", "2013-07-15");
351 registerSource(consumer, "/META-INF/yang/ietf-yang-types@2013-07-15.yang", sId);
353 sId = new SourceIdentifier("ietf-inet-types", "2010-09-24");
354 registerSource(consumer, "/META-INF/yang/ietf-inet-types.yang", sId);
357 private void registerSource(final SharedSchemaRepository consumer, final String resource, final SourceIdentifier sourceId) {
358 consumer.registerSchemaSource(new SchemaSourceProvider<SchemaSourceRepresentation>() {
360 public CheckedFuture<? extends SchemaSourceRepresentation, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
361 return Futures.immediateCheckedFuture(new YangTextSchemaSource(sourceId) {
363 protected MoreObjects.ToStringHelper addToStringAttributes(final MoreObjects.ToStringHelper toStringHelper) {
364 return toStringHelper;
368 public InputStream openStream() throws IOException {
369 return getClass().getResourceAsStream(resource);
373 }, PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
376 private static InetSocketAddress getAddress(final int port) {
378 // TODO make address configurable
379 return new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), port);
380 } catch (final UnknownHostException e) {
381 throw new RuntimeException(e);
386 public void close() {
387 for (final SshProxyServer sshWrapper : sshWrappers) {
390 for (final Channel deviceCh : devicesChannels) {
393 nettyThreadgroup.shutdownGracefully();
394 minaTimerExecutor.shutdownNow();
395 nioExecutor.shutdownNow();
399 private static class SimulatedOperationProvider implements NetconfOperationProvider {
400 private final SessionIdProvider idProvider;
401 private final Set<NetconfOperationService> netconfOperationServices;
404 public SimulatedOperationProvider(final SessionIdProvider idProvider, final Set<Capability> caps, final Optional<File> notificationsFile) {
405 this.idProvider = idProvider;
406 final SimulatedOperationService simulatedOperationService = new SimulatedOperationService(caps, idProvider.getCurrentSessionId(), notificationsFile);
407 this.netconfOperationServices = Sets.<NetconfOperationService>newHashSet(simulatedOperationService);
411 public NetconfOperationServiceSnapshot openSnapshot(final String sessionIdForReporting) {
412 return new SimulatedServiceSnapshot(idProvider, netconfOperationServices);
415 public void addService(final NetconfOperationService monitoringService) {
416 netconfOperationServices.add(monitoringService);
419 private static class SimulatedServiceSnapshot implements NetconfOperationServiceSnapshot {
420 private final SessionIdProvider idProvider;
421 private final Set<NetconfOperationService> netconfOperationServices;
423 public SimulatedServiceSnapshot(final SessionIdProvider idProvider, final Set<NetconfOperationService> netconfOperationServices) {
424 this.idProvider = idProvider;
425 this.netconfOperationServices = netconfOperationServices;
429 public String getNetconfSessionIdForReporting() {
430 return String.valueOf(idProvider.getCurrentSessionId());
434 public Set<NetconfOperationService> getServices() {
435 return netconfOperationServices;
439 public void close() throws Exception {}
442 static class SimulatedOperationService implements NetconfOperationService {
443 private final Set<Capability> capabilities;
444 private final long currentSessionId;
445 private final Optional<File> notificationsFile;
447 public SimulatedOperationService(final Set<Capability> capabilities, final long currentSessionId, final Optional<File> notificationsFile) {
448 this.capabilities = capabilities;
449 this.currentSessionId = currentSessionId;
450 this.notificationsFile = notificationsFile;
454 public Set<Capability> getCapabilities() {
459 public Set<NetconfOperation> getNetconfOperations() {
460 final DataList storage = new DataList();
461 final SimulatedGet sGet = new SimulatedGet(String.valueOf(currentSessionId), storage);
462 final SimulatedEditConfig sEditConfig = new SimulatedEditConfig(String.valueOf(currentSessionId), storage);
463 final SimulatedGetConfig sGetConfig = new SimulatedGetConfig(String.valueOf(currentSessionId), storage);
464 final SimulatedCommit sCommit = new SimulatedCommit(String.valueOf(currentSessionId));
465 final SimulatedLock sLock = new SimulatedLock(String.valueOf(currentSessionId));
466 final SimulatedUnLock sUnlock = new SimulatedUnLock(String.valueOf(currentSessionId));
467 final SimulatedCreateSubscription sCreateSubs = new SimulatedCreateSubscription(String.valueOf(currentSessionId), notificationsFile);
468 return Sets.<NetconfOperation>newHashSet(sGet, sGetConfig, sEditConfig, sCommit, sLock, sUnlock, sCreateSubs);
472 public void close() {
478 private class LoggingMonitoringService implements SessionMonitoringService {
480 public void onSessionUp(final NetconfManagementSession session) {
481 LOG.debug("Session {} established", session);
485 public void onSessionDown(final NetconfManagementSession session) {
486 LOG.debug("Session {} down", session);