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