adcdea6073860b5f6b660faa356baf9cf7455df4
[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             final InetSocketAddress address = getAddress(currentPort);
189
190             final ChannelFuture server;
191             if(params.ssh) {
192                 final InetSocketAddress bindingAddress = InetSocketAddress.createUnresolved("0.0.0.0", currentPort);
193                 final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());
194
195                 server = dispatcher.createLocalServer(tcpLocalAddress);
196                 try {
197                     final SshProxyServer sshServer = new SshProxyServer(minaTimerExecutor, nettyThreadgroup, nioExecutor);
198                     sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress));
199                     sshWrappers.add(sshServer);
200                 } catch (final Exception e) {
201                     LOG.warn("Cannot start simulated device on {}, skipping", address, e);
202                     // Close local server and continue
203                     server.cancel(true);
204                     if(server.isDone()) {
205                         server.channel().close();
206                     }
207                     continue;
208                 } finally {
209                     currentPort++;
210                 }
211
212                 try {
213                     server.get();
214                 } catch (final InterruptedException e) {
215                     throw new RuntimeException(e);
216                 } catch (final ExecutionException e) {
217                     LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
218                     continue;
219                 }
220
221                 LOG.debug("Simulated SSH device started on {}", address);
222
223             } else {
224                 server = dispatcher.createServer(address);
225                 currentPort++;
226
227                 try {
228                     server.get();
229                 } catch (final InterruptedException e) {
230                     throw new RuntimeException(e);
231                 } catch (final ExecutionException e) {
232                     LOG.warn("Cannot start tcp simulated device on {}, skipping", address, e);
233                     continue;
234                 }
235
236                 LOG.debug("Simulated TCP device started on {}", address);
237             }
238
239             devicesChannels.add(server.channel());
240             openDevices.add(currentPort - 1);
241         }
242
243         if(openDevices.size() == params.deviceCount) {
244             LOG.info("All simulated devices started successfully from port {} to {}", params.startingPort, currentPort - 1);
245         } else {
246             LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
247         }
248
249         return openDevices;
250     }
251
252     private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress, final LocalAddress tcpLocalAddress) throws IOException {
253         return new SshProxyServerConfigurationBuilder()
254                 .setBindingAddress(bindingAddress)
255                 .setLocalAddress(tcpLocalAddress)
256                 .setAuthenticator(new PasswordAuthenticator() {
257                     @Override
258                     public boolean authenticate(final String username, final String password, final ServerSession session) {
259                         return true;
260                     }
261                 })
262                 .setKeyPairProvider(new PEMGeneratorHostKeyProvider(Files.createTempFile("prefix", "suffix").toAbsolutePath().toString()))
263                 .setIdleTimeout(Integer.MAX_VALUE)
264                 .createSshProxyServerConfiguration();
265     }
266
267     private PEMGeneratorHostKeyProvider getPemGeneratorHostKeyProvider() {
268         try {
269             final Path tempFile = Files.createTempFile("tempKeyNetconfTest", "suffix");
270             return new PEMGeneratorHostKeyProvider(tempFile.toAbsolutePath().toString());
271         } catch (final IOException e) {
272             LOG.error("Unable to generate PEM key", e);
273             throw new RuntimeException(e);
274         }
275     }
276
277     private Map<ModuleBuilder, String> parseSchemasToModuleBuilders(final Main.Params params) {
278         final SharedSchemaRepository consumer = new SharedSchemaRepository("netconf-simulator");
279         consumer.registerSchemaSourceListener(TextToASTTransformer.create(consumer, consumer));
280
281         final Set<SourceIdentifier> loadedSources = Sets.newHashSet();
282
283         consumer.registerSchemaSourceListener(new SchemaSourceListener() {
284             @Override
285             public void schemaSourceEncountered(final SchemaSourceRepresentation schemaSourceRepresentation) {}
286
287             @Override
288             public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> potentialSchemaSources) {
289                 for (final PotentialSchemaSource<?> potentialSchemaSource : potentialSchemaSources) {
290                     loadedSources.add(potentialSchemaSource.getSourceIdentifier());
291                 }
292             }
293
294             @Override
295             public void schemaSourceUnregistered(final PotentialSchemaSource<?> potentialSchemaSource) {}
296         });
297
298         if(params.schemasDir != null) {
299             final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(consumer, YangTextSchemaSource.class, params.schemasDir);
300             consumer.registerSchemaSourceListener(cache);
301         }
302
303         addDefaultSchemas(consumer);
304
305         final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> asts = Maps.newHashMap();
306         for (final SourceIdentifier loadedSource : loadedSources) {
307             try {
308                 final CheckedFuture<ASTSchemaSource, SchemaSourceException> ast = consumer.getSchemaSource(loadedSource, ASTSchemaSource.class);
309                 final CheckedFuture<YangTextSchemaSource, SchemaSourceException> text = consumer.getSchemaSource(loadedSource, YangTextSchemaSource.class);
310                 asts.put(loadedSource, new AbstractMap.SimpleEntry<>(ast.get(), text.get()));
311             } catch (final InterruptedException e) {
312                 throw new RuntimeException(e);
313             } catch (final ExecutionException e) {
314                 throw new RuntimeException("Cannot parse schema context", e);
315             }
316         }
317         return toModuleBuilders(asts);
318     }
319
320     private void addDefaultSchemas(final SharedSchemaRepository consumer) {
321         SourceIdentifier sId = new SourceIdentifier("ietf-netconf-monitoring", "2010-10-04");
322         registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring.yang", sId);
323
324         sId = new SourceIdentifier("ietf-yang-types", "2013-07-15");
325         registerSource(consumer, "/META-INF/yang/ietf-yang-types@2013-07-15.yang", sId);
326
327         sId = new SourceIdentifier("ietf-inet-types", "2010-09-24");
328         registerSource(consumer, "/META-INF/yang/ietf-inet-types.yang", sId);
329     }
330
331     private void registerSource(final SharedSchemaRepository consumer, final String resource, final SourceIdentifier sourceId) {
332         consumer.registerSchemaSource(new SchemaSourceProvider<SchemaSourceRepresentation>() {
333             @Override
334             public CheckedFuture<? extends SchemaSourceRepresentation, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
335                 return Futures.immediateCheckedFuture(new YangTextSchemaSource(sourceId) {
336                     @Override
337                     protected Objects.ToStringHelper addToStringAttributes(final Objects.ToStringHelper toStringHelper) {
338                         return toStringHelper;
339                     }
340
341                     @Override
342                     public InputStream openStream() throws IOException {
343                         return getClass().getResourceAsStream(resource);
344                     }
345                 });
346             }
347         }, PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
348     }
349
350     private static InetSocketAddress getAddress(final int port) {
351         try {
352             // TODO make address configurable
353             return new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), port);
354         } catch (final UnknownHostException e) {
355             throw new RuntimeException(e);
356         }
357     }
358
359     @Override
360     public void close() {
361         for (final SshProxyServer sshWrapper : sshWrappers) {
362             sshWrapper.close();
363         }
364         for (final Channel deviceCh : devicesChannels) {
365             deviceCh.close();
366         }
367         nettyThreadgroup.shutdownGracefully();
368         minaTimerExecutor.shutdownNow();
369         nioExecutor.shutdownNow();
370         // close Everything
371     }
372
373     private static class SimulatedOperationProvider implements NetconfOperationProvider {
374         private final SessionIdProvider idProvider;
375         private final Set<NetconfOperationService> netconfOperationServices;
376
377
378         public SimulatedOperationProvider(final SessionIdProvider idProvider, final Set<Capability> caps) {
379             this.idProvider = idProvider;
380             final SimulatedOperationService simulatedOperationService = new SimulatedOperationService(caps, idProvider.getCurrentSessionId());
381             this.netconfOperationServices = Sets.<NetconfOperationService>newHashSet(simulatedOperationService);
382         }
383
384         @Override
385         public NetconfOperationServiceSnapshot openSnapshot(final String sessionIdForReporting) {
386             return new SimulatedServiceSnapshot(idProvider, netconfOperationServices);
387         }
388
389         public void addService(final NetconfOperationService monitoringService) {
390             netconfOperationServices.add(monitoringService);
391         }
392
393         private static class SimulatedServiceSnapshot implements NetconfOperationServiceSnapshot {
394             private final SessionIdProvider idProvider;
395             private final Set<NetconfOperationService> netconfOperationServices;
396
397             public SimulatedServiceSnapshot(final SessionIdProvider idProvider, final Set<NetconfOperationService> netconfOperationServices) {
398                 this.idProvider = idProvider;
399                 this.netconfOperationServices = netconfOperationServices;
400             }
401
402             @Override
403             public String getNetconfSessionIdForReporting() {
404                 return String.valueOf(idProvider.getCurrentSessionId());
405             }
406
407             @Override
408             public Set<NetconfOperationService> getServices() {
409                 return netconfOperationServices;
410             }
411
412             @Override
413             public void close() throws Exception {}
414         }
415
416         static class SimulatedOperationService implements NetconfOperationService {
417             private final Set<Capability> capabilities;
418             private final long currentSessionId;
419
420             public SimulatedOperationService(final Set<Capability> capabilities, final long currentSessionId) {
421                 this.capabilities = capabilities;
422                 this.currentSessionId = currentSessionId;
423             }
424
425             @Override
426             public Set<Capability> getCapabilities() {
427                 return capabilities;
428             }
429
430             @Override
431             public Set<NetconfOperation> getNetconfOperations() {
432                 final DataList storage = new DataList();
433                 final SimulatedGet sGet = new SimulatedGet(String.valueOf(currentSessionId), storage);
434                 final SimulatedEditConfig sEditConfig = new SimulatedEditConfig(String.valueOf(currentSessionId), storage);
435                 final SimulatedGetConfig sGetConfig = new SimulatedGetConfig(String.valueOf(currentSessionId), storage);
436                 final SimulatedCommit sCommit = new SimulatedCommit(String.valueOf(currentSessionId));
437                 return Sets.<NetconfOperation>newHashSet(sGet,  sGetConfig, sEditConfig, sCommit);
438             }
439
440             @Override
441             public void close() {
442             }
443
444         }
445     }
446
447     private class LoggingMonitoringService implements SessionMonitoringService {
448         @Override
449         public void onSessionUp(final NetconfManagementSession session) {
450             LOG.debug("Session {} established", session);
451         }
452
453         @Override
454         public void onSessionDown(final NetconfManagementSession session) {
455             LOG.debug("Session {} down", session);
456         }
457     }
458
459 }