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