Bug 8153: enforce check-style rules for netconf
[netconf.git] / netconf / tools / netconf-testtool / src / main / java / org / opendaylight / netconf / test / tool / NetconfDeviceSimulator.java
index 23d6750896140857b0dc10b9e6b3d36939edc0e3..6e01531dc775cd5dc2a5b6fb1be1f9b592c7ac9f 100644 (file)
@@ -8,7 +8,6 @@
 
 package org.opendaylight.netconf.test.tool;
 
-import com.google.common.base.Function;
 import com.google.common.base.MoreObjects;
 import com.google.common.base.Optional;
 import com.google.common.collect.Collections2;
@@ -23,7 +22,6 @@ import io.netty.channel.local.LocalAddress;
 import io.netty.channel.nio.NioEventLoopGroup;
 import io.netty.util.HashedWheelTimer;
 import java.io.Closeable;
-import java.io.File;
 import java.io.IOException;
 import java.io.InputStream;
 import java.net.BindException;
@@ -56,9 +54,11 @@ import org.opendaylight.netconf.monitoring.osgi.NetconfMonitoringOperationServic
 import org.opendaylight.netconf.ssh.SshProxyServer;
 import org.opendaylight.netconf.ssh.SshProxyServerConfiguration;
 import org.opendaylight.netconf.ssh.SshProxyServerConfigurationBuilder;
+import org.opendaylight.netconf.test.tool.customrpc.SettableOperationProvider;
 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
