Search in sources :

Example 1 with StandaloneCommandBuilder

use of org.wildfly.core.launcher.StandaloneCommandBuilder in project wildfly-core by wildfly.

the class LauncherTestCase method testStandaloneWithAgent.

@Test
public void testStandaloneWithAgent() throws Exception {
    final StandaloneCommandBuilder builder = StandaloneCommandBuilder.of(ServerHelper.JBOSS_HOME).addJavaOptions(ServerHelper.DEFAULT_SERVER_JAVA_OPTS).setUseSecurityManager(parseProperty("security.manager")).addModuleOption("-javaagent:" + ServerHelper.JBOSS_HOME.resolve("logging-agent-tests.jar") + "=" + LoggingAgent.DEBUG_ARG);
    final String localRepo = System.getProperty("maven.repo.local");
    if (localRepo != null) {
        builder.addJavaOption("-Dmaven.repo.local=" + localRepo);
    }
    Process process = null;
    try {
        process = Launcher.of(builder).setRedirectErrorStream(true).redirectOutput(STDOUT_PATH).launch();
        ServerHelper.waitForStandalone(process, LauncherTestCase::readStdout);
        final List<JsonObject> lines = ServerHelper.readLogFileFromModel("json.log");
        Assert.assertEquals("Expected 2 lines found " + lines.size(), 2, lines.size());
        JsonObject msg = lines.get(0);
        Assert.assertEquals(LoggingAgent.MSG, msg.getString("message"));
        Assert.assertEquals("FINE", msg.getString("level"));
        msg = lines.get(1);
        Assert.assertEquals(LoggingAgent.MSG, msg.getString("message"));
        Assert.assertEquals("INFO", msg.getString("level"));
        try (ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient()) {
            ServerHelper.shutdownStandalone(client);
        }
        process.waitFor(ServerHelper.TIMEOUT, TimeUnit.SECONDS);
        if (process.exitValue() != 0) {
            Assert.fail(readStdout());
        }
    } finally {
        ProcessHelper.destroyProcess(process);
    }
}
Also used : StandaloneCommandBuilder(org.wildfly.core.launcher.StandaloneCommandBuilder) ModelControllerClient(org.jboss.as.controller.client.ModelControllerClient) JsonObject(javax.json.JsonObject) Test(org.junit.Test)

Example 2 with StandaloneCommandBuilder

use of org.wildfly.core.launcher.StandaloneCommandBuilder in project wildfly-core by wildfly.

the class ServerConfigurator method configureStandalone.

private static void configureStandalone() throws InterruptedException, IOException {
    final Path stdout = Paths.get(TestSuiteEnvironment.getTmpDir(), "config-standalone-stdout.txt");
    final StandaloneCommandBuilder builder = StandaloneCommandBuilder.of(ServerHelper.JBOSS_HOME).addJavaOptions(ServerHelper.DEFAULT_SERVER_JAVA_OPTS);
    final String localRepo = System.getProperty("maven.repo.local");
    if (localRepo != null) {
        builder.addJavaOption("-Dmaven.repo.local=" + localRepo);
    }
    Process process = null;
    try {
        process = Launcher.of(builder).setRedirectErrorStream(true).redirectOutput(stdout).launch();
        ServerHelper.waitForStandalone(process, () -> readStdout(stdout));
        try (ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient()) {
            final CompositeOperationBuilder opBuilder = CompositeOperationBuilder.create();
            ModelNode address = Operations.createAddress("subsystem", "logging", "custom-formatter", "json");
            ModelNode op = Operations.createAddOperation(address);
            op.get("class").set("org.jboss.logmanager.formatters.JsonFormatter");
            op.get("module").set("org.jboss.logmanager");
            final ModelNode properties = op.get("properties").setEmptyObject();
            properties.get("exceptionOutputType").set("FORMATTED");
            properties.get("prettyPrint").set(false);
            opBuilder.addStep(op);
            address = Operations.createAddress("subsystem", "logging", "file-handler", "json");
            op = Operations.createAddOperation(address);
            op.get("append").set(false);
            op.get("level").set("DEBUG");
            op.get("autoflush").set(true);
            op.get("named-formatter").set("json");
            final ModelNode file = op.get("file");
            file.get("relative-to").set("jboss.server.log.dir");
            file.get("path").set("json.log");
            opBuilder.addStep(op);
            address = Operations.createAddress("subsystem", "logging", "logger", "org.wildfly.common.test.LoggingAgent");
            op = Operations.createAddOperation(address);
            op.get("handlers").setEmptyList().add("json");
            op.get("level").set("DEBUG");
            opBuilder.addStep(op);
            executeOperation(client, opBuilder.build());
            ServerHelper.shutdownStandalone(client);
        }
        if (!process.waitFor(ServerHelper.TIMEOUT, TimeUnit.SECONDS)) {
            Assert.fail(readStdout(stdout));
        }
        if (process.exitValue() != 0) {
            Assert.fail(readStdout(stdout));
        }
    } finally {
        ProcessHelper.destroyProcess(process);
    }
}
Also used : Path(java.nio.file.Path) StandaloneCommandBuilder(org.wildfly.core.launcher.StandaloneCommandBuilder) ModelControllerClient(org.jboss.as.controller.client.ModelControllerClient) CompositeOperationBuilder(org.jboss.as.controller.client.helpers.Operations.CompositeOperationBuilder) ModelNode(org.jboss.dmr.ModelNode)

