Merge "Fix allowable Unix ports range 1024 - 65535"
[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.Inet4Address;
34 import java.net.InetSocketAddress;
35 import java.net.URI;
36 import java.net.UnknownHostException;
37 import java.nio.file.Files;
38 import java.nio.file.Path;
39 import java.util.AbstractMap;
40 import java.util.Date;
41 import java.util.HashMap;
42 import java.util.List;
43 import java.util.Map;
44 import java.util.Set;
45 import java.util.TreeMap;
46 import java.util.concurrent.ExecutionException;
47 import java.util.concurrent.ExecutorService;
48 import java.util.concurrent.Executors;
49 import java.util.concurrent.ScheduledExecutorService;
50 import org.antlr.v4.runtime.ParserRuleContext;
51 import org.antlr.v4.runtime.tree.ParseTreeWalker;
52 import org.apache.sshd.common.util.ThreadUtils;
53 import org.apache.sshd.server.PasswordAuthenticator;
54 import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
55 import org.apache.sshd.server.session.ServerSession;
56 import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession;
57 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
58 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
59 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
60 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
61 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
62 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
63 import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
64 import org.opendaylight.controller.netconf.mapping.api.Capability;
65 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
66 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
67 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
68 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceSnapshot;
69 import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringOperationService;
70 import org.opendaylight.controller.netconf.ssh.SshProxyServer;
71 import org.opendaylight.controller.netconf.ssh.SshProxyServerConfiguration;
72 import org.opendaylight.controller.netconf.ssh.SshProxyServerConfigurationBuilder;
73 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
74 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
75 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
76 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
77 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
78 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
79 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
80 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
81 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
82 import org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils;
83 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
84 import org.opendaylight.yangtools.yang.parser.impl.YangParserListenerImpl;
85 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
86 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
87 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
88 import org.slf4j.Logger;
89 import org.slf4j.LoggerFactory;
90
91 public class NetconfDeviceSimulator implements Closeable {
92
93     private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSimulator.class);
94
95     private final NioEventLoopGroup nettyThreadgroup;
96     private final HashedWheelTimer hashedWheelTimer;
97     private final List<Channel> devicesChannels = Lists.newArrayList();
98     private final List<SshProxyServer> sshWrappers = Lists.newArrayList();
99     private final ScheduledExecutorService minaTimerExecutor;
100     private final ExecutorService nioExecutor;
101
102     public NetconfDeviceSimulator() {
103         // TODO make pool size configurable
104         this(new NioEventLoopGroup(), new HashedWheelTimer(),
105                 Executors.newScheduledThreadPool(8, new ThreadFactoryBuilder().setNameFormat("netconf-ssh-server-mina-timers-%d").build()),
106                 ThreadUtils.newFixedThreadPool("netconf-ssh-server-nio-group", 8));
107     }
108
109     private NetconfDeviceSimulator(final NioEventLoopGroup eventExecutors, final HashedWheelTimer hashedWheelTimer, final ScheduledExecutorService minaTimerExecutor, final ExecutorService nioExecutor) {
110         this.nettyThreadgroup = eventExecutors;
111         this.hashedWheelTimer = hashedWheelTimer;
112         this.minaTimerExecutor = minaTimerExecutor;
113         this.nioExecutor = nioExecutor;
114     }
115
116     private NetconfServerDispatcher createDispatcher(final Map<ModuleBuilder, String> moduleBuilders, final boolean exi, final int generateConfigsTimeout) {
117
118         final Set<Capability> capabilities = Sets.newHashSet(Collections2.transform(moduleBuilders.keySet(), new Function<ModuleBuilder, Capability>() {
119             @Override
120             public Capability apply(final ModuleBuilder input) {
121                 return new ModuleBuilderCapability(input, moduleBuilders.get(input));
122             }
123         }));
124
125         final SessionIdProvider idProvider = new SessionIdProvider();
126
127         final SimulatedOperationProvider simulatedOperationProvider = new SimulatedOperationProvider(idProvider, capabilities);
128         final NetconfMonitoringOperationService monitoringService = new NetconfMonitoringOperationService(new NetconfMonitoringServiceImpl(simulatedOperationProvider));
129         simulatedOperationProvider.addService(monitoringService);
130
131         final DefaultCommitNotificationProducer commitNotifier = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
132
133         final Set<String> serverCapabilities = exi
134                 ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES
135                 : Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0, XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
136
137         final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
138                 hashedWheelTimer, simulatedOperationProvider, idProvider, generateConfigsTimeout, commitNotifier, new LoggingMonitoringService(), serverCapabilities);
139
140         final NetconfServerDispatcher.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerChannelInitializer(
141                 serverNegotiatorFactory);
142         return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
143     }
144
145     private Map<ModuleBuilder, String> toModuleBuilders(final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> sources) {
146         final Map<SourceIdentifier, ParserRuleContext> asts = Maps.transformValues(sources, new Function<Map.Entry<ASTSchemaSource, YangTextSchemaSource>, ParserRuleContext>() {
147             @Override
148             public ParserRuleContext apply(final Map.Entry<ASTSchemaSource, YangTextSchemaSource> input) {
149                 return input.getKey().getAST();
150             }
151         });
152         final Map<String, TreeMap<Date, URI>> namespaceContext = BuilderUtils.createYangNamespaceContext(
153                 asts.values(), Optional.<SchemaContext>absent());
154
155         final ParseTreeWalker walker = new ParseTreeWalker();
156         final Map<ModuleBuilder, String> sourceToBuilder = new HashMap<>();
157
158         for (final Map.Entry<SourceIdentifier, ParserRuleContext> entry : asts.entrySet()) {
159             final ModuleBuilder moduleBuilder = YangParserListenerImpl.create(namespaceContext, entry.getKey().getName(),
160                     walker, entry.getValue()).getModuleBuilder();
161
162             try(InputStreamReader stream = new InputStreamReader(sources.get(entry.getKey()).getValue().openStream(), Charsets.UTF_8)) {
163                 sourceToBuilder.put(moduleBuilder, CharStreams.toString(stream));
164             } catch (final IOException e) {
165                 throw new RuntimeException(e);
166             }
167         }
168
169         return sourceToBuilder;
170     }
171
172
173     public List<Integer> start(final Main.Params params) {
174         LOG.info("Starting {}, {} simulated devices starting on port {}", params.deviceCount, params.ssh ? "SSH" : "TCP", params.startingPort);
175
176         final Map<ModuleBuilder, String> moduleBuilders = parseSchemasToModuleBuilders(params);
177
178         final NetconfServerDispatcher dispatcher = createDispatcher(moduleBuilders, params.exi, params.generateConfigsTimeout);
179
180         int currentPort = params.startingPort;
181
182         final List<Integer> openDevices = Lists.newArrayList();
183
184         // Generate key to temp folder
185         final PEMGeneratorHostKeyProvider keyPairProvider = getPemGeneratorHostKeyProvider();
186
187         for (int i = 0; i < params.deviceCount; i++) {
188             if (currentPort > 65535) {
189                 LOG.warn("Port cannot be greater than 65535, stopping further attempts.");
190                 break;
191             }
192             final InetSocketAddress address = getAddress(currentPort);
193
194             final ChannelFuture server;
195             if(params.ssh) {
196                 final InetSocketAddress bindingAddress = InetSocketAddress.createUnresolved("0.0.0.0", currentPort);
197                 final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());
198
199                 server = dispatcher.createLocalServer(tcpLocalAddress);
200                 try {
201                     final SshProxyServer sshServer = new SshProxyServer(minaTimerExecutor, nettyThreadgroup, nioExecutor);
202                     sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress));
203                     sshWrappers.add(sshServer);
204                 } catch (final Exception e) {
205                     LOG.warn("Cannot start simulated device on {}, skipping", address, e);
206                     // Close local server and continue
207                     server.cancel(true);
208                     if(server.isDone()) {
209                         server.channel().close();
210                     }
211                     continue;
212                 } finally {
213                     currentPort++;
214                 }
215
216                 try {
217                     server.get();
218                 } catch (final InterruptedException e) {
219                     throw new RuntimeException(e);
220                 } catch (final ExecutionException e) {
221                     LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
222                     continue;
223                 }
224
225                 LOG.debug("Simulated SSH device started on {}", address);
226
227             } else {
228                 server = dispatcher.createServer(address);
229                 currentPort++;
230
231                 try {
232                     server.get();
233                 } catch (final InterruptedException e) {
234                     throw new RuntimeException(e);
235                 } catch (final ExecutionException e) {
236                     LOG.warn("Cannot start tcp simulated device on {}, skipping", address, e);
237                     continue;
238                 }
239
240                 LOG.debug("Simulated TCP device started on {}", address);
241             }
242
243             devicesChannels.add(server.channel());
244             openDevices.add(currentPort - 1);
245         }
246
247         if(openDevices.size() == params.deviceCount) {
248             LOG.info("All simulated devices started successfully from port {} to {}", params.startingPort, currentPort - 1);
249         } else if (openDevices.size() == 0) {
250             LOG.warn("No simulated devices started.");
251         } else {
252             LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
253         }
254
255         return openDevices;
256     }
257
258     private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress, final LocalAddress tcpLocalAddress) throws IOException {
259         return new SshProxyServerConfigurationBuilder()
260                 .setBindingAddress(bindingAddress)
261                 .setLocalAddress(tcpLocalAddress)
262                 .setAuthenticator(new PasswordAuthenticator() {
263                     @Override
264                     public boolean authenticate(final String username, final String password, final ServerSession session) {
265                         return true;
266                     }
267                 })
268                 .setKeyPairProvider(new PEMGeneratorHostKeyProvider(Files.createTempFile("prefix", "suffix").toAbsolutePath().toString()))
269                 .setIdleTimeout(Integer.MAX_VALUE)
270                 .createSshProxyServerConfiguration();
271     }
272
273     private PEMGeneratorHostKeyProvider getPemGeneratorHostKeyProvider() {
274         try {
275             final Path tempFile = Files.createTempFile("tempKeyNetconfTest", "suffix");
276             return new PEMGeneratorHostKeyProvider(tempFile.toAbsolutePath().toString());
277         } catch (final IOException e) {
278             LOG.error("Unable to generate PEM key", e);
279             throw new RuntimeException(e);
280         }
281     }
282
283     private Map<ModuleBuilder, String> parseSchemasToModuleBuilders(final Main.Params params) {
284         final SharedSchemaRepository consumer = new SharedSchemaRepository("netconf-simulator");
285         consumer.registerSchemaSourceListener(TextToASTTransformer.create(consumer, consumer));
286
287         final Set<SourceIdentifier> loadedSources = Sets.newHashSet();
288
289         consumer.registerSchemaSourceListener(new SchemaSourceListener() {
290             @Override
291             public void schemaSourceEncountered(final SchemaSourceRepresentation schemaSourceRepresentation) {}
292
293             @Override
294             public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> potentialSchemaSources) {
295                 for (final PotentialSchemaSource<?> potentialSchemaSource : potentialSchemaSources) {
296                     loadedSources.add(potentialSchemaSource.getSourceIdentifier());
297                 }
298             }
299
300             @Override
301             public void schemaSourceUnregistered(final PotentialSchemaSource<?> potentialSchemaSource) {}
302         });
303
304         if(params.schemasDir != null) {
305             final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(consumer, YangTextSchemaSource.class, params.schemasDir);
306             consumer.registerSchemaSourceListener(cache);
307         }
308
309         addDefaultSchemas(consumer);
310
311         final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> asts = Maps.newHashMap();
312         for (final SourceIdentifier loadedSource : loadedSources) {
313             try {
314                 final CheckedFuture<ASTSchemaSource, SchemaSourceException> ast = consumer.getSchemaSource(loadedSource, ASTSchemaSource.class);
315                 final CheckedFuture<YangTextSchemaSource, SchemaSourceException> text = consumer.getSchemaSource(loadedSource, YangTextSchemaSource.class);
316                 asts.put(loadedSource, new AbstractMap.SimpleEntry<>(ast.get(), text.get()));
317             } catch (final InterruptedException e) {
318                 throw new RuntimeException(e);
319             } catch (final ExecutionException e) {
320                 throw new RuntimeException("Cannot parse schema context", e);
321             }
322         }
323         return toModuleBuilders(asts);
324     }
325
326     private void addDefaultSchemas(final SharedSchemaRepository consumer) {
327         SourceIdentifier sId = new SourceIdentifier("ietf-netconf-monitoring", "2010-10-04");
328         registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring.yang", sId);
329
330         sId = new SourceIdentifier("ietf-yang-types", "2013-07-15");
331         registerSource(consumer, "/META-INF/yang/ietf-yang-types@2013-07-15.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 Objects.ToStringHelper addToStringAttributes(final Objects.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
379     private static class SimulatedOperationProvider implements NetconfOperationProvider {
380         private final SessionIdProvider idProvider;
381         private final Set<NetconfOperationService> netconfOperationServices;
382
383
384         public SimulatedOperationProvider(final SessionIdProvider idProvider, final Set<Capability> caps) {
385             this.idProvider = idProvider;
386             final SimulatedOperationService simulatedOperationService = new SimulatedOperationService(caps, idProvider.getCurrentSessionId());
387             this.netconfOperationServices = Sets.<NetconfOperationService>newHashSet(simulatedOperationService);
388         }
389
390         @Override
391         public NetconfOperationServiceSnapshot openSnapshot(final String sessionIdForReporting) {
392             return new SimulatedServiceSnapshot(idProvider, netconfOperationServices);
393         }
394
395         public void addService(final NetconfOperationService monitoringService) {
396             netconfOperationServices.add(monitoringService);
397         }
398
399         private static class SimulatedServiceSnapshot implements NetconfOperationServiceSnapshot {
400             private final SessionIdProvider idProvider;
401             private final Set<NetconfOperationService> netconfOperationServices;
402
403             public SimulatedServiceSnapshot(final SessionIdProvider idProvider, final Set<NetconfOperationService> netconfOperationServices) {
404                 this.idProvider = idProvider;
405                 this.netconfOperationServices = netconfOperationServices;
406             }
407
408             @Override
409             public String getNetconfSessionIdForReporting() {
410                 return String.valueOf(idProvider.getCurrentSessionId());
411             }
412
413             @Override
414             public Set<NetconfOperationService> getServices() {
415                 return netconfOperationServices;
416             }
417
418             @Override
419             public void close() throws Exception {}
420         }
421
422         static class SimulatedOperationService implements NetconfOperationService {
423             private final Set<Capability> capabilities;
424             private final long currentSessionId;
425
426             public SimulatedOperationService(final Set<Capability> capabilities, final long currentSessionId) {
427                 this.capabilities = capabilities;
428                 this.currentSessionId = currentSessionId;
429             }
430
431             @Override
432             public Set<Capability> getCapabilities() {
433                 return capabilities;
434             }
435
436             @Override
437             public Set<NetconfOperation> getNetconfOperations() {
438                 final DataList storage = new DataList();
439                 final SimulatedGet sGet = new SimulatedGet(String.valueOf(currentSessionId), storage);
440                 final SimulatedEditConfig sEditConfig = new SimulatedEditConfig(String.valueOf(currentSessionId), storage);
441                 final SimulatedGetConfig sGetConfig = new SimulatedGetConfig(String.valueOf(currentSessionId), storage);
442                 final SimulatedCommit sCommit = new SimulatedCommit(String.valueOf(currentSessionId));
443                 return Sets.<NetconfOperation>newHashSet(sGet,  sGetConfig, sEditConfig, sCommit);
444             }
445
446             @Override
447             public void close() {
448             }
449
450         }
451     }
452
453     private class LoggingMonitoringService implements SessionMonitoringService {
454         @Override
455         public void onSessionUp(final NetconfManagementSession session) {
456             LOG.debug("Session {} established", session);
457         }
458
459         @Override
460         public void onSessionDown(final NetconfManagementSession session) {
461             LOG.debug("Session {} down", session);
462         }
463     }
464
465 }