Bug 8153: enforce check-style rules for netconf
[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.MoreObjects;
12 import com.google.common.base.Optional;
13 import com.google.common.collect.Collections2;
14 import com.google.common.collect.Lists;
15 import com.google.common.collect.Sets;
16 import com.google.common.util.concurrent.CheckedFuture;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ThreadFactoryBuilder;
19 import io.netty.channel.Channel;
20 import io.netty.channel.ChannelFuture;
21 import io.netty.channel.local.LocalAddress;
22 import io.netty.channel.nio.NioEventLoopGroup;
23 import io.netty.util.HashedWheelTimer;
24 import java.io.Closeable;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.net.BindException;
28 import java.net.Inet4Address;
29 import java.net.InetSocketAddress;
30 import java.net.UnknownHostException;
31 import java.nio.file.Files;
32 import java.nio.file.Path;
33 import java.util.List;
34 import java.util.Set;
35 import java.util.concurrent.ExecutionException;
36 import java.util.concurrent.ExecutorService;
37 import java.util.concurrent.Executors;
38 import java.util.concurrent.ScheduledExecutorService;
39 import org.apache.sshd.common.util.ThreadUtils;
40 import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
41 import org.opendaylight.controller.config.util.capability.BasicCapability;
42 import org.opendaylight.controller.config.util.capability.Capability;
43 import org.opendaylight.controller.config.util.capability.YangModuleCapability;
44 import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
45 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
46 import org.opendaylight.netconf.auth.AuthProvider;
47 import org.opendaylight.netconf.impl.NetconfServerDispatcherImpl;
48 import org.opendaylight.netconf.impl.NetconfServerSessionNegotiatorFactory;
49 import org.opendaylight.netconf.impl.SessionIdProvider;
50 import org.opendaylight.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
51 import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactory;
52 import org.opendaylight.netconf.monitoring.osgi.NetconfMonitoringActivator;
53 import org.opendaylight.netconf.monitoring.osgi.NetconfMonitoringOperationService;
54 import org.opendaylight.netconf.ssh.SshProxyServer;
55 import org.opendaylight.netconf.ssh.SshProxyServerConfiguration;
56 import org.opendaylight.netconf.ssh.SshProxyServerConfigurationBuilder;
57 import org.opendaylight.netconf.test.tool.customrpc.SettableOperationProvider;
58 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
59 import org.opendaylight.yangtools.yang.model.api.Module;
60 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
61 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
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,
94                     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,
99             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,
107             final SchemaSourceProvider<YangTextSchemaSource> sourceProvider, final TesttoolParameters params) {
108
109         final Set<Capability> transformedCapabilities = Sets.newHashSet(Collections2.transform(capabilities, input -> {
110             if (sendFakeSchema) {
111                 sendFakeSchema = false;
112                 return new FakeCapability((YangModuleCapability) input);
113             } else {
114                 return input;
115             }
116         }));
117         transformedCapabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0"));
118         final NetconfMonitoringService monitoringService1 = new DummyMonitoringService(transformedCapabilities);
119         final SessionIdProvider idProvider = new SessionIdProvider();
120
121         final NetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory = createOperationServiceFactory(
122             sourceProvider, params, transformedCapabilities, monitoringService1, idProvider);
123
124         final Set<String> serverCapabilities = params.exi
125                 ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES
126                 : Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
127                     XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
128
129         final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new TesttoolNegotiationFactory(
130                 hashedWheelTimer, aggregatedNetconfOperationServiceFactory, idProvider, params.generateConfigsTimeout,
131                 monitoringService1, serverCapabilities);
132
133         final NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer =
134             new NetconfServerDispatcherImpl.ServerChannelInitializer(serverNegotiatorFactory);
135         return new NetconfServerDispatcherImpl(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
136     }
137
138     private NetconfOperationServiceFactory createOperationServiceFactory(
139             final SchemaSourceProvider<YangTextSchemaSource> sourceProvider, final TesttoolParameters params,
140             final Set<Capability> transformedCapabilities, final NetconfMonitoringService monitoringService1,
141             final SessionIdProvider idProvider) {
142         final AggregatedNetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory =
143             new AggregatedNetconfOperationServiceFactory();
144
145         final NetconfOperationServiceFactory operationProvider;
146         if (params.mdSal) {
147             operationProvider = new MdsalOperationProvider(
148                 idProvider, transformedCapabilities, schemaContext, sourceProvider);
149         } else {
150             operationProvider = new SimulatedOperationProvider(idProvider, transformedCapabilities,
151                     Optional.fromNullable(params.notificationFile),
152                     Optional.fromNullable(params.initialConfigXMLFile));
153         }
154
155
156         final NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory monitoringService =
157                 new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(
158                         new NetconfMonitoringOperationService(monitoringService1));
159         aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(operationProvider);
160         aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(monitoringService);
161         if (params.rpcConfig != null) {
162             final SettableOperationProvider settableService = new SettableOperationProvider(params.rpcConfig);
163             aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(settableService);
164         }
165         return aggregatedNetconfOperationServiceFactory;
166     }
167
168     public List<Integer> start(final TesttoolParameters params) {
169         LOG.info("Starting {}, {} simulated devices starting on port {}",
170             params.deviceCount, params.ssh ? "SSH" : "TCP", params.startingPort);
171
172         final SharedSchemaRepository schemaRepo = new SharedSchemaRepository("netconf-simulator");
173         final Set<Capability> capabilities = parseSchemasToModuleCapabilities(params, schemaRepo);
174
175         final NetconfServerDispatcherImpl dispatcher = createDispatcher(capabilities,
176             sourceIdentifier -> schemaRepo.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class), params);
177
178         int currentPort = params.startingPort;
179
180         final List<Integer> openDevices = Lists.newArrayList();
181
182         // Generate key to temp folder
183         final PEMGeneratorHostKeyProvider keyPairProvider = getPemGeneratorHostKeyProvider();
184
185         for (int i = 0; i < params.deviceCount; i++) {
186             if (currentPort > 65535) {
187                 LOG.warn("Port cannot be greater than 65535, stopping further attempts.");
188                 break;
189             }
190             final InetSocketAddress address = getAddress(params.ip, currentPort);
191
192             final ChannelFuture server;
193             if (params.ssh) {
194                 final InetSocketAddress bindingAddress = InetSocketAddress.createUnresolved("0.0.0.0", currentPort);
195                 final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());
196
197                 server = dispatcher.createLocalServer(tcpLocalAddress);
198                 try {
199                     final SshProxyServer sshServer = new SshProxyServer(
200                         minaTimerExecutor, nettyThreadgroup, nioExecutor);
201                     sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress, keyPairProvider));
202                     sshWrappers.add(sshServer);
203                 } catch (final BindException e) {
204                     LOG.warn("Cannot start simulated device on {}, port already in use. Skipping.", address);
205                     // Close local server and continue
206                     server.cancel(true);
207                     if (server.isDone()) {
208                         server.channel().close();
209                     }
210                     continue;
211                 } catch (final IOException e) {
212                     LOG.warn("Cannot start simulated device on {} due to IOException.", address, e);
213                     break;
214                 } finally {
215                     currentPort++;
216                 }
217
218                 try {
219                     server.get();
220                 } catch (final InterruptedException e) {
221                     throw new RuntimeException(e);
222                 } catch (final ExecutionException e) {
223                     LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
224                     continue;
225                 }
226
227                 LOG.debug("Simulated SSH device started on {}", address);
228
229             } else {
230                 server = dispatcher.createServer(address);
231                 currentPort++;
232
233                 try {
234                     server.get();
235                 } catch (final InterruptedException e) {
236                     throw new RuntimeException(e);
237                 } catch (final ExecutionException e) {
238                     LOG.warn("Cannot start tcp simulated device on {}, skipping", address, e);
239                     continue;
240                 }
241
242                 LOG.debug("Simulated TCP device started on {}", address);
243             }
244
245             devicesChannels.add(server.channel());
246             openDevices.add(currentPort - 1);
247         }
248
249         if (openDevices.size() == params.deviceCount) {
250             LOG.info("All simulated devices started successfully from port {} to {}",
251                 params.startingPort, currentPort - 1);
252         } else if (openDevices.size() == 0) {
253             LOG.warn("No simulated devices started.");
254         } else {
255             LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
256         }
257
258         return openDevices;
259     }
260
261     private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress,
262             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,
288                                                              final SharedSchemaRepository consumer) {
289         final Set<SourceIdentifier> loadedSources = Sets.newHashSet();
290
291         consumer.registerSchemaSourceListener(TextToASTTransformer.create(consumer, consumer));
292
293         consumer.registerSchemaSourceListener(new SchemaSourceListener() {
294             @Override
295             public void schemaSourceEncountered(final SchemaSourceRepresentation schemaSourceRepresentation) {}
296
297             @Override
298             public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> potentialSchemaSources) {
299                 for (final PotentialSchemaSource<?> potentialSchemaSource : potentialSchemaSources) {
300                     loadedSources.add(potentialSchemaSource.getSourceIdentifier());
301                 }
302             }
303
304             @Override
305             public void schemaSourceUnregistered(final PotentialSchemaSource<?> potentialSchemaSource) {}
306         });
307
308         if (params.schemasDir != null) {
309             final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(
310                 consumer, YangTextSchemaSource.class, params.schemasDir);
311             consumer.registerSchemaSourceListener(cache);
312         }
313
314         addDefaultSchemas(consumer);
315
316         try {
317             //necessary for creating mdsal data stores and operations
318             this.schemaContext = consumer.createSchemaContextFactory(
319                 SchemaSourceFilter.ALWAYS_ACCEPT)
320                 .createSchemaContext(loadedSources).checkedGet();
321         } catch (final SchemaResolutionException e) {
322             throw new RuntimeException("Cannot parse schema context", e);
323         }
324
325         final Set<Capability> capabilities = Sets.newHashSet();
326
327         for (final Module module : schemaContext.getModules()) {
328             for (final Module subModule : module.getSubmodules()) {
329                 addModuleCapability(consumer, capabilities, subModule);
330             }
331             addModuleCapability(consumer, capabilities, module);
332         }
333         return capabilities;
334     }
335
336     private void addModuleCapability(final SharedSchemaRepository consumer, final Set<Capability> capabilities,
337                                      final Module module) {
338         final SourceIdentifier moduleSourceIdentifier = SourceIdentifier.create(module.getName(),
339                 (SimpleDateFormatUtil.DEFAULT_DATE_REV == module.getRevision() ? Optional.absent() :
340                         Optional.of(module.getQNameModule().getFormattedRevision())));
341         try {
342             final String moduleContent = new String(
343                 consumer.getSchemaSource(moduleSourceIdentifier, YangTextSchemaSource.class).checkedGet().read());
344             capabilities.add(new YangModuleCapability(module, moduleContent));
345             //IOException would be thrown in creating SchemaContext already
346         } catch (SchemaSourceException | IOException e) {
347             throw new RuntimeException("Cannot retrieve schema source for module "
348                 + moduleSourceIdentifier.toString() + " from schema repository", e);
349         }
350     }
351
352     private void addDefaultSchemas(final SharedSchemaRepository consumer) {
353         SourceIdentifier srcId = RevisionSourceIdentifier.create("ietf-netconf-monitoring", "2010-10-04");
354         registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring.yang", srcId);
355
356         srcId = RevisionSourceIdentifier.create("ietf-netconf-monitoring-extension", "2013-12-10");
357         registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring-extension.yang", srcId);
358
359         srcId = RevisionSourceIdentifier.create("ietf-yang-types", "2013-07-15");
360         registerSource(consumer, "/META-INF/yang/ietf-yang-types@2013-07-15.yang", srcId);
361
362         srcId = RevisionSourceIdentifier.create("ietf-inet-types", "2013-07-15");
363         registerSource(consumer, "/META-INF/yang/ietf-inet-types@2013-07-15.yang", srcId);
364     }
365
366     private void registerSource(final SharedSchemaRepository consumer, final String resource,
367                                 final SourceIdentifier sourceId) {
368         consumer.registerSchemaSource(new SchemaSourceProvider<SchemaSourceRepresentation>() {
369             @Override
370             public CheckedFuture<? extends SchemaSourceRepresentation, SchemaSourceException> getSource(
371                     final SourceIdentifier sourceIdentifier) {
372                 return Futures.immediateCheckedFuture(new YangTextSchemaSource(sourceId) {
373                     @Override
374                     protected MoreObjects.ToStringHelper addToStringAttributes(
375                             final MoreObjects.ToStringHelper toStringHelper) {
376                         return toStringHelper;
377                     }
378
379                     @Override
380                     public InputStream openStream() throws IOException {
381                         return getClass().getResourceAsStream(resource);
382                     }
383                 });
384             }
385         }, PotentialSchemaSource.create(
386             sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
387     }
388
389     private static InetSocketAddress getAddress(final String ip, final int port) {
390         try {
391             return new InetSocketAddress(Inet4Address.getByName(ip), port);
392         } catch (final UnknownHostException e) {
393             throw new RuntimeException(e);
394         }
395     }
396
397     @Override
398     public void close() {
399         for (final SshProxyServer sshWrapper : sshWrappers) {
400             sshWrapper.close();
401         }
402         for (final Channel deviceCh : devicesChannels) {
403             deviceCh.close();
404         }
405         nettyThreadgroup.shutdownGracefully();
406         minaTimerExecutor.shutdownNow();
407         nioExecutor.shutdownNow();
408         // close Everything
409     }
410 }