Merge "Incorrect name of elements in yang case nodes"
[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.Optional;
14 import com.google.common.collect.Collections2;
15 import com.google.common.collect.Lists;
16 import com.google.common.collect.Maps;
17 import com.google.common.collect.Sets;
18 import com.google.common.io.CharStreams;
19 import com.google.common.util.concurrent.CheckedFuture;
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.IOException;
27 import java.io.InputStreamReader;
28 import java.lang.management.ManagementFactory;
29 import java.net.Inet4Address;
30 import java.net.InetSocketAddress;
31 import java.net.URI;
32 import java.net.UnknownHostException;
33 import java.util.AbstractMap;
34 import java.util.Date;
35 import java.util.HashMap;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.Set;
39 import java.util.TreeMap;
40 import java.util.concurrent.ExecutionException;
41 import org.antlr.v4.runtime.ParserRuleContext;
42 import org.antlr.v4.runtime.tree.ParseTreeWalker;
43 import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession;
44 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
45 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
46 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
47 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
48 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
49 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
50 import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
51 import org.opendaylight.controller.netconf.mapping.api.Capability;
52 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
53 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
54 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
55 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceSnapshot;
56 import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringOperationService;
57 import org.opendaylight.controller.netconf.ssh.NetconfSSHServer;
58 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
59 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
60 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
61 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
62 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
63 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
64 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
65 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
66 import org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils;
67 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
68 import org.opendaylight.yangtools.yang.parser.impl.YangParserListenerImpl;
69 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
70 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
71 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
74
75 public class NetconfDeviceSimulator implements Closeable {
76
77     private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSimulator.class);
78
79     public static final int CONNECTION_TIMEOUT_MILLIS = 20000;
80
81     private final NioEventLoopGroup nettyThreadgroup;
82     private final HashedWheelTimer hashedWheelTimer;
83     private final List<Channel> devicesChannels = Lists.newArrayList();
84
85     public NetconfDeviceSimulator() {
86         this(new NioEventLoopGroup(), new HashedWheelTimer());
87     }
88
89     public NetconfDeviceSimulator(final NioEventLoopGroup eventExecutors, final HashedWheelTimer hashedWheelTimer) {
90         this.nettyThreadgroup = eventExecutors;
91         this.hashedWheelTimer = hashedWheelTimer;
92     }
93
94     private NetconfServerDispatcher createDispatcher(final Map<ModuleBuilder, String> moduleBuilders, final boolean exi) {
95
96         final Set<Capability> capabilities = Sets.newHashSet(Collections2.transform(moduleBuilders.keySet(), new Function<ModuleBuilder, Capability>() {
97             @Override
98             public Capability apply(final ModuleBuilder input) {
99                 return new ModuleBuilderCapability(input, moduleBuilders.get(input));
100             }
101         }));
102
103         final SessionIdProvider idProvider = new SessionIdProvider();
104
105         final SimulatedOperationProvider simulatedOperationProvider = new SimulatedOperationProvider(idProvider, capabilities);
106         final NetconfMonitoringOperationService monitoringService = new NetconfMonitoringOperationService(new NetconfMonitoringServiceImpl(simulatedOperationProvider));
107         simulatedOperationProvider.addService(monitoringService);
108
109         final DefaultCommitNotificationProducer commitNotifier = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
110
111         final Set<String> serverCapabilities = exi
112                 ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES
113                 : Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0, XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
114
115         final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
116                 hashedWheelTimer, simulatedOperationProvider, idProvider, CONNECTION_TIMEOUT_MILLIS, commitNotifier, new LoggingMonitoringService(), serverCapabilities);
117
118         final NetconfServerDispatcher.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerChannelInitializer(
119                 serverNegotiatorFactory);
120         return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
121     }
122
123     private Map<ModuleBuilder, String> toModuleBuilders(final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> sources) {
124             final Map<SourceIdentifier, ParserRuleContext> asts = Maps.transformValues(sources,  new Function<Map.Entry<ASTSchemaSource, YangTextSchemaSource>, ParserRuleContext>() {
125                 @Override
126                 public ParserRuleContext apply(final Map.Entry<ASTSchemaSource, YangTextSchemaSource> input) {
127                     return input.getKey().getAST();
128                 }
129             });
130             final Map<String, TreeMap<Date, URI>> namespaceContext = BuilderUtils.createYangNamespaceContext(
131                     asts.values(), Optional.<SchemaContext>absent());
132
133             final ParseTreeWalker walker = new ParseTreeWalker();
134             final Map<ModuleBuilder, String> sourceToBuilder = new HashMap<>();
135
136             for (final Map.Entry<SourceIdentifier, ParserRuleContext> entry : asts.entrySet()) {
137                 final ModuleBuilder moduleBuilder = YangParserListenerImpl.create(namespaceContext, entry.getKey().getName(),
138                         walker, entry.getValue()).getModuleBuilder();
139
140                 try(InputStreamReader stream = new InputStreamReader(sources.get(entry.getKey()).getValue().openStream(), Charsets.UTF_8)) {
141                     sourceToBuilder.put(moduleBuilder, CharStreams.toString(stream));
142                 } catch (final IOException e) {
143                     throw new RuntimeException(e);
144                 }
145             }
146
147             return sourceToBuilder;
148         }
149
150
151     public List<Integer> start(final Main.Params params) {
152         final Map<ModuleBuilder, String> moduleBuilders = parseSchemasToModuleBuilders(params);
153
154         final NetconfServerDispatcher dispatcher = createDispatcher(moduleBuilders, params.exi);
155
156         int currentPort = params.startingPort;
157
158         final List<Integer> openDevices = Lists.newArrayList();
159         for (int i = 0; i < params.deviceCount; i++) {
160             final InetSocketAddress address = getAddress(currentPort);
161
162             final ChannelFuture server;
163             if(params.ssh) {
164                 final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());
165
166                 server = dispatcher.createLocalServer(tcpLocalAddress);
167                 try {
168                     NetconfSSHServer.start(currentPort, tcpLocalAddress, new AcceptingAuthProvider(), nettyThreadgroup);
169                 } catch (final Exception e) {
170                     LOG.warn("Cannot start simulated device on {}, skipping", address, e);
171                     // Close local server and continue
172                     server.cancel(true);
173                     if(server.isDone()) {
174                         server.channel().close();
175                     }
176                     continue;
177                 } finally {
178                     currentPort++;
179                 }
180
181                 try {
182                     server.get();
183                 } catch (final InterruptedException e) {
184                     throw new RuntimeException(e);
185                 } catch (final ExecutionException e) {
186                     LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
187                     continue;
188                 }
189
190                 LOG.debug("Simulated SSH device started on {}", address);
191
192             } else {
193                 server = dispatcher.createServer(address);
194                 currentPort++;
195
196                 try {
197                     server.get();
198                 } catch (final InterruptedException e) {
199                     throw new RuntimeException(e);
200                 } catch (final ExecutionException e) {
201                     LOG.warn("Cannot start tcp simulated device on {}, skipping", address, e);
202                     continue;
203                 }
204
205                 LOG.debug("Simulated TCP device started on {}", address);
206             }
207
208             devicesChannels.add(server.channel());
209             openDevices.add(currentPort - 1);
210
211         }
212
213         if(openDevices.size() == params.deviceCount) {
214             LOG.info("All simulated devices started successfully from port {} to {}", params.startingPort, currentPort);
215         } else {
216             LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
217         }
218
219         return openDevices;
220     }
221
222     private Map<ModuleBuilder, String> parseSchemasToModuleBuilders(final Main.Params params) {
223         final SharedSchemaRepository consumer = new SharedSchemaRepository("netconf-simulator");
224         consumer.registerSchemaSourceListener(TextToASTTransformer.create(consumer, consumer));
225
226         final Set<SourceIdentifier> loadedSources = Sets.newHashSet();
227
228         consumer.registerSchemaSourceListener(new SchemaSourceListener() {
229             @Override
230             public void schemaSourceEncountered(final SchemaSourceRepresentation schemaSourceRepresentation) {}
231
232             @Override
233             public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> potentialSchemaSources) {
234                 for (final PotentialSchemaSource<?> potentialSchemaSource : potentialSchemaSources) {
235                     loadedSources.add(potentialSchemaSource.getSourceIdentifier());
236                 }
237             }
238
239             @Override
240             public void schemaSourceUnregistered(final PotentialSchemaSource<?> potentialSchemaSource) {}
241         });
242
243         final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(consumer, YangTextSchemaSource.class, params.schemasDir);
244         consumer.registerSchemaSourceListener(cache);
245
246         final Map<SourceIdentifier, Map.Entry<ASTSchemaSource, YangTextSchemaSource>> asts = Maps.newHashMap();
247         for (final SourceIdentifier loadedSource : loadedSources) {
248                 try {
249                     final CheckedFuture<ASTSchemaSource, SchemaSourceException> ast = consumer.getSchemaSource(loadedSource, ASTSchemaSource.class);
250                     final CheckedFuture<YangTextSchemaSource, SchemaSourceException> text = consumer.getSchemaSource(loadedSource, YangTextSchemaSource.class);
251                     asts.put(loadedSource, new AbstractMap.SimpleEntry<>(ast.get(), text.get()));
252                 } catch (final InterruptedException e) {
253                     throw new RuntimeException(e);
254                 } catch (final ExecutionException e) {
255                     throw new RuntimeException("Cannot parse schema context", e);
256                 }
257         }
258         return toModuleBuilders(asts);
259     }
260
261     private static InetSocketAddress getAddress(final int port) {
262         try {
263             // TODO make address configurable
264             return new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), port);
265         } catch (final UnknownHostException e) {
266             throw new RuntimeException(e);
267         }
268     }
269
270     @Override
271     public void close() {
272         for (final Channel deviceCh : devicesChannels) {
273             deviceCh.close();
274         }
275         nettyThreadgroup.shutdownGracefully();
276         // close Everything
277     }
278
279     private static class SimulatedOperationProvider implements NetconfOperationProvider {
280         private final SessionIdProvider idProvider;
281         private final Set<NetconfOperationService> netconfOperationServices;
282
283
284         public SimulatedOperationProvider(final SessionIdProvider idProvider, final Set<Capability> caps) {
285             this.idProvider = idProvider;
286             final SimulatedOperationService simulatedOperationService = new SimulatedOperationService(caps, idProvider.getCurrentSessionId());
287             this.netconfOperationServices = Sets.<NetconfOperationService>newHashSet(simulatedOperationService);
288         }
289
290         @Override
291         public NetconfOperationServiceSnapshot openSnapshot(final String sessionIdForReporting) {
292             return new SimulatedServiceSnapshot(idProvider, netconfOperationServices);
293         }
294
295         public void addService(final NetconfOperationService monitoringService) {
296             netconfOperationServices.add(monitoringService);
297         }
298
299         private static class SimulatedServiceSnapshot implements NetconfOperationServiceSnapshot {
300             private final SessionIdProvider idProvider;
301             private final Set<NetconfOperationService> netconfOperationServices;
302
303             public SimulatedServiceSnapshot(final SessionIdProvider idProvider, final Set<NetconfOperationService> netconfOperationServices) {
304                 this.idProvider = idProvider;
305                 this.netconfOperationServices = netconfOperationServices;
306             }
307
308             @Override
309             public String getNetconfSessionIdForReporting() {
310                 return String.valueOf(idProvider.getCurrentSessionId());
311             }
312
313             @Override
314             public Set<NetconfOperationService> getServices() {
315                 return netconfOperationServices;
316             }
317
318             @Override
319             public void close() throws Exception {}
320         }
321
322         static class SimulatedOperationService implements NetconfOperationService {
323             private final Set<Capability> capabilities;
324             private static SimulatedGet sGet;
325
326             public SimulatedOperationService(final Set<Capability> capabilities, final long currentSessionId) {
327                 this.capabilities = capabilities;
328                 sGet = new SimulatedGet(String.valueOf(currentSessionId));
329             }
330
331             @Override
332             public Set<Capability> getCapabilities() {
333                 return capabilities;
334             }
335
336             @Override
337             public Set<NetconfOperation> getNetconfOperations() {
338                 return Sets.<NetconfOperation>newHashSet(sGet);
339             }
340
341             @Override
342             public void close() {
343             }
344
345         }
346     }
347
348     private class LoggingMonitoringService implements SessionMonitoringService {
349         @Override
350         public void onSessionUp(final NetconfManagementSession session) {
351             LOG.debug("Session {} established", session);
352         }
353
354         @Override
355         public void onSessionDown(final NetconfManagementSession session) {
356             LOG.debug("Session {} down", session);
357         }
358     }
359
360 }