@@ -88,78 +88,92 @@ public class NetconfDeviceSimulator implements Closeable {
 
     private boolean sendFakeSchema = false;
 
-    public NetconfDeviceSimulator() {
-        // TODO make pool size configurable
+    public NetconfDeviceSimulator(final int threadPoolSize) {
         this(new NioEventLoopGroup(), new HashedWheelTimer(),
-                Executors.newScheduledThreadPool(8, new ThreadFactoryBuilder().setNameFormat("netconf-ssh-server-mina-timers-%d").build()),
-                ThreadUtils.newFixedThreadPool("netconf-ssh-server-nio-group", 8));
+                Executors.newScheduledThreadPool(threadPoolSize,
+                    new ThreadFactoryBuilder().setNameFormat("netconf-ssh-server-mina-timers-%d").build()),
+                ThreadUtils.newFixedThreadPool("netconf-ssh-server-nio-group", threadPoolSize));
     }
 
-    private NetconfDeviceSimulator(final NioEventLoopGroup eventExecutors, final HashedWheelTimer hashedWheelTimer, final ScheduledExecutorService minaTimerExecutor, final ExecutorService nioExecutor) {
+    private NetconfDeviceSimulator(final NioEventLoopGroup eventExecutors, final HashedWheelTimer hashedWheelTimer,
+            final ScheduledExecutorService minaTimerExecutor, final ExecutorService nioExecutor) {
         this.nettyThreadgroup = eventExecutors;
         this.hashedWheelTimer = hashedWheelTimer;
         this.minaTimerExecutor = minaTimerExecutor;
         this.nioExecutor = nioExecutor;
     }
 
-    private NetconfServerDispatcherImpl createDispatcher(final Set<Capability> capabilities, final boolean exi, final int generateConfigsTimeout,
-                                                         final Optional<File> notificationsFile, final boolean mdSal, final Optional<File> initialConfigXMLFile,
-                                                         final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
+    private NetconfServerDispatcherImpl createDispatcher(final Set<Capability> capabilities,
+            final SchemaSourceProvider<YangTextSchemaSource> sourceProvider, final TesttoolParameters params) {
 
-        final Set<Capability> transformedCapabilities = Sets.newHashSet(Collections2.transform(capabilities, new Function<Capability, Capability>() {
-            @Override
-            public Capability apply(final Capability input) {
-                if (sendFakeSchema) {
-                    sendFakeSchema = false;
-                    return new FakeCapability((YangModuleCapability) input);
-                } else {
-                    return input;
-                }
+        final Set<Capability> transformedCapabilities = Sets.newHashSet(Collections2.transform(capabilities, input -> {
+            if (sendFakeSchema) {
+                sendFakeSchema = false;
+                return new FakeCapability((YangModuleCapability) input);
+            } else {
+                return input;
             }
         }));
-
+        transformedCapabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0"));
+        final NetconfMonitoringService monitoringService1 = new DummyMonitoringService(transformedCapabilities);
         final SessionIdProvider idProvider = new SessionIdProvider();
 
-        final AggregatedNetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory = new AggregatedNetconfOperationServiceFactory();
-        final NetconfOperationServiceFactory operationProvider = mdSal ? new MdsalOperationProvider(idProvider, transformedCapabilities, schemaContext, sourceProvider) :
-            new SimulatedOperationProvider(idProvider, transformedCapabilities, notificationsFile, initialConfigXMLFile);
+        final NetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory = createOperationServiceFactory(
+            sourceProvider, params, transformedCapabilities, monitoringService1, idProvider);
 
-        transformedCapabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0"));
+        final Set<String> serverCapabilities = params.exi
+                ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES
+                : Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
+                    XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
+
+        final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new TesttoolNegotiationFactory(
+                hashedWheelTimer, aggregatedNetconfOperationServiceFactory, idProvider, params.generateConfigsTimeout,
+                monitoringService1, serverCapabilities);
+
+        final NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer =
+            new NetconfServerDispatcherImpl.ServerChannelInitializer(serverNegotiatorFactory);
+        return new NetconfServerDispatcherImpl(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
+    }
+
+    private NetconfOperationServiceFactory createOperationServiceFactory(
+            final SchemaSourceProvider<YangTextSchemaSource> sourceProvider, final TesttoolParameters params,
+            final Set<Capability> transformedCapabilities, final NetconfMonitoringService monitoringService1,
+            final SessionIdProvider idProvider) {
+        final AggregatedNetconfOperationServiceFactory aggregatedNetconfOperationServiceFactory =
+            new AggregatedNetconfOperationServiceFactory();
+
+        final NetconfOperationServiceFactory operationProvider;
+        if (params.mdSal) {
+            operationProvider = new MdsalOperationProvider(
+                idProvider, transformedCapabilities, schemaContext, sourceProvider);
+        } else {
+            operationProvider = new SimulatedOperationProvider(idProvider, transformedCapabilities,
+                    Optional.fromNullable(params.notificationFile),
+                    Optional.fromNullable(params.initialConfigXMLFile));
+        }
 
-        final NetconfMonitoringService monitoringService1 = new DummyMonitoringService(transformedCapabilities);
 
         final NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory monitoringService =
                 new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(
                         new NetconfMonitoringOperationService(monitoringService1));
         aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(operationProvider);
         aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(monitoringService);
-
-        final Set<String> serverCapabilities = exi
-                ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES
-                : Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0, XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
-
-        final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new TesttoolNegotiationFactory(
-                hashedWheelTimer, aggregatedNetconfOperationServiceFactory, idProvider, generateConfigsTimeout, monitoringService1, serverCapabilities);
-
-        final NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(
-                serverNegotiatorFactory);
-        return new NetconfServerDispatcherImpl(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
+        if (params.rpcConfig != null) {
+            final SettableOperationProvider settableService = new SettableOperationProvider(params.rpcConfig);
+            aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(settableService);
+        }
+        return aggregatedNetconfOperationServiceFactory;
     }
 
     public List<Integer> start(final TesttoolParameters params) {
-        LOG.info("Starting {}, {} simulated devices starting on port {}", params.deviceCount, params.ssh ? "SSH" : "TCP", params.startingPort);
+        LOG.info("Starting {}, {} simulated devices starting on port {}",
+            params.deviceCount, params.ssh ? "SSH" : "TCP", params.startingPort);
 
         final SharedSchemaRepository schemaRepo = new SharedSchemaRepository("netconf-simulator");
         final Set<Capability> capabilities = parseSchemasToModuleCapabilities(params, schemaRepo);
 
-        final NetconfServerDispatcherImpl dispatcher = createDispatcher(capabilities, params.exi, params.generateConfigsTimeout,
-                Optional.fromNullable(params.notificationFile), params.mdSal, Optional.fromNullable(params.initialConfigXMLFile),
-                new SchemaSourceProvider<YangTextSchemaSource>() {
-                    @Override
-                    public CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
-                        return schemaRepo.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class);
-                    }
-                });
+        final NetconfServerDispatcherImpl dispatcher = createDispatcher(capabilities,
+            sourceIdentifier -> schemaRepo.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class), params);
 
         int currentPort = params.startingPort;
 
@@ -173,23 +187,24 @@ public class NetconfDeviceSimulator implements Closeable {
                 LOG.warn("Port cannot be greater than 65535, stopping further attempts.");
                 break;
             }
-            final InetSocketAddress address = getAddress(currentPort);
+            final InetSocketAddress address = getAddress(params.ip, currentPort);
 
             final ChannelFuture server;
-            if(params.ssh) {
+            if (params.ssh) {
                 final InetSocketAddress bindingAddress = InetSocketAddress.createUnresolved("0.0.0.0", currentPort);
                 final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());
 
                 server = dispatcher.createLocalServer(tcpLocalAddress);
                 try {
-                    final SshProxyServer sshServer = new SshProxyServer(minaTimerExecutor, nettyThreadgroup, nioExecutor);
+                    final SshProxyServer sshServer = new SshProxyServer(
+                        minaTimerExecutor, nettyThreadgroup, nioExecutor);
                     sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress, keyPairProvider));
                     sshWrappers.add(sshServer);
                 } catch (final BindException e) {
                     LOG.warn("Cannot start simulated device on {}, port already in use. Skipping.", address);
                     // Close local server and continue
                     server.cancel(true);
-                    if(server.isDone()) {
+                    if (server.isDone()) {
                         server.channel().close();
                     }
                     continue;
@@ -231,8 +246,9 @@ public class NetconfDeviceSimulator implements Closeable {
             openDevices.add(currentPort - 1);
         }
 
-        if(openDevices.size() == params.deviceCount) {
-            LOG.info("All simulated devices started successfully from port {} to {}", params.startingPort, currentPort - 1);
+        if (openDevices.size() == params.deviceCount) {
+            LOG.info("All simulated devices started successfully from port {} to {}",
+                params.startingPort, currentPort - 1);
         } else if (openDevices.size() == 0) {
             LOG.warn("No simulated devices started.");
         } else {
@@ -242,7 +258,8 @@ public class NetconfDeviceSimulator implements Closeable {
         return openDevices;
     }
 
-    private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress, final LocalAddress tcpLocalAddress, final PEMGeneratorHostKeyProvider keyPairProvider) throws IOException {
+    private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress,
+            final LocalAddress tcpLocalAddress, final PEMGeneratorHostKeyProvider keyPairProvider) throws IOException {
         return new SshProxyServerConfigurationBuilder()
                 .setBindingAddress(bindingAddress)
                 .setLocalAddress(tcpLocalAddress)
@@ -267,7 +284,8 @@ public class NetconfDeviceSimulator implements Closeable {
         }
     }
 
-    private Set<Capability> parseSchemasToModuleCapabilities(final TesttoolParameters params, final SharedSchemaRepository consumer) {
+    private Set<Capability> parseSchemasToModuleCapabilities(final TesttoolParameters params,
+                                                             final SharedSchemaRepository consumer) {
         final Set<SourceIdentifier> loadedSources = Sets.newHashSet();
 
         consumer.registerSchemaSourceListener(TextToASTTransformer.create(consumer, consumer));
@@ -287,8 +305,9 @@ public class NetconfDeviceSimulator implements Closeable {
             public void schemaSourceUnregistered(final PotentialSchemaSource<?> potentialSchemaSource) {}
         });
 
-        if(params.schemasDir != null) {
-            final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(consumer, YangTextSchemaSource.class, params.schemasDir);
+        if (params.schemasDir != null) {
+            final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(
+                consumer, YangTextSchemaSource.class, params.schemasDir);
             consumer.registerSchemaSourceListener(cache);
         }
 
@@ -314,41 +333,46 @@ public class NetconfDeviceSimulator implements Closeable {
         return capabilities;
     }
 
-    private void addModuleCapability(SharedSchemaRepository consumer, Set<Capability> capabilities, Module module) {
+    private void addModuleCapability(final SharedSchemaRepository consumer, final Set<Capability> capabilities,
+                                     final Module module) {
         final SourceIdentifier moduleSourceIdentifier = SourceIdentifier.create(module.getName(),
-                (SimpleDateFormatUtil.DEFAULT_DATE_REV == module.getRevision() ? Optional.<String>absent() :
-                        Optional.of(SimpleDateFormatUtil.getRevisionFormat().format(module.getRevision()))));
+                (SimpleDateFormatUtil.DEFAULT_DATE_REV == module.getRevision() ? Optional.absent() :
+                        Optional.of(module.getQNameModule().getFormattedRevision())));
         try {
-            String moduleContent = new String(consumer.getSchemaSource(moduleSourceIdentifier, YangTextSchemaSource.class)
-                    .checkedGet().read());
+            final String moduleContent = new String(
+                consumer.getSchemaSource(moduleSourceIdentifier, YangTextSchemaSource.class).checkedGet().read());
             capabilities.add(new YangModuleCapability(module, moduleContent));
             //IOException would be thrown in creating SchemaContext already
-        } catch (SchemaSourceException |IOException e) {
-            throw new RuntimeException("Cannot retrieve schema source for module " + moduleSourceIdentifier.toString() + " from schema repository", e);
+        } catch (SchemaSourceException | IOException e) {
+            throw new RuntimeException("Cannot retrieve schema source for module "
+                + moduleSourceIdentifier.toString() + " from schema repository", e);
         }
     }
 
     private void addDefaultSchemas(final SharedSchemaRepository consumer) {
-        SourceIdentifier sId = new SourceIdentifier("ietf-netconf-monitoring", "2010-10-04");
-        registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring.yang", sId);
+        SourceIdentifier srcId = RevisionSourceIdentifier.create("ietf-netconf-monitoring", "2010-10-04");
+        registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring.yang", srcId);
 
-        sId = new SourceIdentifier("ietf-netconf-monitoring-extension", "2013-12-10");
-        registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring-extension.yang", sId);
+        srcId = RevisionSourceIdentifier.create("ietf-netconf-monitoring-extension", "2013-12-10");
+        registerSource(consumer, "/META-INF/yang/ietf-netconf-monitoring-extension.yang", srcId);
 
-        sId = new SourceIdentifier("ietf-yang-types", "2010-09-24");
-        registerSource(consumer, "/META-INF/yang/ietf-yang-types.yang", sId);
+        srcId = RevisionSourceIdentifier.create("ietf-yang-types", "2013-07-15");
+        registerSource(consumer, "/META-INF/yang/ietf-yang-types@2013-07-15.yang", srcId);
 
-        sId = new SourceIdentifier("ietf-inet-types", "2010-09-24");
-        registerSource(consumer, "/META-INF/yang/ietf-inet-types.yang", sId);
+        srcId = RevisionSourceIdentifier.create("ietf-inet-types", "2013-07-15");
+        registerSource(consumer, "/META-INF/yang/ietf-inet-types@2013-07-15.yang", srcId);
     }
 
-    private void registerSource(final SharedSchemaRepository consumer, final String resource, final SourceIdentifier sourceId) {
+    private void registerSource(final SharedSchemaRepository consumer, final String resource,
+                                final SourceIdentifier sourceId) {
         consumer.registerSchemaSource(new SchemaSourceProvider<SchemaSourceRepresentation>() {
             @Override
-            public CheckedFuture<? extends SchemaSourceRepresentation, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
+            public CheckedFuture<? extends SchemaSourceRepresentation, SchemaSourceException> getSource(
+                    final SourceIdentifier sourceIdentifier) {
                 return Futures.immediateCheckedFuture(new YangTextSchemaSource(sourceId) {
                     @Override
-                    protected MoreObjects.ToStringHelper addToStringAttributes(final MoreObjects.ToStringHelper toStringHelper) {
+                    protected MoreObjects.ToStringHelper addToStringAttributes(
+                            final MoreObjects.ToStringHelper toStringHelper) {
                         return toStringHelper;
                     }
 
@@ -358,13 +382,13 @@ public class NetconfDeviceSimulator implements Closeable {
                     }
                 });
             }
-        }, PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
+        }, PotentialSchemaSource.create(
+            sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.IMMEDIATE.getValue()));
     }
 
-    private static InetSocketAddress getAddress(final int port) {
+    private static InetSocketAddress getAddress(final String ip, final int port) {
         try {
-            // TODO make address configurable
-            return new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), port);
+            return new InetSocketAddress(Inet4Address.getByName(ip), port);
         } catch (final UnknownHostException e) {
             throw new RuntimeException(e);
         }