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