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.Optional;
14 import com.google.common.collect.Collections2;
15 import com.google.common.collect.Lists;
16 import com.google.common.collect.Maps;
17 import com.google.common.collect.Sets;
18 import com.google.common.io.CharStreams;
19 import com.google.common.util.concurrent.CheckedFuture;
20 import io.netty.channel.Channel;
21 import io.netty.channel.ChannelFuture;
22 import io.netty.channel.local.LocalAddress;
23 import io.netty.channel.nio.NioEventLoopGroup;
24 import io.netty.util.HashedWheelTimer;
25 import java.io.Closeable;
27 import java.io.IOException;
28 import java.io.InputStreamReader;
29 import java.lang.management.ManagementFactory;
30 import java.net.Inet4Address;
31 import java.net.InetSocketAddress;
33 import java.net.UnknownHostException;
34 import java.util.AbstractMap;
35 import java.util.Date;
36 import java.util.HashMap;
37 import java.util.List;
40 import java.util.TreeMap;
41 import java.util.concurrent.ExecutionException;
42 import org.antlr.v4.runtime.ParserRuleContext;
43 import org.antlr.v4.runtime.tree.ParseTreeWalker;
44 import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession;
45 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
46 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
47 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
48 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
49 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
50 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
51 import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
52 import org.opendaylight.controller.netconf.mapping.api.Capability;
53 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
54 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
55 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
56 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceSnapshot;
57 import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringOperationService;
58 import org.opendaylight.controller.netconf.ssh.NetconfSSHServer;
59 import org.opendaylight.controller.netconf.ssh.authentication.PEMGenerator;
60 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
61 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
62 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
63 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
64 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
65 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
66 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
67 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
68 import org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils;
69 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
70 import org.opendaylight.yangtools.yang.parser.impl.YangParserListenerImpl;
71 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
72 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
73 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
77 public class NetconfDeviceSimulator implements Closeable {
79 private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSimulator.class);
81 public static final int CONNECTION_TIMEOUT_MILLIS = 20000;
83 private final NioEventLoopGroup nettyThreadgroup;
84 private final HashedWheelTimer hashedWheelTimer;
85 private final List<Channel> devicesChannels = Lists.newArrayList();
87 public NetconfDeviceSimulator() {
88 this(new NioEventLoopGroup(), new HashedWheelTimer());
91 public NetconfDeviceSimulator(final NioEventLoopGroup eventExecutors, final HashedWheelTimer hashedWheelTimer) {
92 this.nettyThreadgroup = eventExecutors;
93 this.hashedWheelTimer = hashedWheelTimer;
96 private NetconfServerDispatcher createDispatcher(final Map<ModuleBuilder, String> moduleBuilders, final boolean exi) {
98 final Set<Capability> capabilities = Sets.newHashSet(Collections2.transform(moduleBuilders.keySet(), new Function<ModuleBuilder, Capability>() {
100 public Capability apply(final ModuleBuilder input) {
101 return new ModuleBuilderCapability(input, moduleBuilders.get(input));
105 final SessionIdProvider idProvider = new SessionIdProvider();
107 final SimulatedOperationProvider simulatedOperationProvider = new SimulatedOperationProvider(idProvider, capabilities);
108 final NetconfMonitoringOperationService monitoringService = new NetconfMonitoringOperationService(new NetconfMonitoringServiceImpl(simulatedOperationProvider));
109 simulatedOperationProvider.addService(monitoringService);
111 final DefaultCommitNotificationProducer commitNotifier = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
113 final Set<String> serverCapabilities = exi
114 ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES
115 : Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0, XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
117 final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
118 hashedWheelTimer, simulatedOperationProvider, idProvider, CONNECTION_TIMEOUT_MILLIS, commitNotifier, new LoggingMonitoringService(), serverCapabilities);
120 final NetconfServerDispatcher.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerChannelInitializer(
121 serverNegotiatorFactory);
122 return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
125 private Map<ModuleBuilder, String> toModuleBuilders(final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> sources) {
126 final Map<SourceIdentifier, ParserRuleContext> asts = Maps.transformValues(sources, new Function<Map.Entry<ASTSchemaSource, YangTextSchemaSource>, ParserRuleContext>() {
128 public ParserRuleContext apply(final Map.Entry<ASTSchemaSource, YangTextSchemaSource> input) {
129 return input.getKey().getAST();
132 final Map<String, TreeMap<Date, URI>> namespaceContext = BuilderUtils.createYangNamespaceContext(
133 asts.values(), Optional.<SchemaContext>absent());
135 final ParseTreeWalker walker = new ParseTreeWalker();
136 final Map<ModuleBuilder, String> sourceToBuilder = new HashMap<>();
138 for (final Map.Entry<SourceIdentifier, ParserRuleContext> entry : asts.entrySet()) {
139 final ModuleBuilder moduleBuilder = YangParserListenerImpl.create(namespaceContext, entry.getKey().getName(),
140 walker, entry.getValue()).getModuleBuilder();
142 try(InputStreamReader stream = new InputStreamReader(sources.get(entry.getKey()).getValue().openStream(), Charsets.UTF_8)) {
143 sourceToBuilder.put(moduleBuilder, CharStreams.toString(stream));
144 } catch (final IOException e) {
145 throw new RuntimeException(e);
149 return sourceToBuilder;
153 public List<Integer> start(final Main.Params params) {
154 final Map<ModuleBuilder, String> moduleBuilders = parseSchemasToModuleBuilders(params);
156 final NetconfServerDispatcher dispatcher = createDispatcher(moduleBuilders, params.exi);
158 int currentPort = params.startingPort;
160 final List<Integer> openDevices = Lists.newArrayList();
161 for (int i = 0; i < params.deviceCount; i++) {
162 final InetSocketAddress address = getAddress(currentPort);
164 final ChannelFuture server;
166 final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());
168 server = dispatcher.createLocalServer(tcpLocalAddress);
170 final NetconfSSHServer sshServer = NetconfSSHServer.start(currentPort, tcpLocalAddress, nettyThreadgroup, getPemArray());
171 sshServer.setAuthProvider(new AcceptingAuthProvider());
172 } catch (final Exception e) {
173 LOG.warn("Cannot start simulated device on {}, skipping", address, e);
174 // Close local server and continue
176 if(server.isDone()) {
177 server.channel().close();
186 } catch (final InterruptedException e) {
187 throw new RuntimeException(e);
188 } catch (final ExecutionException e) {
189 LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
193 LOG.debug("Simulated SSH device started on {}", address);
196 server = dispatcher.createServer(address);
201 } catch (final InterruptedException e) {
202 throw new RuntimeException(e);
203 } catch (final ExecutionException e) {
204 LOG.warn("Cannot start tcp simulated device on {}, skipping", address, e);
208 LOG.debug("Simulated TCP device started on {}", address);
211 devicesChannels.add(server.channel());
212 openDevices.add(currentPort - 1);
216 if(openDevices.size() == params.deviceCount) {
217 LOG.info("All simulated devices started successfully from port {} to {}", params.startingPort, currentPort);
219 LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
225 private char[] getPemArray() {
227 return PEMGenerator.readOrGeneratePK(new File("PK")).toCharArray();
228 } catch (final IOException e) {
229 throw new RuntimeException(e);
233 private Map<ModuleBuilder, String> parseSchemasToModuleBuilders(final Main.Params params) {
234 final SharedSchemaRepository consumer = new SharedSchemaRepository("netconf-simulator");
235 consumer.registerSchemaSourceListener(TextToASTTransformer.create(consumer, consumer));
237 final Set<SourceIdentifier> loadedSources = Sets.newHashSet();
239 consumer.registerSchemaSourceListener(new SchemaSourceListener() {
241 public void schemaSourceEncountered(final SchemaSourceRepresentation schemaSourceRepresentation) {}
244 public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> potentialSchemaSources) {
245 for (final PotentialSchemaSource<?> potentialSchemaSource : potentialSchemaSources) {
246 loadedSources.add(potentialSchemaSource.getSourceIdentifier());
251 public void schemaSourceUnregistered(final PotentialSchemaSource<?> potentialSchemaSource) {}
254 final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(consumer, YangTextSchemaSource.class, params.schemasDir);
255 consumer.registerSchemaSourceListener(cache);
257 final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> asts = Maps.newHashMap();
258 for (final SourceIdentifier loadedSource : loadedSources) {
260 final CheckedFuture<ASTSchemaSource, SchemaSourceException> ast = consumer.getSchemaSource(loadedSource, ASTSchemaSource.class);
261 final CheckedFuture<YangTextSchemaSource, SchemaSourceException> text = consumer.getSchemaSource(loadedSource, YangTextSchemaSource.class);
262 asts.put(loadedSource, new AbstractMap.SimpleEntry<>(ast.get(), text.get()));
263 } catch (final InterruptedException e) {
264 throw new RuntimeException(e);
265 } catch (final ExecutionException e) {
266 throw new RuntimeException("Cannot parse schema context", e);
269 return toModuleBuilders(asts);
272 private static InetSocketAddress getAddress(final int port) {
274 // TODO make address configurable
275 return new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), port);
276 } catch (final UnknownHostException e) {
277 throw new RuntimeException(e);
282 public void close() {
283 for (final Channel deviceCh : devicesChannels) {
286 nettyThreadgroup.shutdownGracefully();
290 private static class SimulatedOperationProvider implements NetconfOperationProvider {
291 private final SessionIdProvider idProvider;
292 private final Set<NetconfOperationService> netconfOperationServices;
295 public SimulatedOperationProvider(final SessionIdProvider idProvider, final Set<Capability> caps) {
296 this.idProvider = idProvider;
297 final SimulatedOperationService simulatedOperationService = new SimulatedOperationService(caps, idProvider.getCurrentSessionId());
298 this.netconfOperationServices = Sets.<NetconfOperationService>newHashSet(simulatedOperationService);
302 public NetconfOperationServiceSnapshot openSnapshot(final String sessionIdForReporting) {
303 return new SimulatedServiceSnapshot(idProvider, netconfOperationServices);
306 public void addService(final NetconfOperationService monitoringService) {
307 netconfOperationServices.add(monitoringService);
310 private static class SimulatedServiceSnapshot implements NetconfOperationServiceSnapshot {
311 private final SessionIdProvider idProvider;
312 private final Set<NetconfOperationService> netconfOperationServices;
314 public SimulatedServiceSnapshot(final SessionIdProvider idProvider, final Set<NetconfOperationService> netconfOperationServices) {
315 this.idProvider = idProvider;
316 this.netconfOperationServices = netconfOperationServices;
320 public String getNetconfSessionIdForReporting() {
321 return String.valueOf(idProvider.getCurrentSessionId());
325 public Set<NetconfOperationService> getServices() {
326 return netconfOperationServices;
330 public void close() throws Exception {}
333 static class SimulatedOperationService implements NetconfOperationService {
334 private final Set<Capability> capabilities;
335 private static SimulatedGet sGet;
337 public SimulatedOperationService(final Set<Capability> capabilities, final long currentSessionId) {
338 this.capabilities = capabilities;
339 sGet = new SimulatedGet(String.valueOf(currentSessionId));
343 public Set<Capability> getCapabilities() {
348 public Set<NetconfOperation> getNetconfOperations() {
349 return Sets.<NetconfOperation>newHashSet(sGet);
353 public void close() {
359 private class LoggingMonitoringService implements SessionMonitoringService {
361 public void onSessionUp(final NetconfManagementSession session) {
362 LOG.debug("Session {} established", session);
366 public void onSessionDown(final NetconfManagementSession session) {
367 LOG.debug("Session {} down", session);