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