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