Search in sources :

Example 1 with ReportGenerator

use of org.apache.jmeter.report.dashboard.ReportGenerator in project jmeter by apache.

the class JMeter method runNonGui.

// run test in batch mode
@SuppressWarnings("JdkObsolete")
void runNonGui(String testFile, String logFile, boolean remoteStart, String remoteHostsString, boolean generateReportDashboard) throws ConfigurationException {
    try {
        File f = new File(testFile);
        if (!f.exists() || !f.isFile()) {
            throw new ConfigurationException("The file " + f.getAbsolutePath() + " doesn't exist or can't be opened");
        }
        FileServer.getFileServer().setBaseForScript(f);
        HashTree tree = SaveService.loadTree(f);
        // Deliberate use of deprecated ctor
        @SuppressWarnings("deprecation") JMeterTreeModel // NOSONAR Create non-GUI version to avoid headless problems
        treeModel = new JMeterTreeModel(new Object());
        JMeterTreeNode root = (JMeterTreeNode) treeModel.getRoot();
        treeModel.addSubTree(tree, root);
        // Hack to resolve ModuleControllers in non GUI mode
        SearchByClass<ReplaceableController> replaceableControllers = new SearchByClass<>(ReplaceableController.class);
        tree.traverse(replaceableControllers);
        Collection<ReplaceableController> replaceableControllersRes = replaceableControllers.getSearchResults();
        for (ReplaceableController replaceableController : replaceableControllersRes) {
            replaceableController.resolveReplacementSubTree(root);
        }
        // Ensure tree is interpreted (ReplaceableControllers are replaced)
        // For GUI runs this is done in Start.java
        HashTree clonedTree = convertSubTree(tree, true);
        Summariser summariser = null;
        // $NON-NLS-1$
        String summariserName = JMeterUtils.getPropDefault("summariser.name", "");
        if (summariserName.length() > 0) {
            log.info("Creating summariser <{}>", summariserName);
            println("Creating summariser <" + summariserName + ">");
            summariser = new Summariser(summariserName);
        }
        ResultCollector resultCollector = null;
        if (logFile != null) {
            resultCollector = new ResultCollector(summariser);
            resultCollector.setFilename(logFile);
            clonedTree.add(clonedTree.getArray()[0], resultCollector);
        } else {
            // only add Summariser if it can not be shared with the ResultCollector
            if (summariser != null) {
                clonedTree.add(clonedTree.getArray()[0], summariser);
            }
        }
        if (deleteResultFile) {
            SearchByClass<ResultCollector> resultListeners = new SearchByClass<>(ResultCollector.class);
            clonedTree.traverse(resultListeners);
            Iterator<ResultCollector> irc = resultListeners.getSearchResults().iterator();
            while (irc.hasNext()) {
                ResultCollector rc = irc.next();
                File resultFile = new File(rc.getFilename());
                if (resultFile.exists() && !resultFile.delete()) {
                    throw new IllegalStateException("Could not delete results file " + resultFile.getAbsolutePath() + "(canRead:" + resultFile.canRead() + ", canWrite:" + resultFile.canWrite() + ")");
                }
            }
        }
        ReportGenerator reportGenerator = null;
        if (logFile != null && generateReportDashboard) {
            reportGenerator = new ReportGenerator(logFile, resultCollector);
        }
        // Used for remote notification of threads start/stop,see BUG 54152
        // Summariser uses this feature to compute correctly number of threads
        // when NON GUI mode is used
        clonedTree.add(clonedTree.getArray()[0], new RemoteThreadsListenerTestElement());
        List<JMeterEngine> engines = new ArrayList<>();
        println("Created the tree successfully using " + testFile);
        if (!remoteStart) {
            JMeterEngine engine = new StandardJMeterEngine();
            clonedTree.add(clonedTree.getArray()[0], new ListenToTest(org.apache.jmeter.JMeter.ListenToTest.RunMode.LOCAL, false, reportGenerator));
            engine.configure(clonedTree);
            long now = System.currentTimeMillis();
            println("Starting standalone test @ " + new Date(now) + " (" + now + ")");
            engines.add(engine);
            engine.runTest();
        } else {
            // $NON-NLS-1$
            java.util.StringTokenizer st = new java.util.StringTokenizer(remoteHostsString.trim(), ",");
            List<String> hosts = new ArrayList<>();
            while (st.hasMoreElements()) {
                hosts.add(((String) st.nextElement()).trim());
            }
            ListenToTest testListener = new ListenToTest(org.apache.jmeter.JMeter.ListenToTest.RunMode.REMOTE, remoteStop, reportGenerator);
            clonedTree.add(clonedTree.getArray()[0], testListener);
            DistributedRunner distributedRunner = new DistributedRunner(this.remoteProps);
            // NOSONAR
            distributedRunner.setStdout(System.out);
            // NOSONAR
            distributedRunner.setStdErr(System.err);
            distributedRunner.init(hosts, clonedTree);
            engines.addAll(distributedRunner.getEngines());
            testListener.setStartedRemoteEngines(engines);
            distributedRunner.start();
        }
        startUdpDdaemon(engines);
    } catch (ConfigurationException e) {
        throw e;
    } catch (Exception e) {
        // NOSONAR
        System.out.println("Error in NonGUIDriver " + e.toString());
        log.error("Error in NonGUIDriver", e);
        throw new ConfigurationException("Error in NonGUIDriver " + e.getMessage(), e);
    }
}
Also used : HashTree(org.apache.jorphan.collections.HashTree) RemoteThreadsListenerTestElement(org.apache.jmeter.threads.RemoteThreadsListenerTestElement) ArrayList(java.util.ArrayList) JMeterTreeModel(org.apache.jmeter.gui.tree.JMeterTreeModel) Summariser(org.apache.jmeter.reporters.Summariser) ReportGenerator(org.apache.jmeter.report.dashboard.ReportGenerator) ConfigurationException(org.apache.jmeter.report.config.ConfigurationException) StringTokenizer(java.util.StringTokenizer) JMeterTreeNode(org.apache.jmeter.gui.tree.JMeterTreeNode) ReplaceableController(org.apache.jmeter.control.ReplaceableController) ResultCollector(org.apache.jmeter.reporters.ResultCollector) StandardJMeterEngine(org.apache.jmeter.engine.StandardJMeterEngine) SearchByClass(org.apache.jorphan.collections.SearchByClass) Date(java.util.Date) ConfigurationException(org.apache.jmeter.report.config.ConfigurationException) ScriptException(javax.script.ScriptException) JMeterException(org.apache.jorphan.util.JMeterException) ConversionException(com.thoughtworks.xstream.converters.ConversionException) SocketException(java.net.SocketException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) MalformedURLException(java.net.MalformedURLException) IllegalUserActionException(org.apache.jmeter.exceptions.IllegalUserActionException) StringTokenizer(java.util.StringTokenizer) JMeterEngine(org.apache.jmeter.engine.JMeterEngine) ClientJMeterEngine(org.apache.jmeter.engine.ClientJMeterEngine) StandardJMeterEngine(org.apache.jmeter.engine.StandardJMeterEngine) DistributedRunner(org.apache.jmeter.engine.DistributedRunner) File(java.io.File)

