Merge "Bug 6895 - Implement Query parameters - depth"
[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
9 package org.opendaylight.netconf.test.tool;
10
11 import com.google.common.base.Function;
12 import com.google.common.base.MoreObjects;
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.Sets;
17 import com.google.common.util.concurrent.CheckedFuture;
18 import com.google.common.util.concurrent.Futures;
19 import com.google.common.util.concurrent.ThreadFactoryBuilder;
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.net.BindException;
29 import java.net.Inet4Address;
30 import java.net.InetSocketAddress;
31 import java.net.UnknownHostException;
32 import java.nio.file.Files;
33 import java.nio.file.Path;
34 import java.util.List;
35 import java.util.Set;
36 import java.util.concurrent.ExecutionException;
37 import java.util.concurrent.ExecutorService;
38 import java.util.concurrent.Executors;
39 import java.util.concurrent.ScheduledExecutorService;
40 import org.apache.sshd.common.util.ThreadUtils;
41 import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
42 import org.opendaylight.controller.config.util.capability.BasicCapability;
43 import org.opendaylight.controller.config.util.capability.Capability;
44 import org.opendaylight.controller.config.util.capability.YangModuleCapability;
45 import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
46 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
47 import org.opendaylight.netconf.auth.AuthProvider;
48 import org.opendaylight.netconf.impl.NetconfServerDispatcherImpl;
49 import org.opendaylight.netconf.impl.NetconfServerSessionNegotiatorFactory;
50 import org.opendaylight.netconf.impl.SessionIdProvider;
51 import org.opendaylight.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
52 import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactory;
53 import org.opendaylight.netconf.monitoring.osgi.NetconfMonitoringActivator;
54 import org.opendaylight.netconf.monitoring.osgi.NetconfMonitoringOperationService;
55 import org.opendaylight.netconf.ssh.SshProxyServer;
56 import org.opendaylight.netconf.ssh.SshProxyServerConfiguration;
57 import org.opendaylight.netconf.ssh.SshProxyServerConfigurationBuilder;
58 import org.opendaylight.netconf.test.tool.customrpc.SettableOperationProvider;
59 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
60 import org.opendaylight.yangtools.yang.model.api.Module;
61 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
62 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
63 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
64 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
65 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
66 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
67 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
68 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
69 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
70 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
71 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
72 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
73 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
74 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
77
78 public class NetconfDeviceSimulator implements Closeable {
79
80     private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSimulator.class);
81
82     private final NioEventLoopGroup nettyThreadgroup;
83     private final HashedWheelTimer hashedWheelTimer;
84     private final List<Channel> devicesChannels = Lists.newArrayList();
85     private final List<SshProxyServer> sshWrappers = Lists.newArrayList();
86     private final ScheduledExecutorService minaTimerExecutor;
87     private final ExecutorService nioExecutor;
88     private SchemaContext schemaContext;
89
90     private boolean sendFakeSchema = false;
91
92     public NetconfDeviceSimulator(final int ThreadPoolSize) {
93         this(new NioEventLoopGroup(), new HashedWheelTimer(),
94                 Executors.newScheduledThreadPool(ThreadPoolSize, new ThreadFactoryBuilder().setNameFormat("netconf-ssh-server-mina-timers-%d").build()),
95                 ThreadUtils.newFixedThreadPool("netconf-ssh-server-nio-group", ThreadPoolSize));
96     }
97
98     private NetconfDeviceSimulator(final NioEventLoopGroup eventExecutors, final HashedWheelTimer hashedWheelTimer, final ScheduledExecutorService minaTimerExecutor, final ExecutorService nioExecutor) {
99         this.nettyThreadgroup = eventExecutors;
100         this.hashedWheelTimer = hashedWheelTimer;
101         this.minaTimerExecutor = minaTimerExecutor;
102         this.nioExecutor = nioExecutor;
103     }
104
105     private NetconfServerDispatcherImpl createDispatcher(final Set<Capability> capabilities,
106                                                          final SchemaSourceProvider<YangTextSchemaSource> sourceProvider,
107                                                          final TesttoolParameters params) {
108
109         final Set<Capability> transformedCapabilities = Sets.newHashSet(Collections2.transform(capabilities, new Function<Capability, Capability>() {
110             @Override
111             public Capability apply(final Capability input) {
112                 if (sendFakeSchema) {
113                     sendFakeSchema = false;
114                     return new FakeCapability((YangModuleCapability) input);
115                 } else {
116                     return input;
117                 }
118             }
119         }));
120         transformedCapabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0"));
121         final NetconfMonitoringService monitoringService1 = new DummyMonitoringService(transformedCapabilities);
122         final SessionIdProvider idProvider = new SessionIdProvider();
123
124         final NetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory = createOperationServiceFactory(sourceProvider, params, transformedCapabilities, monitoringService1, idProvider);
125
126         final Set<String> serverCapabilities = params.exi
127                 ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES
128                 : Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0, XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
129
130         final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new TesttoolNegotiationFactory(
131                 hashedWheelTimer, aggregatedNetconfOperationServiceFactory, idProvider, params.generateConfigsTimeout, monitoringService1, serverCapabilities);
132
133         final NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(
134                 serverNegotiatorFactory);
135         return new NetconfServerDispatcherImpl(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
136     }
137
138     private NetconfOperationServiceFactory createOperationServiceFactory(final SchemaSourceProvider<YangTextSchemaSource> sourceProvider,
139                                                                          final TesttoolParameters params,
140                                                                          final Set<Capability> transformedCapabilities,
141                                                                          final NetconfMonitoringService monitoringService1,
142                                                                          final SessionIdProvider idProvider) {
143         final AggregatedNetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory = new AggregatedNetconfOperationServiceFactory();
144
145         final NetconfOperationServiceFactory operationProvider;
146         if (params.mdSal) {
147             operationProvider = new MdsalOperationProvider(idProvider, transformedCapabilities, schemaContext, sourceProvider);
148         } else {
149             operationProvider = new SimulatedOperationProvider(idProvider, transformedCapabilities,
150                     Optional.fromNullable(params.notificationFile),
151                     Optional.fromNullable(params.initialConfigXMLFile));
152         }
153
154
155         final NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory monitoringService =
156                 new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(
157                         new NetconfMonitoringOperationService(monitoringService1));
158         aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(operationProvider);
159         aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(monitoringService);
160         if (params.rpcConfig != null) {
161             final SettableOperationProvider settableService = new SettableOperationProvider(params.rpcConfig);
162             aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(settableService);
163         }
164         return aggregatedNetconfOperationServiceFactory;
165     }
166
167     public List<Integer> start(final TesttoolParameters params) {
168         LOG.info("Starting {}, {} simulated devices starting on port {}", params.deviceCount, params.ssh ? "SSH" : "TCP", params.startingPort);
169
170         final SharedSchemaRepository schemaRepo = new SharedSchemaRepository("netconf-simulator");
171         final Set<Capability> capabilities = parseSchemasToModuleCapabilities(params, schemaRepo);
172
173         final NetconfServerDispatcherImpl dispatcher = createDispatcher(capabilities,
174                 new SchemaSourceProvider<YangTextSchemaSource>() {
175                     @Override
176                     public CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
177                         return schemaRepo.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class);
178                     }
179                 }, params);
180
181         int currentPort = params.startingPort;
182
183         final List<Integer> openDevices = Lists.newArrayList();
184
185         // Generate key to temp folder
186         final PEMGeneratorHostKeyProvider keyPairProvider = getPemGeneratorHostKeyProvider();
187
188         for (int i = 0; i < params.deviceCount; i++) {
189             if (currentPort > 65535) {
190                 LOG.warn("Port cannot be greater than 65535, stopping further attempts.");
191                 break;
192             }
193             final InetSocketAddress address = getAddress(params.ip, currentPort);
194
195             final ChannelFuture server;
196             if(params.ssh) {
197                 final InetSocketAddress bindingAddress = InetSocketAddress.createUnresolved("0.0.0.0", currentPort);
198                 final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());
199
200                 server = dispatcher.createLocalServer(tcpLocalAddress);
201                 try {
202                     final SshProxyServer sshServer = new SshProxyServer(minaTimerExecutor, nettyThreadgroup, nioExecutor);
203                     sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress, keyPairProvider));
204                     sshWrappers.add(sshServer);
205                 } catch (final BindException e) {
206                     LOG.warn("Cannot start simulated device on {}, port already in use. Skipping.", address);
207                     // Close local server and continue
208                     server.cancel(true);
209                     if(server.isDone()) {
210                         server.channel().close();
211                     }
212                     continue;
213                 } catch (final IOException e) {
214                     LOG.warn("Cannot start simulated device on {} due to IOException.", address, e);
215                     break;
216                 } finally {
217                     currentPort++;
218                 }
219
220                 try {
221                     server.get();
222                 } catch (final InterruptedException e) {
223                     throw new RuntimeException(e);
224                 } catch (final ExecutionException e) {
225                     LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
226                     continue;
227                 }
228
229                 LOG.debug("Simulated SSH device started on {}", address);
230
231             } else {
232                 server = dispatcher.createServer(address);
233                 currentPort++;
234
235                 try {
236                     server.get();
237                 } catch (final InterruptedException e) {
238                     throw new RuntimeException(e);
239                 } catch (final ExecutionException e) {
240                     LOG.warn("Cannot start tcp simulated device on {}, skipping", address, e);
241                     continue;
242                 }
243
244                 LOG.debug("Simulated TCP device started on {}", address);
245             }
246
247             devicesChannels.add(server.channel());
248             openDevices.add(currentPort - 1);
249         }
250
251         if(openDevices.size() == params.deviceCount) {
252             LOG.info("All simulated devices started successfully from port {} to {}", params.startingPort, currentPort - 1);
253         } else if (openDevices.size() == 0) {
254             LOG.warn("No simulated devices started.");
255         } else {
256             LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
257         }
258
259         return openDevices;
260     }
261
262     private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress, final LocalAddress tcpLocalAddress, final PEMGeneratorHostKeyProvider keyPairProvider) throws IOException {
263         return new SshProxyServerConfigurationBuilder()
264                 .setBindingAddress(bindingAddress)
265                 .setLocalAddress(tcpLocalAddress)
266                 .setAuthenticator(new AuthProvider() {
267                     @Override
268                     public boolean authenticated(final String username, final String password) {
269                         return true;
270                     }
271                 })
272                 .setKeyPairProvider(keyPairProvider)
273                 .setIdleTimeout(Integer.MAX_VALUE)
274                 .createSshProxyServerConfiguration();
275     }
276
277     private PEMGeneratorHostKeyProvider getPemGeneratorHostKeyProvider() {
278         try {
279             final Path tempFile = Files.createTempFile("tempKeyNetconfTest", "suffix");
280             return new PEMGeneratorHostKeyProvider(tempFile.toAbsolutePath().toString());
281         } catch (final IOException e) {
282             LOG.error("Unable to generate PEM key", e);
283             throw new RuntimeException(e);
284         }
285     }
286
287     private Set<Capability> parseSchemasToModuleCapabilities(final TesttoolParameters params, final SharedSchemaRepository consumer) {
288         final Set<SourceIdentifier> loadedSources = Sets.newHashSet();
289
290         consumer.registerSchemaSourceListener(TextToASTTransformer.create(consumer, consumer));
291
292         consumer.registerSchemaSourceListener(new SchemaSourceListener() {
293             @Override
294             public void schemaSourceEncountered(final SchemaSourceRepresentation schemaSourceRepresentation) {}
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         if(params.schemasDir != null) {
308             final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(consumer, YangTextSchemaSource.class, params.schemasDir);
309             consumer.registerSchemaSourceListener(cache);
310         }
311
312         addDefaultSchemas(consumer);
313
314         try {
315             //necessary for creating mdsal data stores and operations
316             this.schemaContext = consumer.createSchemaContextFactory(
317                 SchemaSourceFilter.ALWAYS_ACCEPT)
318                 .createSchemaContext(loadedSources).checkedGet();
319         } catch (final SchemaResolutionException e) {
320             throw new RuntimeException("Cannot parse schema context", e);
321         }
322
323         final Set<Capability> capabilities = Sets.newHashSet();
324
325         for (final Module module : schemaContext.getModules()) {
326             for (final Module subModule : module.getSubmodules()) {
327                 addModuleCapability(consumer, capabilities, subModule);
328             }
329             addModuleCapability(consumer, capabilities, module);
330         }
331         return capabilities;
332     }
333
334     private void addModuleCapability(final SharedSchemaRepository consumer, final Set<Capability> capabilities, final Module module) {
335         final SourceIdentifier moduleSourceIdentifier = SourceIdentifier.create(module.getName(),
336                 (SimpleDateFormatUtil.DEFAULT_DATE_REV == module.getRevision() ? Optional.<String>absent() :
337                         Optional.of(SimpleDateFormatUtil.getRevisionFormat().format(module.getRevision()))));
338         try {
339             final String moduleContent = new String(consumer.getSchemaSource(moduleSourceIdentifier, YangTextSchemaSource.class)
340                     .checkedGet().read());
341             capabilities.add(new YangModuleCapability(module, moduleContent));
342             //IOException would be thrown in creating SchemaContext already
343         } catch (SchemaSourceException |IOException e) {
344             throw new RuntimeException("Cannot retrieve schema source for module " + moduleSourceIdentifier.toString() + " from schema repository", e);
345         }
346     }
347
348     private void addDefaultSchemas(final SharedSchemaRepository consumer) {
349         SourceIdentifier sId = RevisionSourceIdentifier.create("ietf-netconf-monitoring", "2010-10-04");
350         registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring.yang", sId);
351
352         sId = RevisionSourceIdentifier.create("ietf-netconf-monitoring-extension", "2013-12-10");
353         registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring-extension.yang", sId);
354
355         sId = RevisionSourceIdentifier.create("ietf-yang-types", "2013-07-15");
356         registerSource(consumer, "/META-INF/yang/ietf-yang-types@2013-07-15.yang", sId);
357
358         sId = RevisionSourceIdentifier.create("ietf-inet-types", "2013-07-15");
359         registerSource(consumer, "/META-INF/yang/ietf-inet-types@2013-07-15.yang", sId);
360     }
361
362     private void registerSource(final SharedSchemaRepository consumer, final String resource, final SourceIdentifier sourceId) {
363         consumer.registerSchemaSource(new SchemaSourceProvider<SchemaSourceRepresentation>() {
364             @Override
365             public CheckedFuture<? extends SchemaSourceRepresentation, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
366                 return Futures.immediateCheckedFuture(new YangTextSchemaSource(sourceId) {
367                     @Override
368                     protected MoreObjects.ToStringHelper addToStringAttributes(final MoreObjects.ToStringHelper toStringHelper) {
369                         return toStringHelper;
370                     }
371
372                     @Override
373                     public InputStream openStream() throws IOException {
374                         return getClass().getResourceAsStream(resource);
375                     }
376                 });
377             }
378         }, PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
379     }
380
381     private static InetSocketAddress getAddress(final String ip, final int port) {
382         try {
383             return new InetSocketAddress(Inet4Address.getByName(ip), port);
384         } catch (final UnknownHostException e) {
385             throw new RuntimeException(e);
386         }
387     }
388
389     @Override
390     public void close() {
391         for (final SshProxyServer sshWrapper : sshWrappers) {
392             sshWrapper.close();
393         }
394         for (final Channel deviceCh : devicesChannels) {
395             deviceCh.close();
396         }
397         nettyThreadgroup.shutdownGracefully();
398         minaTimerExecutor.shutdownNow();
399         nioExecutor.shutdownNow();
400         // close Everything
401     }
402 }