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