ca7208953e7c0554c62e54010ee85a2ac1b3ba59
[netconf.git] / netconf / tools / netconf-testtool / src / main / java / org / opendaylight / netconf / test / tool / NetconfDeviceSimulator.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.netconf.test.tool;
9
10 import com.google.common.collect.Collections2;
11 import com.google.common.util.concurrent.Futures;
12 import com.google.common.util.concurrent.ThreadFactoryBuilder;
13 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
14 import io.netty.channel.Channel;
15 import io.netty.channel.ChannelFuture;
16 import io.netty.channel.local.LocalAddress;
17 import io.netty.channel.nio.NioEventLoopGroup;
18 import io.netty.util.HashedWheelTimer;
19 import java.io.Closeable;
20 import java.io.IOException;
21 import java.net.BindException;
22 import java.net.Inet4Address;
23 import java.net.InetSocketAddress;
24 import java.net.UnknownHostException;
25 import java.nio.channels.AsynchronousChannelGroup;
26 import java.util.ArrayList;
27 import java.util.HashSet;
28 import java.util.List;
29 import java.util.Optional;
30 import java.util.Set;
31 import java.util.concurrent.ExecutionException;
32 import java.util.concurrent.ExecutorService;
33 import java.util.concurrent.Executors;
34 import java.util.concurrent.ScheduledExecutorService;
35 import org.opendaylight.netconf.api.capability.BasicCapability;
36 import org.opendaylight.netconf.api.capability.Capability;
37 import org.opendaylight.netconf.api.capability.YangModuleCapability;
38 import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
39 import org.opendaylight.netconf.impl.NetconfServerDispatcherImpl;
40 import org.opendaylight.netconf.impl.NetconfServerSessionNegotiatorFactory;
41 import org.opendaylight.netconf.impl.ServerChannelInitializer;
42 import org.opendaylight.netconf.impl.SessionIdProvider;
43 import org.opendaylight.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
44 import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactory;
45 import org.opendaylight.netconf.shaded.sshd.common.keyprovider.KeyPairProvider;
46 import org.opendaylight.netconf.shaded.sshd.common.util.threads.ThreadUtils;
47 import org.opendaylight.netconf.ssh.SshProxyServer;
48 import org.opendaylight.netconf.ssh.SshProxyServerConfiguration;
49 import org.opendaylight.netconf.ssh.SshProxyServerConfigurationBuilder;
50 import org.opendaylight.netconf.test.tool.config.Configuration;
51 import org.opendaylight.netconf.test.tool.customrpc.SettableOperationProvider;
52 import org.opendaylight.netconf.test.tool.monitoring.NetconfMonitoringOperationService;
53 import org.opendaylight.netconf.test.tool.monitoring.NetconfMonitoringOperationServiceFactory;
54 import org.opendaylight.netconf.test.tool.operations.DefaultOperationsCreator;
55 import org.opendaylight.netconf.test.tool.operations.OperationsProvider;
56 import org.opendaylight.netconf.test.tool.rpchandler.SettableOperationRpcProvider;
57 import org.opendaylight.netconf.test.tool.schemacache.SchemaSourceCache;
58 import org.opendaylight.yangtools.yang.common.Revision;
59 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
60 import org.opendaylight.yangtools.yang.model.api.Module;
61 import org.opendaylight.yangtools.yang.model.api.ModuleLike;
62 import org.opendaylight.yangtools.yang.model.api.Submodule;
63 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
64 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
65 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
66 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
67 import org.opendaylight.yangtools.yang.model.repo.fs.FilesystemSchemaSourceCache;
68 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
69 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
70 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
71 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
72 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToIRTransformer;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
75
76 @SuppressFBWarnings("DM_DEFAULT_ENCODING")
77 public class NetconfDeviceSimulator implements Closeable {
78
79     private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSimulator.class);
80
81     private final NioEventLoopGroup nettyThreadgroup;
82     private final HashedWheelTimer hashedWheelTimer;
83     private final List<Channel> devicesChannels = new ArrayList<>();
84     private final List<SshProxyServer> sshWrappers = new ArrayList<>();
85     private final ScheduledExecutorService minaTimerExecutor;
86     private final ExecutorService nioExecutor;
87     private final Configuration configuration;
88     private EffectiveModelContext schemaContext;
89
90     private boolean sendFakeSchema = false;
91
92     public NetconfDeviceSimulator(final Configuration configuration) {
93         this.configuration = configuration;
94         nettyThreadgroup = new NioEventLoopGroup();
95         hashedWheelTimer = new HashedWheelTimer();
96         minaTimerExecutor = Executors.newScheduledThreadPool(configuration.getThreadPoolSize(),
97                 new ThreadFactoryBuilder().setNameFormat("netconf-ssh-server-mina-timers-%d").build());
98         nioExecutor = ThreadUtils
99                 .newFixedThreadPool("netconf-ssh-server-nio-group", configuration.getThreadPoolSize());
100     }
101
102     private NetconfServerDispatcherImpl createDispatcher(final Set<Capability> capabilities,
103             final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
104
105         final Set<Capability> transformedCapabilities = new HashSet<>(Collections2.transform(capabilities, input -> {
106             if (sendFakeSchema) {
107                 sendFakeSchema = false;
108                 return new FakeCapability((YangModuleCapability) input);
109             } else {
110                 return input;
111             }
112         }));
113         transformedCapabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0"));
114         final NetconfMonitoringService monitoringService1 = new DummyMonitoringService(transformedCapabilities);
115         final SessionIdProvider idProvider = new SessionIdProvider();
116
117         final NetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory = createOperationServiceFactory(
118             sourceProvider, transformedCapabilities, monitoringService1, idProvider);
119
120         final Set<String> serverCapabilities = configuration.getCapabilities();
121
122         final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new TesttoolNegotiationFactory(
123                 hashedWheelTimer, aggregatedNetconfOperationServiceFactory, idProvider,
124                 configuration.getGenerateConfigsTimeout(),
125                 monitoringService1, serverCapabilities);
126
127         final ServerChannelInitializer serverChannelInitializer =
128             new ServerChannelInitializer(serverNegotiatorFactory);
129         return new NetconfServerDispatcherImpl(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
130     }
131
132     private NetconfOperationServiceFactory createOperationServiceFactory(
133             final SchemaSourceProvider<YangTextSchemaSource> sourceProvider,
134             final Set<Capability> transformedCapabilities, final NetconfMonitoringService monitoringService1,
135             final SessionIdProvider idProvider) {
136         final AggregatedNetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory =
137             new AggregatedNetconfOperationServiceFactory();
138
139         final NetconfOperationServiceFactory operationProvider;
140         if (configuration.isMdSal()) {
141             LOG.info("using MdsalOperationProvider.");
142             operationProvider = new MdsalOperationProvider(
143                 idProvider, transformedCapabilities, schemaContext, sourceProvider);
144         } else if (configuration.isXmlConfigurationProvided()) {
145             LOG.info("using SimulatedOperationProvider.");
146             operationProvider = new SimulatedOperationProvider(idProvider, transformedCapabilities,
147                     Optional.ofNullable(configuration.getNotificationFile()),
148                     Optional.ofNullable(configuration.getInitialConfigXMLFile()));
149         } else {
150             LOG.info("using OperationsProvider.");
151             operationProvider = new OperationsProvider(idProvider, transformedCapabilities,
152                 configuration.getOperationsCreator() != null ? configuration.getOperationsCreator()
153                     : DefaultOperationsCreator.getDefaultOperationServiceCreator(idProvider.getCurrentSessionId()));
154         }
155
156
157         final NetconfMonitoringOperationServiceFactory monitoringService =
158                 new NetconfMonitoringOperationServiceFactory(
159                         new NetconfMonitoringOperationService(monitoringService1));
160         aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(operationProvider);
161         aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(monitoringService);
162         if (configuration.getRpcConfigFile() != null) {
163             final SettableOperationProvider settableService =
164                     new SettableOperationProvider(configuration.getRpcConfigFile());
165             aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(settableService);
166         } else {
167             final SettableOperationRpcProvider settableService =
168                     new SettableOperationRpcProvider(configuration.getRpcHandler());
169             aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(settableService);
170         }
171         return aggregatedNetconfOperationServiceFactory;
172     }
173
174     public List<Integer> start() {
175         final var proto = configuration.isSsh() ? "SSH" : "TCP";
176         LOG.info("Starting {}, {} simulated devices starting on port {}",
177                 configuration.getDeviceCount(), proto, configuration.getStartingPort());
178
179         final SharedSchemaRepository schemaRepo = new SharedSchemaRepository("netconf-simulator");
180         final Set<Capability> capabilities = parseSchemasToModuleCapabilities(schemaRepo);
181
182         final NetconfServerDispatcherImpl dispatcher = createDispatcher(capabilities,
183             sourceIdentifier -> schemaRepo.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class));
184
185         int currentPort = configuration.getStartingPort();
186
187         final List<Integer> openDevices = new ArrayList<>();
188
189         // Generate key to temp folder
190         final KeyPairProvider keyPairProvider = new VirtualKeyPairProvider();
191
192         final AsynchronousChannelGroup group;
193         try {
194             group = AsynchronousChannelGroup.withThreadPool(nioExecutor);
195         } catch (final IOException e) {
196             throw new IllegalStateException("Failed to create group", e);
197         }
198
199         for (int i = 0; i < configuration.getDeviceCount(); i++) {
200             if (currentPort > 65535) {
201                 LOG.warn("Port cannot be greater than 65535, stopping further attempts.");
202                 break;
203             }
204             final InetSocketAddress address = getAddress(configuration.getIp(), currentPort);
205
206             final ChannelFuture server;
207             if (configuration.isSsh()) {
208                 final InetSocketAddress bindingAddress = InetSocketAddress.createUnresolved("0.0.0.0", currentPort);
209                 final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());
210
211                 server = dispatcher.createLocalServer(tcpLocalAddress);
212                 try {
213                     final SshProxyServer sshServer = new SshProxyServer(
214                         minaTimerExecutor, nettyThreadgroup, group);
215                     sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress, keyPairProvider));
216                     sshWrappers.add(sshServer);
217                 } catch (final BindException e) {
218                     LOG.warn("Cannot start simulated device on {}, port already in use. Skipping.", address);
219                     // Close local server and continue
220                     server.cancel(true);
221                     if (server.isDone()) {
222                         server.channel().close();
223                     }
224                     continue;
225                 } catch (final IOException e) {
226                     LOG.warn("Cannot start simulated device on {} due to IOException.", address, e);
227                     break;
228                 } finally {
229                     currentPort++;
230                 }
231
232                 try {
233                     server.get();
234                 } catch (final InterruptedException e) {
235                     throw new RuntimeException(e);
236                 } catch (final ExecutionException e) {
237                     LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
238                     continue;
239                 }
240
241                 LOG.debug("Simulated SSH device started on {}", address);
242
243             } else {
244                 server = dispatcher.createServer(address);
245                 currentPort++;
246
247                 try {
248                     server.get();
249                 } catch (final InterruptedException e) {
250                     throw new RuntimeException(e);
251                 } catch (final ExecutionException e) {
252                     LOG.warn("Cannot start tcp simulated device on {}, skipping", address, e);
253                     continue;
254                 }
255
256                 LOG.debug("Simulated TCP device started on {}", server.channel().localAddress());
257             }
258
259             devicesChannels.add(server.channel());
260             openDevices.add(currentPort - 1);
261         }
262
263         if (openDevices.size() == configuration.getDeviceCount()) {
264             LOG.info("All simulated devices started successfully from port {} to {}",
265                     configuration.getStartingPort(), currentPort - 1);
266         } else if (openDevices.size() == 0) {
267             LOG.warn("No simulated devices started.");
268         } else {
269             LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
270         }
271
272         return openDevices;
273     }
274
275     private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress,
276             final LocalAddress tcpLocalAddress, final KeyPairProvider keyPairProvider) {
277         return new SshProxyServerConfigurationBuilder()
278                 .setBindingAddress(bindingAddress)
279                 .setLocalAddress(tcpLocalAddress)
280                 .setAuthenticator(configuration.getAuthProvider())
281                 .setPublickeyAuthenticator(configuration.getPublickeyAuthenticator())
282                 .setKeyPairProvider(keyPairProvider)
283                 .setIdleTimeout(Integer.MAX_VALUE)
284                 .createSshProxyServerConfiguration();
285     }
286
287     private Set<Capability> parseSchemasToModuleCapabilities(final SharedSchemaRepository consumer) {
288         final Set<SourceIdentifier> loadedSources = new HashSet<>();
289         consumer.registerSchemaSourceListener(TextToIRTransformer.create(consumer, consumer));
290         consumer.registerSchemaSourceListener(new SchemaSourceListener() {
291             @Override
292             public void schemaSourceEncountered(final SchemaSourceRepresentation schemaSourceRepresentation) {
293
294             }
295
296             @Override
297             public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> potentialSchemaSources) {
298                 for (final PotentialSchemaSource<?> potentialSchemaSource : potentialSchemaSources) {
299                     loadedSources.add(potentialSchemaSource.getSourceIdentifier());
300                 }
301             }
302
303             @Override
304             public void schemaSourceUnregistered(final PotentialSchemaSource<?> potentialSchemaSource) {
305
306             }
307         });
308
309         if (configuration.getSchemasDir() != null) {
310             LOG.info("Loading models from directory.");
311             final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(
312                 consumer, YangTextSchemaSource.class, configuration.getSchemasDir());
313             consumer.registerSchemaSourceListener(cache);
314         } else if (configuration.getModels() != null) {
315             LOG.info("Loading models from classpath.");
316             final SchemaSourceCache<YangTextSchemaSource> cache = new SchemaSourceCache<>(
317                     consumer, YangTextSchemaSource.class, configuration.getModels());
318             consumer.registerSchemaSourceListener(cache);
319         } else {
320             LOG.info("Custom module loading skipped.");
321         }
322
323         configuration.getDefaultYangResources().forEach(r -> {
324             final SourceIdentifier sourceIdentifier = RevisionSourceIdentifier.create(r.getModuleName(),
325                 Revision.ofNullable(r.getRevision()));
326             registerSource(consumer, r.getResourcePath(), sourceIdentifier);
327         });
328
329         try {
330             //necessary for creating mdsal data stores and operations
331             schemaContext = consumer.createEffectiveModelContextFactory()
332                     .createEffectiveModelContext(loadedSources).get();
333         } catch (final InterruptedException | ExecutionException e) {
334             throw new RuntimeException("Cannot parse schema context. "
335                     + "Please read stack trace and check YANG files in schema directory.", e);
336         }
337
338         final Set<Capability> capabilities = new HashSet<>();
339
340         for (final Module module : schemaContext.getModules()) {
341             for (final Submodule subModule : module.getSubmodules()) {
342                 addModuleCapability(consumer, capabilities, subModule);
343             }
344             addModuleCapability(consumer, capabilities, module);
345         }
346         return capabilities;
347     }
348
349     private static void addModuleCapability(final SharedSchemaRepository consumer, final Set<Capability> capabilities,
350                                             final ModuleLike module) {
351         final SourceIdentifier moduleSourceIdentifier = RevisionSourceIdentifier.create(module.getName(),
352             module.getRevision());
353         try {
354             final String moduleContent = new String(
355                 consumer.getSchemaSource(moduleSourceIdentifier, YangTextSchemaSource.class).get().read());
356             capabilities.add(new YangModuleCapability(module, moduleContent));
357             //IOException would be thrown in creating SchemaContext already
358         } catch (final ExecutionException | InterruptedException | IOException e) {
359             throw new RuntimeException("Cannot retrieve schema source for module "
360                 + moduleSourceIdentifier.toString() + " from schema repository", e);
361         }
362     }
363
364     private static void registerSource(final SharedSchemaRepository consumer, final String resource,
365             final SourceIdentifier sourceId) {
366         consumer.registerSchemaSource(sourceIdentifier -> Futures.immediateFuture(
367             YangTextSchemaSource.forResource(NetconfDeviceSimulator.class, resource)),
368             PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class,
369                 PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
370     }
371
372     private static InetSocketAddress getAddress(final String ip, final int port) {
373         try {
374             return new InetSocketAddress(Inet4Address.getByName(ip), port);
375         } catch (final UnknownHostException e) {
376             throw new RuntimeException(e);
377         }
378     }
379
380     @Override
381     public void close() {
382         for (final SshProxyServer sshWrapper : sshWrappers) {
383             try {
384                 sshWrapper.close();
385             } catch (final IOException e) {
386                 LOG.debug("Wrapper {} failed to close", sshWrapper, e);
387             }
388         }
389         for (final Channel deviceCh : devicesChannels) {
390             deviceCh.close();
391         }
392         nettyThreadgroup.shutdownGracefully();
393         minaTimerExecutor.shutdownNow();
394         nioExecutor.shutdownNow();
395     }
396
397 }