Example 2 with ReportGenerator

use of org.apache.jmeter.report.dashboard.ReportGenerator in project jmeter by apache.

the class JMeter method start.

/**
 * Takes the command line arguments and uses them to determine how to
 * startup JMeter.
 *
 * Called reflectively by {@link NewDriver#main(String[])}
 * @param args The arguments for JMeter
 */
@SuppressWarnings("JdkObsolete")
public void start(String[] args) {
    CLArgsParser parser = new CLArgsParser(args, options);
    String error = parser.getErrorString();
    if (error == null) {
        // Check option combinations
        boolean gui = parser.getArgumentById(NONGUI_OPT) == null;
        boolean nonGuiOnly = parser.getArgumentById(REMOTE_OPT) != null || parser.getArgumentById(REMOTE_OPT_PARAM) != null || parser.getArgumentById(REMOTE_STOP) != null;
        if (gui && nonGuiOnly) {
            error = "-r and -R and -X are only valid in non-GUI mode";
        }
    }
    if (null != error) {
        // NOSONAR
        System.err.println("Error: " + error);
        // NOSONAR
        System.out.println("Usage");
        // NOSONAR
        System.out.println(CLUtil.describeOptions(options).toString());
        // repeat the error so no need to scroll back past the usage to see it
        // NOSONAR
        System.out.println("Error: " + error);
        return;
    }
    try {
        // Also initialises JMeter logging
        initializeProperties(parser);
        SecurityProviderLoader.addSecurityProvider(JMeterUtils.getJMeterProperties());
        Thread.setDefaultUncaughtExceptionHandler((Thread t, Throwable e) -> {
            if (!(e instanceof ThreadDeath)) {
                log.error("Uncaught exception in thread {}", t, e);
                // NOSONAR
                System.err.println("Uncaught Exception " + e + " in thread " + t + ". See log file for details.");
            }
        });
        if (log.isInfoEnabled()) {
            log.info(JMeterUtils.getJMeterCopyright());
            log.info("Version {}", JMeterUtils.getJMeterVersion());
            // $NON-NLS-1$ //$NON-NLS-2$
            log.info("java.version={}", System.getProperty("java.version"));
            // $NON-NLS-1$ //$NON-NLS-2$
            log.info("java.vm.name={}", System.getProperty("java.vm.name"));
            // $NON-NLS-1$ //$NON-NLS-2$
            log.info("os.name={}", System.getProperty("os.name"));
            // $NON-NLS-1$ //$NON-NLS-2$
            log.info("os.arch={}", System.getProperty("os.arch"));
            // $NON-NLS-1$ //$NON-NLS-2$
            log.info("os.version={}", System.getProperty("os.version"));
            // $NON-NLS-1$ //$NON-NLS-2$
            log.info("file.encoding={}", System.getProperty("file.encoding"));
            // $NON-NLS-1$ //$NON-NLS-2$
            log.info("java.awt.headless={}", System.getProperty("java.awt.headless"));
            log.info("Max memory     ={}", Runtime.getRuntime().maxMemory());
            log.info("Available Processors ={}", Runtime.getRuntime().availableProcessors());
            log.info("Default Locale={}", Locale.getDefault().getDisplayName());
            log.info("JMeter  Locale={}", JMeterUtils.getLocale().getDisplayName());
            log.info("JMeterHome={}", JMeterUtils.getJMeterHome());
            // $NON-NLS-1$ //$NON-NLS-2$
            log.info("user.dir  ={}", System.getProperty("user.dir"));
            // $NON-NLS-1$
            log.info("PWD       ={}", new File(".").getCanonicalPath());
            log.info("IP: {} Name: {} FullName: {}", JMeterUtils.getLocalHostIP(), JMeterUtils.getLocalHostName(), JMeterUtils.getLocalHostFullName());
        }
        setProxy(parser);
        updateClassLoader();
        if (log.isDebugEnabled()) {
            // $NON-NLS-1$
            String jcp = System.getProperty("java.class.path");
            String[] bits = jcp.split(File.pathSeparator);
            log.debug("ClassPath");
            for (String bit : bits) {
                log.debug(bit);
            }
        }
        // Set some (hopefully!) useful properties
        long now = System.currentTimeMillis();
        // $NON-NLS-1$
        JMeterUtils.setProperty("START.MS", Long.toString(now));
        // so it agrees with above
        Date today = new Date(now);
        // $NON-NLS-1$ $NON-NLS-2$
        JMeterUtils.setProperty("START.YMD", new SimpleDateFormat("yyyyMMdd").format(today));
        // $NON-NLS-1$ $NON-NLS-2$
        JMeterUtils.setProperty("START.HMS", new SimpleDateFormat("HHmmss").format(today));
        if (parser.getArgumentById(VERSION_OPT) != null) {
            displayAsciiArt();
        } else if (parser.getArgumentById(HELP_OPT) != null) {
            displayAsciiArt();
            // NOSONAR $NON-NLS-1$
            System.out.println(JMeterUtils.getResourceFileAsText("org/apache/jmeter/help.txt"));
        } else if (parser.getArgumentById(OPTIONS_OPT) != null) {
            displayAsciiArt();
            // NOSONAR
            System.out.println(CLUtil.describeOptions(options).toString());
        } else if (parser.getArgumentById(SERVER_OPT) != null) {
            // Start the server
            try {
                // $NON-NLS-1$
                RemoteJMeterEngineImpl.startServer(RmiUtils.getRmiRegistryPort());
                startOptionalServers();
            } catch (Exception ex) {
                // NOSONAR
                System.err.println("Server failed to start: " + ex);
                log.error("Giving up, as server failed with:", ex);
                throw ex;
            }
        } else {
            String testFile = null;
            CLOption testFileOpt = parser.getArgumentById(TESTFILE_OPT);
            if (testFileOpt != null) {
                testFile = testFileOpt.getArgument();
                if (USE_LAST_JMX.equals(testFile)) {
                    // most recent
                    testFile = LoadRecentProject.getRecentFile(0);
                }
            }
            CLOption testReportOpt = parser.getArgumentById(REPORT_GENERATING_OPT);
            if (testReportOpt != null) {
                // generate report from existing file
                String reportFile = testReportOpt.getArgument();
                extractAndSetReportOutputFolder(parser, deleteResultFile);
                ReportGenerator generator = new ReportGenerator(reportFile, null);
                generator.generate();
            } else if (parser.getArgumentById(NONGUI_OPT) == null) {
                // not non-GUI => GUI
                String initialTestFile = testFile;
                SwingUtilities.invokeAndWait(() -> startGui(initialTestFile));
                startOptionalServers();
            } else {
                // NON-GUI must be true
                extractAndSetReportOutputFolder(parser, deleteResultFile);
                CLOption remoteTest = parser.getArgumentById(REMOTE_OPT_PARAM);
                if (remoteTest == null) {
                    remoteTest = parser.getArgumentById(REMOTE_OPT);
                }
                CLOption jtl = parser.getArgumentById(LOGFILE_OPT);
                String jtlFile = null;
                if (jtl != null) {
                    // $NON-NLS-1$
                    jtlFile = processLAST(jtl.getArgument(), ".jtl");
                }
                CLOption reportAtEndOpt = parser.getArgumentById(REPORT_AT_END_OPT);
                if (reportAtEndOpt != null && jtlFile == null) {
                    throw new IllegalUserActionException("Option -" + ((char) REPORT_AT_END_OPT) + " requires -" + ((char) LOGFILE_OPT) + " option");
                }
                startNonGui(testFile, jtlFile, remoteTest, reportAtEndOpt != null);
                startOptionalServers();
            }
        }
    } catch (IllegalUserActionException e) {
        // NOSONAR
        // NOSONAR
        System.out.println("Incorrect Usage:" + e.getMessage());
        // NOSONAR
        System.out.println(CLUtil.describeOptions(options).toString());
    } catch (Throwable e) {
        // NOSONAR
        log.error("An error occurred: ", e);
        // NOSONAR
        System.out.println("An error occurred: " + e.getMessage());
        // FIXME Should we exit here ? If we are called by Maven or Jenkins
        System.exit(1);
    }
}
Also used : CLOption(org.apache.commons.cli.avalon.CLOption) Date(java.util.Date) ConfigurationException(org.apache.jmeter.report.config.ConfigurationException) ScriptException(javax.script.ScriptException) JMeterException(org.apache.jorphan.util.JMeterException) ConversionException(com.thoughtworks.xstream.converters.ConversionException) SocketException(java.net.SocketException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) MalformedURLException(java.net.MalformedURLException) IllegalUserActionException(org.apache.jmeter.exceptions.IllegalUserActionException) ReportGenerator(org.apache.jmeter.report.dashboard.ReportGenerator) IllegalUserActionException(org.apache.jmeter.exceptions.IllegalUserActionException) CLArgsParser(org.apache.commons.cli.avalon.CLArgsParser) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat)

Aggregations

ConversionException (com.thoughtworks.xstream.converters.ConversionException)2 File (java.io.File)2 FileNotFoundException (java.io.FileNotFoundException)2 IOException (java.io.IOException)2 MalformedURLException (java.net.MalformedURLException)2 SocketException (java.net.SocketException)2 Date (java.util.Date)2 ScriptException (javax.script.ScriptException)2 IllegalUserActionException (org.apache.jmeter.exceptions.IllegalUserActionException)2 ConfigurationException (org.apache.jmeter.report.config.ConfigurationException)2 ReportGenerator (org.apache.jmeter.report.dashboard.ReportGenerator)2 JMeterException (org.apache.jorphan.util.JMeterException)2 SimpleDateFormat (java.text.SimpleDateFormat)1 ArrayList (java.util.ArrayList)1 StringTokenizer (java.util.StringTokenizer)1 CLArgsParser (org.apache.commons.cli.avalon.CLArgsParser)1 CLOption (org.apache.commons.cli.avalon.CLOption)1 ReplaceableController (org.apache.jmeter.control.ReplaceableController)1 ClientJMeterEngine (org.apache.jmeter.engine.ClientJMeterEngine)1 DistributedRunner (org.apache.jmeter.engine.DistributedRunner)1