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