Example 3 with StandaloneCommandBuilder

use of org.wildfly.core.launcher.StandaloneCommandBuilder in project wildfly-core by wildfly.

the class LayersTest method checkExecution.

private static void checkExecution(ExecutorService executor, Path installation) throws Exception {
    StringBuilder str = new StringBuilder();
    Runnable r = new Runnable() {

        @Override
        public void run() {
            try {
                StandaloneCommandBuilder builder = StandaloneCommandBuilder.of(installation);
                String localRepo = System.getProperty(MAVEN_REPO_LOCAL);
                if (localRepo != null) {
                    builder.addJavaOption("-D" + MAVEN_REPO_LOCAL + "=" + localRepo);
                } else {
                    System.out.println("Warning, no Maven local repository set.");
                }
                ProcessBuilder p = new ProcessBuilder(builder.build());
                p.redirectErrorStream(true);
                Process process = p.start();
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    String line;
                    boolean ended = false;
                    while ((line = reader.readLine()) != null) {
                        str.append(line).append("\n");
                        // but these errors are not caused by server configuration.
                        if (line.contains(END_LOG_FAILURE)) {
                            throw new Exception("Process for " + installation.getFileName() + " started with errors.");
                        } else {
                            if (line.contains(END_LOG_SUCCESS)) {
                                ended = true;
                                break;
                            }
                        }
                    }
                    if (!ended) {
                        throw new Exception("Process for " + installation.getFileName() + " not terminated properly.");
                    }
                } finally {
                    process.destroyForcibly();
                    process.waitFor();
                }
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    };
    try {
        executor.submit(r).get(1, TimeUnit.MINUTES);
    } catch (Exception ex) {
        throw new Exception("Exception checking " + installation.getFileName().toString() + "\n Server log \n" + str.toString(), ex);
    }
}
Also used : StandaloneCommandBuilder(org.wildfly.core.launcher.StandaloneCommandBuilder) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException)

Example 4 with StandaloneCommandBuilder

use of org.wildfly.core.launcher.StandaloneCommandBuilder in project wildfly-maven-plugin by wildfly.

