Implement md-sal datastore into netconf test-tool
[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.NavigableMap;
47 import java.util.Set;
48 import java.util.concurrent.ExecutionException;
49 import java.util.concurrent.ExecutorService;
50 import java.util.concurrent.Executors;
51 import java.util.concurrent.ScheduledExecutorService;
52 import org.antlr.v4.runtime.ParserRuleContext;
53 import org.antlr.v4.runtime.tree.ParseTreeWalker;
54 import org.apache.sshd.common.util.ThreadUtils;
55 import org.apache.sshd.server.PasswordAuthenticator;
56 import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
57 import org.apache.sshd.server.session.ServerSession;
58 import org.opendaylight.controller.netconf.api.Capability;
59 import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
60 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
61 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
62 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcherImpl;
63 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
64 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
65 import org.opendaylight.controller.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
66 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
67 import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringActivator;
68 import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringOperationService;
69 import org.opendaylight.controller.netconf.ssh.SshProxyServer;
70 import org.opendaylight.controller.netconf.ssh.SshProxyServerConfiguration;
71 import org.opendaylight.controller.netconf.ssh.SshProxyServerConfigurationBuilder;
72 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
73 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
74 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
75 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
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     private SchemaContext schemaContext;
103
104     private boolean sendFakeSchema = false;
105
106     public NetconfDeviceSimulator() {
107         // TODO make pool size configurable
108         this(new NioEventLoopGroup(), new HashedWheelTimer(),
109                 Executors.newScheduledThreadPool(8, new ThreadFactoryBuilder().setNameFormat("netconf-ssh-server-mina-timers-%d").build()),
110                 ThreadUtils.newFixedThreadPool("netconf-ssh-server-nio-group", 8));
111     }
112
113     private NetconfDeviceSimulator(final NioEventLoopGroup eventExecutors, final HashedWheelTimer hashedWheelTimer, final ScheduledExecutorService minaTimerExecutor, final ExecutorService nioExecutor) {
114         this.nettyThreadgroup = eventExecutors;
115         this.hashedWheelTimer = hashedWheelTimer;
116         this.minaTimerExecutor = minaTimerExecutor;
117         this.nioExecutor = nioExecutor;
118     }
119
120     private NetconfServerDispatcherImpl createDispatcher(final Map<ModuleBuilder, String> moduleBuilders, final boolean exi, final int generateConfigsTimeout, final Optional<File> notificationsFile, final boolean mdSal) {
121
122         final Set<Capability> capabilities = Sets.newHashSet(Collections2.transform(moduleBuilders.keySet(), new Function<ModuleBuilder, Capability>() {
123             @Override
124             public Capability apply(final ModuleBuilder input) {
125                 if (sendFakeSchema) {
126                     sendFakeSchema = false;
127                     return new FakeModuleBuilderCapability(input, moduleBuilders.get(input));
128                 } else {
129                     return new ModuleBuilderCapability(input, moduleBuilders.get(input));
130                 }
131             }
132         }));
133
134         final SessionIdProvider idProvider = new SessionIdProvider();
135
136         final AggregatedNetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory = new AggregatedNetconfOperationServiceFactory();
137         final NetconfOperationServiceFactory operationProvider = mdSal ? new MdsalOperationProvider(idProvider, capabilities, schemaContext) :
138                 new SimulatedOperationProvider(idProvider, capabilities, notificationsFile);
139
140         final NetconfMonitoringService monitoringService1 = new DummyMonitoringService(capabilities);
141
142         final NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory monitoringService =
143                 new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(
144                         new NetconfMonitoringOperationService(monitoringService1));
145         aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(operationProvider);
146         aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(monitoringService);
147
148         final DefaultCommitNotificationProducer commitNotifier = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
149
150         final Set<String> serverCapabilities = exi
151                 ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES
152                 : Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0, XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
153
154         final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
155                 hashedWheelTimer, aggregatedNetconfOperationServiceFactory, idProvider, generateConfigsTimeout, commitNotifier, monitoringService1, serverCapabilities);
156
157         final NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(
158                 serverNegotiatorFactory);
159         return new NetconfServerDispatcherImpl(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
160     }
161
162     private Map<ModuleBuilder, String> toModuleBuilders(final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> sources) {
163         final Map<SourceIdentifier, ParserRuleContext> asts = Maps.transformValues(sources, new Function<Map.Entry<ASTSchemaSource, YangTextSchemaSource>, ParserRuleContext>() {
164             @Override
165             public ParserRuleContext apply(final Map.Entry<ASTSchemaSource, YangTextSchemaSource> input) {
166                 return input.getKey().getAST();
167             }
168         });
169         final Map<String, NavigableMap<Date, URI>> namespaceContext = BuilderUtils.createYangNamespaceContext(
170                 asts.values(), Optional.<SchemaContext>absent());
171
172         final ParseTreeWalker walker = new ParseTreeWalker();
173         final Map<ModuleBuilder, String> sourceToBuilder = new HashMap<>();
174
175         for (final Map.Entry<SourceIdentifier, ParserRuleContext> entry : asts.entrySet()) {
176             final ModuleBuilder moduleBuilder = YangParserListenerImpl.create(namespaceContext, entry.getKey().getName(),
177                     walker, entry.getValue()).getModuleBuilder();
178
179             try(InputStreamReader stream = new InputStreamReader(sources.get(entry.getKey()).getValue().openStream(), Charsets.UTF_8)) {
180                 sourceToBuilder.put(moduleBuilder, CharStreams.toString(stream));
181             } catch (final IOException e) {
182                 throw new RuntimeException(e);
183             }
184         }
185
186         return sourceToBuilder;
187     }
188
189
190     public List<Integer> start(final Main.Params params) {
191         LOG.info("Starting {}, {} simulated devices starting on port {}", params.deviceCount, params.ssh ? "SSH" : "TCP", params.startingPort);
192
193         final Map<ModuleBuilder, String> moduleBuilders = parseSchemasToModuleBuilders(params);
194
195         final NetconfServerDispatcherImpl dispatcher = createDispatcher(moduleBuilders, params.exi, params.generateConfigsTimeout, Optional.fromNullable(params.notificationFile), params.mdSal);
196
197         int currentPort = params.startingPort;
198
199         final List<Integer> openDevices = Lists.newArrayList();
200
201         // Generate key to temp folder
202         final PEMGeneratorHostKeyProvider keyPairProvider = getPemGeneratorHostKeyProvider();
203
204         for (int i = 0; i < params.deviceCount; i++) {
205             if (currentPort > 65535) {
206                 LOG.warn("Port cannot be greater than 65535, stopping further attempts.");
207                 break;
208             }
209             final InetSocketAddress address = getAddress(currentPort);
210
211             final ChannelFuture server;
212             if(params.ssh) {
213                 final InetSocketAddress bindingAddress = InetSocketAddress.createUnresolved("0.0.0.0", currentPort);
214                 final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());
215
216                 server = dispatcher.createLocalServer(tcpLocalAddress);
217                 try {
218                     final SshProxyServer sshServer = new SshProxyServer(minaTimerExecutor, nettyThreadgroup, nioExecutor);
219                     sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress, keyPairProvider));
220                     sshWrappers.add(sshServer);
221                 } catch (final BindException e) {
222                     LOG.warn("Cannot start simulated device on {}, port already in use. Skipping.", address);
223                     // Close local server and continue
224                     server.cancel(true);
225                     if(server.isDone()) {
226                         server.channel().close();
227                     }
228                     continue;
229                 } catch (final IOException e) {
230                     LOG.warn("Cannot start simulated device on {} due to IOException.", address, e);
231                     break;
232                 } finally {
233                     currentPort++;
234                 }
235
236                 try {
237                     server.get();
238                 } catch (final InterruptedException e) {
239                     throw new RuntimeException(e);
240                 } catch (final ExecutionException e) {
241                     LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
242                     continue;
243                 }
244
245                 LOG.debug("Simulated SSH device started on {}", address);
246
247             } else {
248                 server = dispatcher.createServer(address);
249                 currentPort++;
250
251                 try {
252                     server.get();
253                 } catch (final InterruptedException e) {
254                     throw new RuntimeException(e);
255                 } catch (final ExecutionException e) {
256                     LOG.warn("Cannot start tcp simulated device on {}, skipping", address, e);
257                     continue;
258                 }
259
260                 LOG.debug("Simulated TCP device started on {}", address);
261             }
262
263             devicesChannels.add(server.channel());
264             openDevices.add(currentPort - 1);
265         }
266
267         if(openDevices.size() == params.deviceCount) {
268             LOG.info("All simulated devices started successfully from port {} to {}", params.startingPort, currentPort - 1);
269         } else if (openDevices.size() == 0) {
270             LOG.warn("No simulated devices started.");
271         } else {
272             LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
273         }
274
275         return openDevices;
276     }
277
278     private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress, final LocalAddress tcpLocalAddress, final PEMGeneratorHostKeyProvider keyPairProvider) throws IOException {
279         return new SshProxyServerConfigurationBuilder()
280                 .setBindingAddress(bindingAddress)
281                 .setLocalAddress(tcpLocalAddress)
282                 .setAuthenticator(new PasswordAuthenticator() {
283                     @Override
284                     public boolean authenticate(final String username, final String password, final ServerSession session) {
285                         return true;
286                     }
287                 })
288                 .setKeyPairProvider(keyPairProvider)
289                 .setIdleTimeout(Integer.MAX_VALUE)
290                 .createSshProxyServerConfiguration();
291     }
292
293     private PEMGeneratorHostKeyProvider getPemGeneratorHostKeyProvider() {
294         try {
295             final Path tempFile = Files.createTempFile("tempKeyNetconfTest", "suffix");
296             return new PEMGeneratorHostKeyProvider(tempFile.toAbsolutePath().toString());
297         } catch (final IOException e) {
298             LOG.error("Unable to generate PEM key", e);
299             throw new RuntimeException(e);
300         }
301     }
302
303     private Map<ModuleBuilder, String> parseSchemasToModuleBuilders(final Main.Params params) {
304         final SharedSchemaRepository consumer = new SharedSchemaRepository("netconf-simulator");
305         consumer.registerSchemaSourceListener(TextToASTTransformer.create(consumer, consumer));
306
307         final Set<SourceIdentifier> loadedSources = Sets.newHashSet();
308
309         consumer.registerSchemaSourceListener(new SchemaSourceListener() {
310             @Override
311             public void schemaSourceEncountered(final SchemaSourceRepresentation schemaSourceRepresentation) {}
312
313             @Override
314             public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> potentialSchemaSources) {
315                 for (final PotentialSchemaSource<?> potentialSchemaSource : potentialSchemaSources) {
316                     loadedSources.add(potentialSchemaSource.getSourceIdentifier());
317                 }
318             }
319
320             @Override
321             public void schemaSourceUnregistered(final PotentialSchemaSource<?> potentialSchemaSource) {}
322         });
323
324         if(params.schemasDir != null) {
325             final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(consumer, YangTextSchemaSource.class, params.schemasDir);
326             consumer.registerSchemaSourceListener(cache);
327         }
328
329         addDefaultSchemas(consumer);
330
331         final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> asts = Maps.newHashMap();
332
333         try {
334             //necessary for creating mdsal datastores and operations
335             schemaContext = consumer.createSchemaContextFactory(
336                 SchemaSourceFilter.ALWAYS_ACCEPT)
337                 .createSchemaContext(loadedSources).checkedGet();
338         } catch (final SchemaResolutionException e) {
339             throw new RuntimeException("Cannot parse schema context", e);
340         }
341
342         for (final SourceIdentifier loadedSource : loadedSources) {
343             try {
344                 final CheckedFuture<ASTSchemaSource, SchemaSourceException> ast = consumer.getSchemaSource(loadedSource, ASTSchemaSource.class);
345                 final CheckedFuture<YangTextSchemaSource, SchemaSourceException> text = consumer.getSchemaSource(loadedSource, YangTextSchemaSource.class);
346                 asts.put(loadedSource, new AbstractMap.SimpleEntry<>(ast.get(), text.get()));
347             } catch (final InterruptedException e) {
348                 throw new RuntimeException(e);
349             } catch (final ExecutionException e) {
350                 throw new RuntimeException("Cannot parse schema context", e);
351             }
352         }
353         return toModuleBuilders(asts);
354     }
355
356     private void addDefaultSchemas(final SharedSchemaRepository consumer) {
357         SourceIdentifier sId = new SourceIdentifier("ietf-netconf-monitoring", "2010-10-04");
358         registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring.yang", sId);
359
360         sId = new SourceIdentifier("ietf-netconf-monitoring-extension", "2013-12-10");
361         registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring-extension.yang", sId);
362
363         sId = new SourceIdentifier("ietf-yang-types", "2010-09-24");
364         registerSource(consumer, "/META-INF/yang/ietf-yang-types.yang", sId);
365
366         sId = new SourceIdentifier("ietf-inet-types", "2010-09-24");
367         registerSource(consumer, "/META-INF/yang/ietf-inet-types.yang", sId);
368     }
369
370     private void registerSource(final SharedSchemaRepository consumer, final String resource, final SourceIdentifier sourceId) {
371         consumer.registerSchemaSource(new SchemaSourceProvider<SchemaSourceRepresentation>() {
372             @Override
373             public CheckedFuture<? extends SchemaSourceRepresentation, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
374                 return Futures.immediateCheckedFuture(new YangTextSchemaSource(sourceId) {
375                     @Override
376                     protected MoreObjects.ToStringHelper addToStringAttributes(final MoreObjects.ToStringHelper toStringHelper) {
377                         return toStringHelper;
378                     }
379
380                     @Override
381                     public InputStream openStream() throws IOException {
382                         return getClass().getResourceAsStream(resource);
383                     }
384                 });
385             }
386         }, PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
387     }
388
389     private static InetSocketAddress getAddress(final int port) {
390         try {
391             // TODO make address configurable
392             return new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), port);
393         } catch (final UnknownHostException e) {
394             throw new RuntimeException(e);
395         }
396     }
397
398     @Override
399     public void close() {
400         for (final SshProxyServer sshWrapper : sshWrappers) {
401             sshWrapper.close();
402         }
403         for (final Channel deviceCh : devicesChannels) {
404             deviceCh.close();
405         }
406         nettyThreadgroup.shutdownGracefully();
407         minaTimerExecutor.shutdownNow();
408         nioExecutor.shutdownNow();
409         // close Everything
410     }
411
412 }