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