the class RunMojo method execute.

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (skip) {
        return;
    }
    MavenRepositoriesEnricher.enrich(mavenSession, project, repositories);
    mavenRepoManager = new MavenArtifactRepositoryManager(repoSystem, session, repositories);
    final Log log = getLog();
    final Path deploymentContent = getDeploymentContent();
    // The deployment must exist before we do anything
    if (Files.notExists(deploymentContent)) {
        throw new MojoExecutionException(String.format("The deployment '%s' could not be found.", deploymentContent.toAbsolutePath()));
    }
    // Validate the environment
    final Path wildflyPath = provisionIfRequired(deploymentContent.getParent().resolve(provisioningDir));
    if (!ServerHelper.isValidHomeDirectory(wildflyPath)) {
        throw new MojoExecutionException(String.format("JBOSS_HOME '%s' is not a valid directory.", wildflyPath));
    }
    final StandaloneCommandBuilder commandBuilder = createCommandBuilder(wildflyPath);
    // Print some server information
    log.info("JAVA_HOME : " + commandBuilder.getJavaHome());
    log.info("JBOSS_HOME: " + commandBuilder.getWildFlyHome());
    log.info("JAVA_OPTS : " + Utils.toString(commandBuilder.getJavaOptions(), " "));
    try {
        if (addUser != null && addUser.hasUsers()) {
            log.info("Adding users: " + addUser);
            addUser.addUsers(commandBuilder.getWildFlyHome(), commandBuilder.getJavaHome());
        }
        // Start the server
        log.info("Server is starting up. Press CTRL + C to stop the server.");
        Process process = startContainer(commandBuilder);
        try (ModelControllerClient client = createClient()) {
            // Execute commands before the deployment is done
            final CommandConfiguration cmdConfig = CommandConfiguration.of(this::createClient, this::getClientConfiguration).addCommands(commands).addScripts(scripts).setJBossHome(commandBuilder.getWildFlyHome()).setFork(true).setStdout("none").setTimeout(timeout).build();
            commandExecutor.execute(cmdConfig, mavenRepoManager);
            // Create the deployment and deploy
            final Deployment deployment = Deployment.of(deploymentContent).setName(name).setRuntimeName(runtimeName);
            final DeploymentManager deploymentManager = DeploymentManager.Factory.create(client);
            deploymentManager.forceDeploy(deployment);
        } catch (MojoExecutionException | MojoFailureException e) {
            if (process != null) {
                process.destroyForcibly().waitFor(10L, TimeUnit.SECONDS);
            }
            throw e;
        }
        try {
            // Wait for the process to die
            boolean keepRunning = true;
            while (keepRunning) {
                final int exitCode = process.waitFor();
                // 10 is the magic code used in the scripts to survive a :shutdown(restart=true) operation
                if (exitCode == 10) {
                    // Ensure the current process is destroyed and restart a new one
                    process.destroy();
                    process = startContainer(commandBuilder);
                } else {
                    keepRunning = false;
                }
            }
        } catch (Exception e) {
            throw new MojoExecutionException("The server failed to start", e);
        } finally {
            if (process != null)
                process.destroy();
        }
    } catch (Exception e) {
        throw new MojoExecutionException("The server failed to start", e);
    }
}
Also used : Path(java.nio.file.Path) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) Log(org.apache.maven.plugin.logging.Log) CommandConfiguration(org.wildfly.plugin.cli.CommandConfiguration) DeploymentManager(org.wildfly.plugin.core.DeploymentManager) MojoFailureException(org.apache.maven.plugin.MojoFailureException) Deployment(org.wildfly.plugin.core.Deployment) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) ProvisioningException(org.jboss.galleon.ProvisioningException) StandaloneCommandBuilder(org.wildfly.core.launcher.StandaloneCommandBuilder) ModelControllerClient(org.jboss.as.controller.client.ModelControllerClient) MavenArtifactRepositoryManager(org.jboss.galleon.maven.plugin.util.MavenArtifactRepositoryManager)

Example 5 with StandaloneCommandBuilder

use of org.wildfly.core.launcher.StandaloneCommandBuilder in project wildfly-core by wildfly.

the class Server method start.

