Fix yang source provisioning from MD-SAL netconf northbound
[netconf.git] / opendaylight / netconf / tools / netconf-testtool / src / main / java / org / opendaylight / 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.netconf.test.tool;
10
11 import com.google.common.base.Function;
12 import com.google.common.base.MoreObjects;
13 import com.google.common.base.Optional;
14 import com.google.common.collect.Collections2;
15 import com.google.common.collect.Lists;
16 import com.google.common.collect.Sets;
17 import com.google.common.util.concurrent.CheckedFuture;
18 import com.google.common.util.concurrent.Futures;
19 import com.google.common.util.concurrent.ThreadFactoryBuilder;
20 import io.netty.channel.Channel;
21 import io.netty.channel.ChannelFuture;
22 import io.netty.channel.local.LocalAddress;
23 import io.netty.channel.nio.NioEventLoopGroup;
24 import io.netty.util.HashedWheelTimer;
25 import java.io.Closeable;
26 import java.io.File;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.net.BindException;
30 import java.net.Inet4Address;
31 import java.net.InetSocketAddress;
32 import java.net.UnknownHostException;
33 import java.nio.file.Files;
34 import java.nio.file.Path;
35 import java.util.List;
36 import java.util.Set;
37 import java.util.concurrent.ExecutionException;
38 import java.util.concurrent.ExecutorService;
39 import java.util.concurrent.Executors;
40 import java.util.concurrent.ScheduledExecutorService;
41 import org.apache.sshd.common.util.ThreadUtils;
42 import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
43 import org.opendaylight.controller.config.util.capability.BasicCapability;
44 import org.opendaylight.controller.config.util.capability.Capability;
45 import org.opendaylight.controller.config.util.capability.YangModuleCapability;
46 import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
47 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
48 import org.opendaylight.netconf.auth.AuthProvider;
49 import org.opendaylight.netconf.impl.NetconfServerDispatcherImpl;
50 import org.opendaylight.netconf.impl.NetconfServerSessionNegotiatorFactory;
51 import org.opendaylight.netconf.impl.SessionIdProvider;
52 import org.opendaylight.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
53 import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactory;
54 import org.opendaylight.netconf.monitoring.osgi.NetconfMonitoringActivator;
55 import org.opendaylight.netconf.monitoring.osgi.NetconfMonitoringOperationService;
56 import org.opendaylight.netconf.ssh.SshProxyServer;
57 import org.opendaylight.netconf.ssh.SshProxyServerConfiguration;
58 import org.opendaylight.netconf.ssh.SshProxyServerConfigurationBuilder;
59 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
60 import org.opendaylight.yangtools.yang.model.api.Module;
61 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
62 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
63 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
64 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
65 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
66 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
67 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
68 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
69 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
70 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
71 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
72 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
73 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
76
77 public class NetconfDeviceSimulator implements Closeable {
78
79     private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSimulator.class);
80
81     private final NioEventLoopGroup nettyThreadgroup;
82     private final HashedWheelTimer hashedWheelTimer;
83     private final List<Channel> devicesChannels = Lists.newArrayList();
84     private final List<SshProxyServer> sshWrappers = Lists.newArrayList();
85     private final ScheduledExecutorService minaTimerExecutor;
86     private final ExecutorService nioExecutor;
87     private SchemaContext schemaContext;
88
89     private boolean sendFakeSchema = false;
90
91     public NetconfDeviceSimulator() {
92         // TODO make pool size configurable
93         this(new NioEventLoopGroup(), new HashedWheelTimer(),
94                 Executors.newScheduledThreadPool(8, new ThreadFactoryBuilder().setNameFormat("netconf-ssh-server-mina-timers-%d").build()),
95                 ThreadUtils.newFixedThreadPool("netconf-ssh-server-nio-group", 8));
96     }
97
98     private NetconfDeviceSimulator(final NioEventLoopGroup eventExecutors, final HashedWheelTimer hashedWheelTimer, final ScheduledExecutorService minaTimerExecutor, final ExecutorService nioExecutor) {
99         this.nettyThreadgroup = eventExecutors;
100         this.hashedWheelTimer = hashedWheelTimer;
101         this.minaTimerExecutor = minaTimerExecutor;
102         this.nioExecutor = nioExecutor;
103     }
104
105     private NetconfServerDispatcherImpl createDispatcher(final Set<Capability> capabilities, final boolean exi, final int generateConfigsTimeout,
106                                                          final Optional<File> notificationsFile, final boolean mdSal, final Optional<File> initialConfigXMLFile,
107                                                          final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
108
109         final Set<Capability> transformedCapabilities = Sets.newHashSet(Collections2.transform(capabilities, new Function<Capability, Capability>() {
110             @Override
111             public Capability apply(final Capability input) {
112                 if (sendFakeSchema) {
113                     sendFakeSchema = false;
114                     return new FakeCapability((YangModuleCapability) input);
115                 } else {
116                     return input;
117                 }
118             }
119         }));
120
121         final SessionIdProvider idProvider = new SessionIdProvider();
122
123         final AggregatedNetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory = new AggregatedNetconfOperationServiceFactory();
124         final NetconfOperationServiceFactory operationProvider = mdSal ? new MdsalOperationProvider(idProvider, transformedCapabilities, schemaContext, sourceProvider) :
125             new SimulatedOperationProvider(idProvider, transformedCapabilities, notificationsFile, initialConfigXMLFile);
126
127         transformedCapabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0"));
128
129         final NetconfMonitoringService monitoringService1 = new DummyMonitoringService(transformedCapabilities);
130
131         final NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory monitoringService =
132                 new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(
133                         new NetconfMonitoringOperationService(monitoringService1));
134         aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(operationProvider);
135         aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(monitoringService);
136
137         final Set<String> serverCapabilities = exi
138                 ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES
139                 : Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0, XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
140
141         final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new TesttoolNegotiationFactory(
142                 hashedWheelTimer, aggregatedNetconfOperationServiceFactory, idProvider, generateConfigsTimeout, monitoringService1, serverCapabilities);
143
144         final NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(
145                 serverNegotiatorFactory);
146         return new NetconfServerDispatcherImpl(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
147     }
148
149     public List<Integer> start(final Main.Params params) {
150         LOG.info("Starting {}, {} simulated devices starting on port {}", params.deviceCount, params.ssh ? "SSH" : "TCP", params.startingPort);
151
152         final SharedSchemaRepository schemaRepo = new SharedSchemaRepository("netconf-simulator");
153         final Set<Capability> capabilities = parseSchemasToModuleCapabilities(params, schemaRepo);
154
155         final NetconfServerDispatcherImpl dispatcher = createDispatcher(capabilities, params.exi, params.generateConfigsTimeout,
156                 Optional.fromNullable(params.notificationFile), params.mdSal, Optional.fromNullable(params.initialConfigXMLFile),
157                 new SchemaSourceProvider<YangTextSchemaSource>() {
158                     @Override
159                     public CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
160                         return schemaRepo.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class);
161                     }
162                 });
163
164         int currentPort = params.startingPort;
165
166         final List<Integer> openDevices = Lists.newArrayList();
167
168         // Generate key to temp folder
169         final PEMGeneratorHostKeyProvider keyPairProvider = getPemGeneratorHostKeyProvider();
170
171         for (int i = 0; i < params.deviceCount; i++) {
172             if (currentPort > 65535) {
173                 LOG.warn("Port cannot be greater than 65535, stopping further attempts.");
174                 break;
175             }
176             final InetSocketAddress address = getAddress(currentPort);
177
178             final ChannelFuture server;
179             if(params.ssh) {
180                 final InetSocketAddress bindingAddress = InetSocketAddress.createUnresolved("0.0.0.0", currentPort);
181                 final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());
182
183                 server = dispatcher.createLocalServer(tcpLocalAddress);
184                 try {
185                     final SshProxyServer sshServer = new SshProxyServer(minaTimerExecutor, nettyThreadgroup, nioExecutor);
186                     sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress, keyPairProvider));
187                     sshWrappers.add(sshServer);
188                 } catch (final BindException e) {
189                     LOG.warn("Cannot start simulated device on {}, port already in use. Skipping.", address);
190                     // Close local server and continue
191                     server.cancel(true);
192                     if(server.isDone()) {
193                         server.channel().close();
194                     }
195                     continue;
196                 } catch (final IOException e) {
197                     LOG.warn("Cannot start simulated device on {} due to IOException.", address, e);
198                     break;
199                 } finally {
200                     currentPort++;
201                 }
202
203                 try {
204                     server.get();
205                 } catch (final InterruptedException e) {
206                     throw new RuntimeException(e);
207                 } catch (final ExecutionException e) {
208                     LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
209                     continue;
210                 }
211
212                 LOG.debug("Simulated SSH device started on {}", address);
213
214             } else {
215                 server = dispatcher.createServer(address);
216                 currentPort++;
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 tcp simulated device on {}, skipping", address, e);
224                     continue;
225                 }
226
227                 LOG.debug("Simulated TCP device started on {}", address);
228             }
229
230             devicesChannels.add(server.channel());
231             openDevices.add(currentPort - 1);
232         }
233
234         if(openDevices.size() == params.deviceCount) {
235             LOG.info("All simulated devices started successfully from port {} to {}", params.startingPort, currentPort - 1);
236         } else if (openDevices.size() == 0) {
237             LOG.warn("No simulated devices started.");
238         } else {
239             LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
240         }
241
242         return openDevices;
243     }
244
245     private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress, final LocalAddress tcpLocalAddress, final PEMGeneratorHostKeyProvider keyPairProvider) throws IOException {
246         return new SshProxyServerConfigurationBuilder()
247                 .setBindingAddress(bindingAddress)
248                 .setLocalAddress(tcpLocalAddress)
249                 .setAuthenticator(new AuthProvider() {
250                     @Override
251                     public boolean authenticated(final String username, final String password) {
252                         return true;
253                     }
254                 })
255                 .setKeyPairProvider(keyPairProvider)
256                 .setIdleTimeout(Integer.MAX_VALUE)
257                 .createSshProxyServerConfiguration();
258     }
259
260     private PEMGeneratorHostKeyProvider getPemGeneratorHostKeyProvider() {
261         try {
262             final Path tempFile = Files.createTempFile("tempKeyNetconfTest", "suffix");
263             return new PEMGeneratorHostKeyProvider(tempFile.toAbsolutePath().toString());
264         } catch (final IOException e) {
265             LOG.error("Unable to generate PEM key", e);
266             throw new RuntimeException(e);
267         }
268     }
269
270     private Set<Capability> parseSchemasToModuleCapabilities(final Main.Params params, final SharedSchemaRepository consumer) {
271         final Set<SourceIdentifier> loadedSources = Sets.newHashSet();
272
273         consumer.registerSchemaSourceListener(TextToASTTransformer.create(consumer, consumer));
274
275         consumer.registerSchemaSourceListener(new SchemaSourceListener() {
276             @Override
277             public void schemaSourceEncountered(final SchemaSourceRepresentation schemaSourceRepresentation) {}
278
279             @Override
280             public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> potentialSchemaSources) {
281                 for (final PotentialSchemaSource<?> potentialSchemaSource : potentialSchemaSources) {
282                     loadedSources.add(potentialSchemaSource.getSourceIdentifier());
283                 }
284             }
285
286             @Override
287             public void schemaSourceUnregistered(final PotentialSchemaSource<?> potentialSchemaSource) {}
288         });
289
290         if(params.schemasDir != null) {
291             final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(consumer, YangTextSchemaSource.class, params.schemasDir);
292             consumer.registerSchemaSourceListener(cache);
293         }
294
295         addDefaultSchemas(consumer);
296
297         try {
298             //necessary for creating mdsal data stores and operations
299             this.schemaContext = consumer.createSchemaContextFactory(
300                 SchemaSourceFilter.ALWAYS_ACCEPT)
301                 .createSchemaContext(loadedSources).checkedGet();
302         } catch (final SchemaResolutionException e) {
303             throw new RuntimeException("Cannot parse schema context", e);
304         }
305
306         final Set<Capability> capabilities = Sets.newHashSet();
307
308         for (final Module module : schemaContext.getModules()) {
309             for (final Module subModule : module.getSubmodules()) {
310                 addModuleCapability(consumer, capabilities, subModule);
311             }
312             addModuleCapability(consumer, capabilities, module);
313         }
314         return capabilities;
315     }
316
317     private void addModuleCapability(SharedSchemaRepository consumer, Set<Capability> capabilities, Module module) {
318         final SourceIdentifier moduleSourceIdentifier = SourceIdentifier.create(module.getName(),
319                 (SimpleDateFormatUtil.DEFAULT_DATE_REV == module.getRevision() ? Optional.<String>absent() :
320                         Optional.of(SimpleDateFormatUtil.getRevisionFormat().format(module.getRevision()))));
321         try {
322             String moduleContent = new String(consumer.getSchemaSource(moduleSourceIdentifier, YangTextSchemaSource.class)
323                     .checkedGet().read());
324             capabilities.add(new YangModuleCapability(module, moduleContent));
325             //IOException would be thrown in creating SchemaContext already
326         } catch (SchemaSourceException |IOException e) {
327             throw new RuntimeException("Cannot retrieve schema source for module " + moduleSourceIdentifier.toString() + " from schema repository", e);
328         }
329     }
330
331     private void addDefaultSchemas(final SharedSchemaRepository consumer) {
332         SourceIdentifier sId = new SourceIdentifier("ietf-netconf-monitoring", "2010-10-04");
333         registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring.yang", sId);
334
335         sId = new SourceIdentifier("ietf-netconf-monitoring-extension", "2013-12-10");
336         registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring-extension.yang", sId);
337
338         sId = new SourceIdentifier("ietf-yang-types", "2010-09-24");
339         registerSource(consumer, "/META-INF/yang/ietf-yang-types.yang", sId);
340
341         sId = new SourceIdentifier("ietf-inet-types", "2010-09-24");
342         registerSource(consumer, "/META-INF/yang/ietf-inet-types.yang", sId);
343     }
344
345     private void registerSource(final SharedSchemaRepository consumer, final String resource, final SourceIdentifier sourceId) {
346         consumer.registerSchemaSource(new SchemaSourceProvider<SchemaSourceRepresentation>() {
347             @Override
348             public CheckedFuture<? extends SchemaSourceRepresentation, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
349                 return Futures.immediateCheckedFuture(new YangTextSchemaSource(sourceId) {
350                     @Override
351                     protected MoreObjects.ToStringHelper addToStringAttributes(final MoreObjects.ToStringHelper toStringHelper) {
352                         return toStringHelper;
353                     }
354
355                     @Override
356                     public InputStream openStream() throws IOException {
357                         return getClass().getResourceAsStream(resource);
358                     }
359                 });
360             }
361         }, PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
362     }
363
364     private static InetSocketAddress getAddress(final int port) {
365         try {
366             // TODO make address configurable
367             return new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), port);
368         } catch (final UnknownHostException e) {
369             throw new RuntimeException(e);
370         }
371     }
372
373     @Override
374     public void close() {
375         for (final SshProxyServer sshWrapper : sshWrappers) {
376             sshWrapper.close();
377         }
378         for (final Channel deviceCh : devicesChannels) {
379             deviceCh.close();
380         }
381         nettyThreadgroup.shutdownGracefully();
382         minaTimerExecutor.shutdownNow();
383         nioExecutor.shutdownNow();
384         // close Everything
385     }
386 }