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;
26 import java.io.IOException;
27 import java.io.InputStream;
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.impl.DefaultCommitNotificationProducer;
46 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
47 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
48 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
49 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
50 import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
51 import org.opendaylight.controller.netconf.mapping.api.Capability;
52 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
53 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
54 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
55 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceSnapshot;
56 import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringOperationService;
57 import org.opendaylight.controller.netconf.ssh.NetconfSSHServer;
58 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
59 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
60 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
61 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
62 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
63 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
64 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
65 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
66 import org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils;
67 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
68 import org.opendaylight.yangtools.yang.parser.impl.YangParserListenerImpl;
69 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
70 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
71 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
75 public class NetconfDeviceSimulator implements Closeable {
77 private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSimulator.class);
79 public static final int CONNECTION_TIMEOUT_MILLIS = 20000;
81 private final NioEventLoopGroup nettyThreadgroup;
82 private final HashedWheelTimer hashedWheelTimer;
83 private final List<Channel> devicesChannels = Lists.newArrayList();
85 public NetconfDeviceSimulator() {
86 this(new NioEventLoopGroup(), new HashedWheelTimer());
89 public NetconfDeviceSimulator(final NioEventLoopGroup eventExecutors, final HashedWheelTimer hashedWheelTimer) {
90 this.nettyThreadgroup = eventExecutors;
91 this.hashedWheelTimer = hashedWheelTimer;
94 private NetconfServerDispatcher createDispatcher(final Map<ModuleBuilder, String> moduleBuilders) {
96 final Set<Capability> capabilities = Sets.newHashSet(Collections2.transform(moduleBuilders.keySet(), new Function<ModuleBuilder, Capability>() {
98 public Capability apply(final ModuleBuilder input) {
99 return new ModuleBuilderCapability(input, moduleBuilders.get(input));
103 final SessionIdProvider idProvider = new SessionIdProvider();
105 final SimulatedOperationProvider simulatedOperationProvider = new SimulatedOperationProvider(idProvider, capabilities);
106 final NetconfMonitoringOperationService monitoringService = new NetconfMonitoringOperationService(new NetconfMonitoringServiceImpl(simulatedOperationProvider));
107 simulatedOperationProvider.addService(monitoringService);
109 final DefaultCommitNotificationProducer commitNotifier = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
111 final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
112 hashedWheelTimer, simulatedOperationProvider, idProvider, CONNECTION_TIMEOUT_MILLIS, commitNotifier, new LoggingMonitoringService());
114 final NetconfServerDispatcher.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerChannelInitializer(
115 serverNegotiatorFactory);
116 return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
119 private Map<ModuleBuilder, String> toModuleBuilders(final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> sources) {
120 final Map<SourceIdentifier, ParserRuleContext> asts = Maps.transformValues(sources, new Function<Map.Entry<ASTSchemaSource, YangTextSchemaSource>, ParserRuleContext>() {
122 public ParserRuleContext apply(final Map.Entry<ASTSchemaSource, YangTextSchemaSource> input) {
123 return input.getKey().getAST();
126 final Map<String, TreeMap<Date, URI>> namespaceContext = BuilderUtils.createYangNamespaceContext(
127 asts.values(), Optional.<SchemaContext>absent());
129 final ParseTreeWalker walker = new ParseTreeWalker();
130 final Map<ModuleBuilder, String> sourceToBuilder = new HashMap<>();
132 for (final Map.Entry<SourceIdentifier, ParserRuleContext> entry : asts.entrySet()) {
133 final ModuleBuilder moduleBuilder = YangParserListenerImpl.create(namespaceContext, entry.getKey().getName(),
134 walker, entry.getValue()).getModuleBuilder();
136 try(InputStreamReader stream = new InputStreamReader(sources.get(entry.getKey()).getValue().openStream(), Charsets.UTF_8)) {
137 sourceToBuilder.put(moduleBuilder, CharStreams.toString(stream));
138 } catch (final IOException e) {
139 throw new RuntimeException(e);
143 return sourceToBuilder;
147 public List<Integer> start(final Main.Params params) {
148 final Map<ModuleBuilder, String> moduleBuilders = parseSchemasToModuleBuilders(params);
150 final NetconfServerDispatcher dispatcher = createDispatcher(moduleBuilders);
152 int currentPort = params.startingPort;
154 final List<Integer> openDevices = Lists.newArrayList();
155 for (int i = 0; i < params.deviceCount; i++) {
156 final InetSocketAddress address = getAddress(currentPort);
158 final ChannelFuture server;
160 final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());
162 server = dispatcher.createLocalServer(tcpLocalAddress);
164 NetconfSSHServer.start(currentPort, tcpLocalAddress, new AcceptingAuthProvider(), nettyThreadgroup);
165 } catch (final Exception e) {
166 LOG.warn("Cannot start simulated device on {}, skipping", address, e);
167 // Close local server and continue
169 if(server.isDone()) {
170 server.channel().close();
179 } catch (final InterruptedException e) {
180 throw new RuntimeException(e);
181 } catch (final ExecutionException e) {
182 LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
186 LOG.debug("Simulated SSH device started on {}", address);
189 server = dispatcher.createServer(address);
194 } catch (final InterruptedException e) {
195 throw new RuntimeException(e);
196 } catch (final ExecutionException e) {
197 LOG.warn("Cannot start tcp simulated device on {}, skipping", address, e);
201 LOG.debug("Simulated TCP device started on {}", address);
204 devicesChannels.add(server.channel());
205 openDevices.add(currentPort - 1);
209 if(openDevices.size() == params.deviceCount) {
210 LOG.info("All simulated devices started successfully from port {} to {}", params.startingPort, currentPort);
212 LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
218 private Map<ModuleBuilder, String> parseSchemasToModuleBuilders(final Main.Params params) {
219 final SharedSchemaRepository consumer = new SharedSchemaRepository("netconf-simulator");
220 consumer.registerSchemaSourceListener(TextToASTTransformer.create(consumer, consumer));
222 final Set<SourceIdentifier> loadedSources = Sets.newHashSet();
224 consumer.registerSchemaSourceListener(new SchemaSourceListener() {
226 public void schemaSourceEncountered(final SchemaSourceRepresentation schemaSourceRepresentation) {}
229 public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> potentialSchemaSources) {
230 for (final PotentialSchemaSource<?> potentialSchemaSource : potentialSchemaSources) {
231 loadedSources.add(potentialSchemaSource.getSourceIdentifier());
236 public void schemaSourceUnregistered(final PotentialSchemaSource<?> potentialSchemaSource) {}
239 final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(consumer, YangTextSchemaSource.class, params.schemasDir);
240 consumer.registerSchemaSourceListener(cache);
242 final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> asts = Maps.newHashMap();
243 for (final SourceIdentifier loadedSource : loadedSources) {
245 final CheckedFuture<ASTSchemaSource, SchemaSourceException> ast = consumer.getSchemaSource(loadedSource, ASTSchemaSource.class);
246 final CheckedFuture<YangTextSchemaSource, SchemaSourceException> text = consumer.getSchemaSource(loadedSource, YangTextSchemaSource.class);
247 asts.put(loadedSource, new AbstractMap.SimpleEntry<>(ast.get(), text.get()));
248 } catch (final InterruptedException e) {
249 throw new RuntimeException(e);
250 } catch (final ExecutionException e) {
251 throw new RuntimeException("Cannot parse schema context", e);
254 return toModuleBuilders(asts);
257 private static InetSocketAddress getAddress(final int port) {
259 // TODO make address configurable
260 return new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), port);
261 } catch (final UnknownHostException e) {
262 throw new RuntimeException(e);
267 public void close() {
268 for (final Channel deviceCh : devicesChannels) {
271 nettyThreadgroup.shutdownGracefully();
275 private static class SimulatedOperationProvider implements NetconfOperationProvider {
276 private final SessionIdProvider idProvider;
277 private final Set<NetconfOperationService> netconfOperationServices;
280 public SimulatedOperationProvider(final SessionIdProvider idProvider, final Set<Capability> caps) {
281 this.idProvider = idProvider;
282 final SimulatedOperationService simulatedOperationService = new SimulatedOperationService(caps, idProvider.getCurrentSessionId());
283 this.netconfOperationServices = Sets.<NetconfOperationService>newHashSet(simulatedOperationService);
287 public NetconfOperationServiceSnapshot openSnapshot(final String sessionIdForReporting) {
288 return new SimulatedServiceSnapshot(idProvider, netconfOperationServices);
291 public void addService(final NetconfOperationService monitoringService) {
292 netconfOperationServices.add(monitoringService);
295 private static class SimulatedServiceSnapshot implements NetconfOperationServiceSnapshot {
296 private final SessionIdProvider idProvider;
297 private final Set<NetconfOperationService> netconfOperationServices;
299 public SimulatedServiceSnapshot(final SessionIdProvider idProvider, final Set<NetconfOperationService> netconfOperationServices) {
300 this.idProvider = idProvider;
301 this.netconfOperationServices = netconfOperationServices;
305 public String getNetconfSessionIdForReporting() {
306 return String.valueOf(idProvider.getCurrentSessionId());
310 public Set<NetconfOperationService> getServices() {
311 return netconfOperationServices;
315 public void close() throws Exception {}
318 static class SimulatedOperationService implements NetconfOperationService {
319 private final Set<Capability> capabilities;
320 private static SimulatedGet sGet;
322 public SimulatedOperationService(final Set<Capability> capabilities, final long currentSessionId) {
323 this.capabilities = capabilities;
324 sGet = new SimulatedGet(String.valueOf(currentSessionId));
328 public Set<Capability> getCapabilities() {
333 public Set<NetconfOperation> getNetconfOperations() {
334 return Sets.<NetconfOperation>newHashSet(sGet);
338 public void close() {
344 private class LoggingMonitoringService implements SessionMonitoringService {
346 public void onSessionUp(final NetconfManagementSession session) {
347 LOG.debug("Session {} established", session);
351 public void onSessionDown(final NetconfManagementSession session) {
352 LOG.debug("Session {} down", session);