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

©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.