Merge "Handle more specific BindException and IOException"
[controller.git] / opendaylight / netconf / netconf-testtool / src / main / java / org / opendaylight / controller / 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.controller.netconf.test.tool;
10
11 import com.google.common.base.Charsets;
12 import com.google.common.base.Function;
13 import com.google.common.base.Objects;
14 import com.google.common.base.Optional;
15 import com.google.common.collect.Collections2;
16 import com.google.common.collect.Lists;
17 import com.google.common.collect.Maps;
18 import com.google.common.collect.Sets;
19 import com.google.common.io.CharStreams;
20 import com.google.common.util.concurrent.CheckedFuture;
21 import com.google.common.util.concurrent.Futures;
22 import com.google.common.util.concurrent.ThreadFactoryBuilder;
23 import io.netty.channel.Channel;
24 import io.netty.channel.ChannelFuture;
25 import io.netty.channel.local.LocalAddress;
26 import io.netty.channel.nio.NioEventLoopGroup;
27 import io.netty.util.HashedWheelTimer;
28 import java.io.Closeable;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.InputStreamReader;
32 import java.lang.management.ManagementFactory;
33 import java.net.BindException;
34 import java.net.Inet4Address;
35 import java.net.InetSocketAddress;
36 import java.net.URI;
37 import java.net.UnknownHostException;
38 import java.nio.file.Files;
39 import java.nio.file.Path;
40 import java.util.AbstractMap;
41 import java.util.Date;
42 import java.util.HashMap;
43 import java.util.List;
44 import java.util.Map;
45 import java.util.Set;
46 import java.util.TreeMap;
47 import java.util.concurrent.ExecutionException;
48 import java.util.concurrent.ExecutorService;
49 import java.util.concurrent.Executors;
50 import java.util.concurrent.ScheduledExecutorService;
51 import org.antlr.v4.runtime.ParserRuleContext;
52 import org.antlr.v4.runtime.tree.ParseTreeWalker;
53 import org.apache.sshd.common.util.ThreadUtils;
54 import org.apache.sshd.server.PasswordAuthenticator;
55 import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
56 import org.apache.sshd.server.session.ServerSession;
57 import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession;
58 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
59 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
60 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
61 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
62 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
63 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
64 import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
65 import org.opendaylight.controller.netconf.mapping.api.Capability;
66 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
67 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
68 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
69 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceSnapshot;
70 import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringOperationService;
71 import org.opendaylight.controller.netconf.ssh.SshProxyServer;
72 import org.opendaylight.controller.netconf.ssh.SshProxyServerConfiguration;
73 import org.opendaylight.controller.netconf.ssh.SshProxyServerConfigurationBuilder;
74 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
75 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
76 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
77 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
78 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
79 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
80 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
81 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
82 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
83 import org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils;
84 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
85 import org.opendaylight.yangtools.yang.parser.impl.YangParserListenerImpl;
86 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
87 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
88 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
91
92 public class NetconfDeviceSimulator implements Closeable {
93
94     private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSimulator.class);
95
96     private final NioEventLoopGroup nettyThreadgroup;
97     private final HashedWheelTimer hashedWheelTimer;
98     private final List<Channel> devicesChannels = Lists.newArrayList();
99     private final List<SshProxyServer> sshWrappers = Lists.newArrayList();
100     private final ScheduledExecutorService minaTimerExecutor;
101     private final ExecutorService nioExecutor;
102
103     public NetconfDeviceSimulator() {
104         // TODO make pool size configurable
105         this(new NioEventLoopGroup(), new HashedWheelTimer(),
106                 Executors.newScheduledThreadPool(8, new ThreadFactoryBuilder().setNameFormat("netconf-ssh-server-mina-timers-%d").build()),
107                 ThreadUtils.newFixedThreadPool("netconf-ssh-server-nio-group", 8));
108     }
109
110     private NetconfDeviceSimulator(final NioEventLoopGroup eventExecutors, final HashedWheelTimer hashedWheelTimer, final ScheduledExecutorService minaTimerExecutor, final ExecutorService nioExecutor) {
111         this.nettyThreadgroup = eventExecutors;
112         this.hashedWheelTimer = hashedWheelTimer;
113         this.minaTimerExecutor = minaTimerExecutor;
114         this.nioExecutor = nioExecutor;
115     }
116
117     private NetconfServerDispatcher createDispatcher(final Map<ModuleBuilder, String> moduleBuilders, final boolean exi, final int generateConfigsTimeout) {
118
119         final Set<Capability> capabilities = Sets.newHashSet(Collections2.transform(moduleBuilders.keySet(), new Function<ModuleBuilder, Capability>() {
120             @Override
121             public Capability apply(final ModuleBuilder input) {
122                 return new ModuleBuilderCapability(input, moduleBuilders.get(input));
123             }
124         }));
125
126         final SessionIdProvider idProvider = new SessionIdProvider();
127
128         final SimulatedOperationProvider simulatedOperationProvider = new SimulatedOperationProvider(idProvider, capabilities);
129         final NetconfMonitoringOperationService monitoringService = new NetconfMonitoringOperationService(new NetconfMonitoringServiceImpl(simulatedOperationProvider));
130         simulatedOperationProvider.addService(monitoringService);
131
132         final DefaultCommitNotificationProducer commitNotifier = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
133
134         final Set<String> serverCapabilities = exi
135                 ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES
136                 : Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0, XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
137
138         final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
139                 hashedWheelTimer, simulatedOperationProvider, idProvider, generateConfigsTimeout, commitNotifier, new LoggingMonitoringService(), serverCapabilities);
140
141         final NetconfServerDispatcher.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerChannelInitializer(
142                 serverNegotiatorFactory);
143         return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
144     }
145
146     private Map<ModuleBuilder, String> toModuleBuilders(final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> sources) {
147         final Map<SourceIdentifier, ParserRuleContext> asts = Maps.transformValues(sources, new Function<Map.Entry<ASTSchemaSource, YangTextSchemaSource>, ParserRuleContext>() {
148             @Override
149             public ParserRuleContext apply(final Map.Entry<ASTSchemaSource, YangTextSchemaSource> input) {
150                 return input.getKey().getAST();
151             }
152         });
153         final Map<String, TreeMap<Date, URI>> namespaceContext = BuilderUtils.createYangNamespaceContext(
154                 asts.values(), Optional.<SchemaContext>absent());
155
156         final ParseTreeWalker walker = new ParseTreeWalker();
157         final Map<ModuleBuilder, String> sourceToBuilder = new HashMap<>();
158
159         for (final Map.Entry<SourceIdentifier, ParserRuleContext> entry : asts.entrySet()) {
160             final ModuleBuilder moduleBuilder = YangParserListenerImpl.create(namespaceContext, entry.getKey().getName(),
161                     walker, entry.getValue()).getModuleBuilder();
162
163             try(InputStreamReader stream = new InputStreamReader(sources.get(entry.getKey()).getValue().openStream(), Charsets.UTF_8)) {
164                 sourceToBuilder.put(moduleBuilder, CharStreams.toString(stream));
165             } catch (final IOException e) {
166                 throw new RuntimeException(e);
167             }
168         }
169
170         return sourceToBuilder;
171     }
172
173
174     public List<Integer> start(final Main.Params params) {
175         LOG.info("Starting {}, {} simulated devices starting on port {}", params.deviceCount, params.ssh ? "SSH" : "TCP", params.startingPort);
176
177         final Map<ModuleBuilder, String> moduleBuilders = parseSchemasToModuleBuilders(params);
178
179         final NetconfServerDispatcher dispatcher = createDispatcher(moduleBuilders, params.exi, params.generateConfigsTimeout);
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(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));
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) throws IOException {
263         return new SshProxyServerConfigurationBuilder()
264                 .setBindingAddress(bindingAddress)
265                 .setLocalAddress(tcpLocalAddress)
266                 .setAuthenticator(new PasswordAuthenticator() {
267                     @Override
268                     public boolean authenticate(final String username, final String password, final ServerSession session) {
269                         return true;
270                     }
271                 })
272                 .setKeyPairProvider(new PEMGeneratorHostKeyProvider(Files.createTempFile("prefix", "suffix").toAbsolutePath().toString()))
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 Map<ModuleBuilder, String> parseSchemasToModuleBuilders(final Main.Params params) {
288         final SharedSchemaRepository consumer = new SharedSchemaRepository("netconf-simulator");
289         consumer.registerSchemaSourceListener(TextToASTTransformer.create(consumer, consumer));
290
291         final Set<SourceIdentifier> loadedSources = Sets.newHashSet();
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<>(consumer, YangTextSchemaSource.class, params.schemasDir);
310             consumer.registerSchemaSourceListener(cache);
311         }
312
313         addDefaultSchemas(consumer);
314
315         final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> asts = Maps.newHashMap();
316         for (final SourceIdentifier loadedSource : loadedSources) {
317             try {
318                 final CheckedFuture<ASTSchemaSource, SchemaSourceException> ast = consumer.getSchemaSource(loadedSource, ASTSchemaSource.class);
319                 final CheckedFuture<YangTextSchemaSource, SchemaSourceException> text = consumer.getSchemaSource(loadedSource, YangTextSchemaSource.class);
320                 asts.put(loadedSource, new AbstractMap.SimpleEntry<>(ast.get(), text.get()));
321             } catch (final InterruptedException e) {
322                 throw new RuntimeException(e);
323             } catch (final ExecutionException e) {
324                 throw new RuntimeException("Cannot parse schema context", e);
325             }
326         }
327         return toModuleBuilders(asts);
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-yang-types", "2013-07-15");
335         registerSource(consumer, "/META-INF/yang/ietf-yang-types@2013-07-15.yang", sId);
336
337         sId = new SourceIdentifier("ietf-inet-types", "2010-09-24");
338         registerSource(consumer, "/META-INF/yang/ietf-inet-types.yang", sId);
339     }
340
341     private void registerSource(final SharedSchemaRepository consumer, final String resource, final SourceIdentifier sourceId) {
342         consumer.registerSchemaSource(new SchemaSourceProvider<SchemaSourceRepresentation>() {
343             @Override
344             public CheckedFuture<? extends SchemaSourceRepresentation, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
345                 return Futures.immediateCheckedFuture(new YangTextSchemaSource(sourceId) {
346                     @Override
347                     protected Objects.ToStringHelper addToStringAttributes(final Objects.ToStringHelper toStringHelper) {
348                         return toStringHelper;
349                     }
350
351                     @Override
352                     public InputStream openStream() throws IOException {
353                         return getClass().getResourceAsStream(resource);
354                     }
355                 });
356             }
357         }, PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
358     }
359
360     private static InetSocketAddress getAddress(final int port) {
361         try {
362             // TODO make address configurable
363             return new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), port);
364         } catch (final UnknownHostException e) {
365             throw new RuntimeException(e);
366         }
367     }
368
369     @Override
370     public void close() {
371         for (final SshProxyServer sshWrapper : sshWrappers) {
372             sshWrapper.close();
373         }
374         for (final Channel deviceCh : devicesChannels) {
375             deviceCh.close();
376         }
377         nettyThreadgroup.shutdownGracefully();
378         minaTimerExecutor.shutdownNow();
379         nioExecutor.shutdownNow();
380         // close Everything
381     }
382
383     private static class SimulatedOperationProvider implements NetconfOperationProvider {
384         private final SessionIdProvider idProvider;
385         private final Set<NetconfOperationService> netconfOperationServices;
386
387
388         public SimulatedOperationProvider(final SessionIdProvider idProvider, final Set<Capability> caps) {
389             this.idProvider = idProvider;
390             final SimulatedOperationService simulatedOperationService = new SimulatedOperationService(caps, idProvider.getCurrentSessionId());
391             this.netconfOperationServices = Sets.<NetconfOperationService>newHashSet(simulatedOperationService);
392         }
393
394         @Override
395         public NetconfOperationServiceSnapshot openSnapshot(final String sessionIdForReporting) {
396             return new SimulatedServiceSnapshot(idProvider, netconfOperationServices);
397         }
398
399         public void addService(final NetconfOperationService monitoringService) {
400             netconfOperationServices.add(monitoringService);
401         }
402
403         private static class SimulatedServiceSnapshot implements NetconfOperationServiceSnapshot {
404             private final SessionIdProvider idProvider;
405             private final Set<NetconfOperationService> netconfOperationServices;
406
407             public SimulatedServiceSnapshot(final SessionIdProvider idProvider, final Set<NetconfOperationService> netconfOperationServices) {
408                 this.idProvider = idProvider;
409                 this.netconfOperationServices = netconfOperationServices;
410             }
411
412             @Override
413             public String getNetconfSessionIdForReporting() {
414                 return String.valueOf(idProvider.getCurrentSessionId());
415             }
416
417             @Override
418             public Set<NetconfOperationService> getServices() {
419                 return netconfOperationServices;
420             }
421
422             @Override
423             public void close() throws Exception {}
424         }
425
426         static class SimulatedOperationService implements NetconfOperationService {
427             private final Set<Capability> capabilities;
428             private final long currentSessionId;
429
430             public SimulatedOperationService(final Set<Capability> capabilities, final long currentSessionId) {
431                 this.capabilities = capabilities;
432                 this.currentSessionId = currentSessionId;
433             }
434
435             @Override
436             public Set<Capability> getCapabilities() {
437                 return capabilities;
438             }
439
440             @Override
441             public Set<NetconfOperation> getNetconfOperations() {
442                 final DataList storage = new DataList();
443                 final SimulatedGet sGet = new SimulatedGet(String.valueOf(currentSessionId), storage);
444                 final SimulatedEditConfig sEditConfig = new SimulatedEditConfig(String.valueOf(currentSessionId), storage);
445                 final SimulatedGetConfig sGetConfig = new SimulatedGetConfig(String.valueOf(currentSessionId), storage);
446                 final SimulatedCommit sCommit = new SimulatedCommit(String.valueOf(currentSessionId));
447                 return Sets.<NetconfOperation>newHashSet(sGet,  sGetConfig, sEditConfig, sCommit);
448             }
449
450             @Override
451             public void close() {
452             }
453
454         }
455     }
456
457     private class LoggingMonitoringService implements SessionMonitoringService {
458         @Override
459         public void onSessionUp(final NetconfManagementSession session) {
460             LOG.debug("Session {} established", session);
461         }
462
463         @Override
464         public void onSessionDown(final NetconfManagementSession session) {
465             LOG.debug("Session {} down", session);
466         }
467     }
468
469 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.