protected void start(PrintStream out) {
    try {
        CommandBuilder cbuilder = null;
        boolean needNormalModeCheck = false;
        if (isBootableJar) {
            final Path bootableJarPath = Paths.get(bootableJar);
            if (Files.notExists(bootableJarPath) || Files.isDirectory(bootableJarPath)) {
                throw new IllegalStateException("Cannot find: " + bootableJar);
            }
            final BootableJarCommandBuilder commandBuilder = BootableJarCommandBuilder.of(bootableJarPath);
            commandBuilder.setInstallDir(Paths.get(installDir));
            cbuilder = commandBuilder;
            commandBuilder.setJavaHome(legacyJavaHome == null ? javaHome : legacyJavaHome);
            if (jvmArgs != null) {
                commandBuilder.setJavaOptions(jvmArgs.split("\\s+"));
            }
            if (Boolean.getBoolean(serverDebug)) {
                commandBuilder.setDebug(true, serverDebugPort);
            }
            // we are testing, of course we want assertions and set-up some other defaults
            commandBuilder.addJavaOption("-ea").setBindAddressHint("management", managementAddress);
            if (jbossArgs != null) {
                String[] args = jbossArgs.split("\\s+");
                for (String a : args) {
                    if (a.startsWith("--cli-script=")) {
                        needNormalModeCheck = true;
                        break;
                    }
                }
                commandBuilder.addServerArguments(args);
            }
            commandBuilder.addServerArgument("-D[Standalone]");
        } else {
            final Path jbossHomeDir = Paths.get(jbossHome);
            if (Files.notExists(jbossHomeDir) && !Files.isDirectory(jbossHomeDir)) {
                throw new IllegalStateException("Cannot find: " + jbossHomeDir);
            }
            final StandaloneCommandBuilder commandBuilder = StandaloneCommandBuilder.of(jbossHomeDir);
            cbuilder = commandBuilder;
            if (modulePath != null && !modulePath.isEmpty()) {
                commandBuilder.setModuleDirs(modulePath.split(Pattern.quote(File.pathSeparator)));
            }
            commandBuilder.setJavaHome(legacyJavaHome == null ? javaHome : legacyJavaHome);
            if (jvmArgs != null) {
                commandBuilder.setJavaOptions(jvmArgs.split("\\s+"));
            }
            if (Boolean.getBoolean(serverDebug)) {
                commandBuilder.setDebug(true, serverDebugPort);
            }
            if (this.startMode == StartMode.ADMIN_ONLY) {
                commandBuilder.setAdminOnly();
            } else if (this.startMode == StartMode.SUSPEND) {
                commandBuilder.setStartSuspended();
            }
            if (readOnly) {
                commandBuilder.setServerReadOnlyConfiguration(serverConfig);
            } else {
                commandBuilder.setServerConfiguration(serverConfig);
            }
            if (gitRepository != null) {
                commandBuilder.setGitRepository(gitRepository, gitBranch, gitAuthConfiguration);
            }
            commandBuilder.setYamlFiles(yamlFiles);
            if (configDir != null) {
                commandBuilder.addJavaOption("-Djboss.server.config.dir=" + configDir.toString());
            }
            // we are testing, of course we want assertions and set-up some other defaults
            commandBuilder.addJavaOption("-ea").setBindAddressHint("management", managementAddress);
            if (jbossArgs != null) {
                commandBuilder.addServerArguments(jbossArgs.split("\\s+"));
            }
            commandBuilder.addServerArgument("-D[Standalone]");
        }
        StringBuilder builder = new StringBuilder("Starting container with: ");
        for (String arg : cbuilder.build()) {
            builder.append(arg).append(" ");
        }
        log.info(builder.toString());
        process = Launcher.of(cbuilder).setRedirectErrorStream(true).launch();
        new Thread(new ConsoleConsumer(process.getInputStream(), out)).start();
        final Process proc = process;
        shutdownThread = ProcessHelper.addShutdownHook(proc);
        createClient();
        long timeout = startupTimeout * 1000;
        boolean serverAvailable = false;
        long sleep = 1000;
        while (timeout > 0 && !serverAvailable) {
            long before = System.currentTimeMillis();
            serverAvailable = client.isServerInRunningState();
            if (serverAvailable && needNormalModeCheck) {
                serverAvailable = client.isServerInNormalMode();
            }
            timeout -= (System.currentTimeMillis() - before);
            if (!serverAvailable) {
                if (processHasDied(proc))
                    break;
                Thread.sleep(sleep);
                timeout -= sleep;
                sleep = Math.max(sleep / 2, 100);
            }
        }
        if (!serverAvailable) {
            destroyProcess();
            throw new RuntimeException("Managed server was not started within " + startupTimeout + " seconds.");
        }
    } catch (Exception e) {
        safeCloseClient();
        throw new RuntimeException("Could not start container", e);
    }
}
Also used : Path(java.nio.file.Path) BootableJarCommandBuilder(org.wildfly.core.launcher.BootableJarCommandBuilder) SocketException(java.net.SocketException) CancellationException(java.util.concurrent.CancellationException) Assert.checkNotNullParamWithNullPointerException(org.wildfly.common.Assert.checkNotNullParamWithNullPointerException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) StandaloneCommandBuilder(org.wildfly.core.launcher.StandaloneCommandBuilder) BootableJarCommandBuilder(org.wildfly.core.launcher.BootableJarCommandBuilder) StandaloneCommandBuilder(org.wildfly.core.launcher.StandaloneCommandBuilder) CommandBuilder(org.wildfly.core.launcher.CommandBuilder)

Aggregations

StandaloneCommandBuilder (org.wildfly.core.launcher.StandaloneCommandBuilder)8 IOException (java.io.IOException)4 Path (java.nio.file.Path)4 ModelControllerClient (org.jboss.as.controller.client.ModelControllerClient)4 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)2 Log (org.apache.maven.plugin.logging.Log)2 BufferedReader (java.io.BufferedReader)1 InputStreamReader (java.io.InputStreamReader)1 SocketException (java.net.SocketException)1 CancellationException (java.util.concurrent.CancellationException)1 ExecutionException (java.util.concurrent.ExecutionException)1 TimeoutException (java.util.concurrent.TimeoutException)1 JsonObject (javax.json.JsonObject)1 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)1 MojoFailureException (org.apache.maven.plugin.MojoFailureException)1 CompositeOperationBuilder (org.jboss.as.controller.client.helpers.Operations.CompositeOperationBuilder)1 ModelNode (org.jboss.dmr.ModelNode)1 ProvisioningException (org.jboss.galleon.ProvisioningException)1 MavenArtifactRepositoryManager (org.jboss.galleon.maven.plugin.util.MavenArtifactRepositoryManager)1 BeforeClass (org.junit.BeforeClass)1