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