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