Search in sources :

Example 1 with EmbeddedProcessStartException

use of org.wildfly.core.embedded.EmbeddedProcessStartException in project wildfly-core by wildfly.

the class EmbedServerHandler method doHandle.

@Override
protected void doHandle(CommandContext ctx) throws CommandLineException {
    final ParsedCommandLine parsedCmd = ctx.getParsedCommandLine();
    final File jbossHome = getJBossHome(parsedCmd);
    // set up the expected properties
    final String baseDir = WildFlySecurityManager.getPropertyPrivileged(JBOSS_SERVER_BASE_DIR, jbossHome + File.separator + "standalone");
    String xml = serverConfig.getValue(parsedCmd);
    if (xml == null) {
        xml = dashC.getValue(parsedCmd);
    }
    boolean adminOnlySetting = true;
    String adminProp = adminOnly.getValue(parsedCmd);
    if (adminProp != null && "false".equalsIgnoreCase(adminProp)) {
        adminOnlySetting = false;
    }
    boolean startEmpty = emptyConfig.isPresent(parsedCmd);
    boolean removeConfig = startEmpty && removeExisting.isPresent(parsedCmd);
    final List<String> args = parsedCmd.getOtherProperties();
    if (!args.isEmpty()) {
        if (args.size() != 1) {
            throw new CommandFormatException("The command accepts 0 unnamed argument(s) but received: " + args);
        }
    }
    Long bootTimeout = null;
    String timeoutString = timeout.getValue(parsedCmd);
    if (timeout.isPresent(parsedCmd) && (timeoutString == null || timeoutString.isEmpty())) {
        throw new CommandFormatException("The --timeout parameter requires a value.");
    }
    if (timeoutString != null) {
        bootTimeout = TimeUnit.SECONDS.toNanos(Long.parseLong(timeoutString));
    }
    String stdOutString = stdOutHandling.getValue(parsedCmd);
    if (stdOutHandling.isPresent(parsedCmd)) {
        if (stdOutString == null || stdOutString.isEmpty()) {
            throw new CommandFormatException("The --std-out parameter requires a value { echo, discard }.");
        }
        if (!(stdOutString.equals(ECHO) || stdOutString.equals(DISCARD_STDOUT))) {
            throw new CommandFormatException("The --std-out parameter should be one of { echo, discard }.");
        }
    }
    final EnvironmentRestorer restorer = new EnvironmentRestorer(JBOSS_SERVER_LOG_DIR);
    boolean ok = false;
    ThreadLocalContextSelector contextSelector = null;
    try {
        Contexts defaultContexts = restorer.getDefaultContexts();
        StdioContext discardStdoutContext = null;
        if (!ECHO.equalsIgnoreCase(stdOutHandling.getValue(parsedCmd))) {
            PrintStream nullStream = new UncloseablePrintStream(NullOutputStream.getInstance());
            StdioContext currentContext = defaultContexts.getStdioContext();
            discardStdoutContext = StdioContext.create(currentContext.getIn(), nullStream, currentContext.getErr());
        }
        // Configure and get the log context, default to baseDir
        String serverLogDir = WildFlySecurityManager.getPropertyPrivileged(JBOSS_SERVER_LOG_DIR, null);
        if (serverLogDir == null) {
            serverLogDir = baseDir + File.separator + "log";
            WildFlySecurityManager.setPropertyPrivileged(JBOSS_SERVER_LOG_DIR, serverLogDir);
        }
        final String serverCfgDir = WildFlySecurityManager.getPropertyPrivileged(JBOSS_SERVER_CONFIG_DIR, baseDir + File.separator + "configuration");
        final LogContext embeddedLogContext = EmbeddedLogContext.configureLogContext(new File(serverLogDir), new File(serverCfgDir), "server.log", ctx);
        Contexts localContexts = new Contexts(embeddedLogContext, discardStdoutContext);
        contextSelector = new ThreadLocalContextSelector(localContexts, defaultContexts);
        contextSelector.pushLocal();
        StdioContext.setStdioContextSelector(contextSelector);
        LogContext.setLogContextSelector(contextSelector);
        List<String> cmdsList = new ArrayList<>();
        if (xml == null && (parsedCmd.hasProperty("--server-config") || parsedCmd.hasProperty("-c"))) {
            throw new CommandFormatException("The --server-config (or -c) parameter requires a value.");
        }
        if (xml != null) {
            xml = xml.trim();
            if (xml.length() == 0) {
                throw new CommandFormatException("The --server-config parameter requires a value.");
            }
            if (!xml.endsWith(".xml")) {
                throw new CommandFormatException("The --server-config filename must end with .xml.");
            }
            cmdsList.add("--server-config=" + xml);
        }
        // if --empty-config is present but the config file already exists we error unless --remove-config has also been used
        if (startEmpty && !removeConfig) {
            String configFileName = xml == null ? "standalone.xml" : xml;
            File configFile = new File(serverCfgDir + File.separator + configFileName);
            if (configFile.exists()) {
                throw new CommandFormatException("The configuration file " + configFileName + " already exists, please use --remove-existing if you wish to overwrite.");
            }
        }
        if (adminOnlySetting) {
            cmdsList.add("--admin-only");
        }
        if (startEmpty) {
            cmdsList.add("--internal-empty-config");
            if (removeConfig) {
                cmdsList.add("--internal-remove-config");
            }
        }
        String[] cmds = cmdsList.toArray(new String[cmdsList.size()]);
        final Configuration.Builder configBuilder;
        if (this.jbossHome == null) {
            // Modular environment, note that the jbossHome here is resolved from the JBOSS_HOME environment
            // variable and should never be null according to the getJBossHome() method.
            configBuilder = Configuration.Builder.of(jbossHome).setModuleLoader(ModuleLoader.forClass(getClass())).setCommandArguments(cmds);
        } else {
            configBuilder = Configuration.Builder.of(jbossHome.getAbsoluteFile()).addSystemPackages(EmbeddedControllerHandlerRegistrar.EXTENDED_SYSTEM_PKGS).setCommandArguments(cmds);
        }
        // Disables the logging subsystem from registering an embedded log context if the subsystem is present
        WildFlySecurityManager.setPropertyPrivileged("org.wildfly.logging.embedded", "false");
        final EmbeddedManagedProcess server = EmbeddedProcessFactory.createStandaloneServer(configBuilder.build());
        server.start();
        serverReference.set(new EmbeddedProcessLaunch(server, restorer, false));
        ModelControllerClient mcc = new ThreadContextsModelControllerClient(server.getModelControllerClient(), contextSelector);
        if (bootTimeout == null || bootTimeout > 0) {
            // Poll for server state. Alternative would be to get ControlledProcessStateService
            // and do reflection stuff to read the state and register for change notifications
            long expired = bootTimeout == null ? Long.MAX_VALUE : System.nanoTime() + bootTimeout;
            String status = "starting";
            final ModelNode getStateOp = new ModelNode();
            getStateOp.get(ClientConstants.OP).set(ClientConstants.READ_ATTRIBUTE_OPERATION);
            getStateOp.get(ClientConstants.NAME).set("server-state");
            do {
                try {
                    final ModelNode response = mcc.execute(getStateOp);
                    if (Util.isSuccess(response)) {
                        status = response.get(ClientConstants.RESULT).asString();
                    }
                } catch (Exception e) {
                // ignore and try again
                }
                if ("starting".equals(status)) {
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        throw new CommandLineException("Interrupted while waiting for embedded server to start");
                    }
                } else {
                    break;
                }
            } while (System.nanoTime() < expired);
            if ("starting".equals(status)) {
                // we'll assume the loop didn't run for decades
                assert bootTimeout != null;
                // Stop server and restore environment
                StopEmbeddedServerHandler.cleanup(serverReference);
                throw new CommandLineException("Embedded server did not exit 'starting' status within " + TimeUnit.NANOSECONDS.toSeconds(bootTimeout) + " seconds");
            }
        }
        // Expose the client to the rest of the CLI last so nothing can be done with
        // it until we're ready
        ctx.bindClient(mcc);
        // Stop the server on any disconnect event
        ctx.addEventListener(new CliEventListener() {

            @Override
            public void cliEvent(CliEvent event, CommandContext ctx) {
                if (event == CliEvent.DISCONNECTED) {
                    StopEmbeddedServerHandler.cleanup(serverReference);
                }
            }
        });
        ok = true;
    } catch (RuntimeException | EmbeddedProcessStartException e) {
        throw new CommandLineException("Cannot start embedded server", e);
    } finally {
        if (!ok) {
            ctx.disconnectController();
            restorer.restoreEnvironment();
        } else if (contextSelector != null) {
            contextSelector.restore(null);
        }
    }
}
Also used : EmbeddedProcessStartException(org.wildfly.core.embedded.EmbeddedProcessStartException) Configuration(org.wildfly.core.embedded.Configuration) CommandContext(org.jboss.as.cli.CommandContext) CliEventListener(org.jboss.as.cli.CliEventListener) ArrayList(java.util.ArrayList) EmbeddedManagedProcess(org.wildfly.core.embedded.EmbeddedManagedProcess) StdioContext(org.jboss.stdio.StdioContext) CommandLineException(org.jboss.as.cli.CommandLineException) ModelControllerClient(org.jboss.as.controller.client.ModelControllerClient) PrintStream(java.io.PrintStream) LogContext(org.jboss.logmanager.LogContext) EmbeddedProcessStartException(org.wildfly.core.embedded.EmbeddedProcessStartException) CommandLineException(org.jboss.as.cli.CommandLineException) CommandFormatException(org.jboss.as.cli.CommandFormatException) CommandFormatException(org.jboss.as.cli.CommandFormatException) ParsedCommandLine(org.jboss.as.cli.operation.ParsedCommandLine) CliEvent(org.jboss.as.cli.CliEvent) ModelNode(org.jboss.dmr.ModelNode) File(java.io.File)

Example 2 with EmbeddedProcessStartException

use of org.wildfly.core.embedded.EmbeddedProcessStartException in project wildfly-core by wildfly.

the class EmbedHostControllerHandler method doHandle.

@Override
protected void doHandle(CommandContext ctx) throws CommandLineException {
    final ParsedCommandLine parsedCmd = ctx.getParsedCommandLine();
    final File jbossHome = getJBossHome(parsedCmd);
    // set up the expected properties, default to JBOSS_HOME/standalone
    final String baseDir = WildFlySecurityManager.getPropertyPrivileged(JBOSS_DOMAIN_BASE_DIR, jbossHome + File.separator + "domain");
    String domainXml = domainConfig.getValue(parsedCmd);
    if (domainXml == null) {
        domainXml = dashC.getValue(parsedCmd);
    }
    if ((domainConfig.isPresent(parsedCmd) || dashC.isPresent(parsedCmd)) && (domainXml == null || domainXml.isEmpty())) {
        throw new CommandFormatException("The --domain-config (or -c) parameter requires a value.");
    }
    String hostXml = hostConfig.getValue(parsedCmd);
    if (hostConfig.isPresent(parsedCmd) && (hostXml == null || hostXml.isEmpty())) {
        throw new CommandFormatException("The --host-config parameter requires a value.");
    }
    Long bootTimeout = null;
    String timeoutString = timeout.getValue(parsedCmd);
    if (timeout.isPresent(parsedCmd) && (timeoutString == null || timeoutString.isEmpty())) {
        throw new CommandFormatException("The --timeout parameter requires a value.");
    }
    if (timeoutString != null) {
        bootTimeout = TimeUnit.SECONDS.toNanos(Long.parseLong(timeoutString));
    }
    String stdOutString = stdOutHandling.getValue(parsedCmd);
    if (stdOutHandling.isPresent(parsedCmd)) {
        if (stdOutString == null || stdOutString.isEmpty()) {
            throw new CommandFormatException("The --std-out parameter requires a value { echo, discard }.");
        }
        if (!(stdOutString.equals(ECHO) || stdOutString.equals(DISCARD_STDOUT))) {
            throw new CommandFormatException("The --std-out parameter should be one of { echo, discard }.");
        }
    }
    final List<String> args = parsedCmd.getOtherProperties();
    if (!args.isEmpty()) {
        throw new CommandFormatException("The command accepts 0 unnamed argument(s) but received: " + args);
    }
    final EnvironmentRestorer restorer = new EnvironmentRestorer(JBOSS_DOMAIN_LOG_DIR);
    boolean ok = false;
    ThreadLocalContextSelector contextSelector = null;
    try {
        Contexts defaultContexts = restorer.getDefaultContexts();
        StdioContext discardStdoutContext = null;
        if (!ECHO.equalsIgnoreCase(stdOutHandling.getValue(parsedCmd))) {
            PrintStream nullStream = new UncloseablePrintStream(NullOutputStream.getInstance());
            StdioContext currentContext = defaultContexts.getStdioContext();
            discardStdoutContext = StdioContext.create(currentContext.getIn(), nullStream, currentContext.getErr());
        }
        // Configure and get the log context
        String controllerLogDir = WildFlySecurityManager.getPropertyPrivileged(JBOSS_DOMAIN_LOG_DIR, null);
        if (controllerLogDir == null) {
            controllerLogDir = baseDir + File.separator + "log";
            WildFlySecurityManager.setPropertyPrivileged(JBOSS_DOMAIN_LOG_DIR, controllerLogDir);
        }
        final String controllerCfgDir = WildFlySecurityManager.getPropertyPrivileged(JBOSS_DOMAIN_CONFIG_DIR, baseDir + File.separator + "configuration");
        final LogContext embeddedLogContext = EmbeddedLogContext.configureLogContext(new File(controllerLogDir), new File(controllerCfgDir), "host-controller.log", ctx);
        Contexts localContexts = new Contexts(embeddedLogContext, discardStdoutContext);
        contextSelector = new ThreadLocalContextSelector(localContexts, defaultContexts);
        contextSelector.pushLocal();
        StdioContext.setStdioContextSelector(contextSelector);
        LogContext.setLogContextSelector(contextSelector);
        List<String> cmdsList = new ArrayList<>();
        if (domainXml != null && domainXml.trim().length() > 0) {
            cmdsList.add(DOMAIN_CONFIG);
            cmdsList.add(domainXml.trim());
        }
        if (hostXml != null && hostXml.trim().length() > 0) {
            cmdsList.add(HOST_CONFIG);
            cmdsList.add(hostXml.trim());
        }
        boolean emptyDomain = emptyDomainConfig.isPresent(parsedCmd);
        boolean removeDomain = removeExistingDomainConfig.isPresent(parsedCmd);
        if (emptyDomain) {
            cmdsList.add(EMPTY_DOMAIN_CONFIG);
        }
        if (removeDomain) {
            cmdsList.add(REMOVE_EXISTING_DOMAIN_CONFIG);
        }
        File domainXmlCfgFile = new File(controllerCfgDir + File.separator + (domainConfig.isPresent(parsedCmd) ? domainXml : "domain.xml"));
        if (emptyDomain && !removeDomain && domainXmlCfgFile.exists() && domainXmlCfgFile.length() != 0) {
            throw new CommandFormatException("The specified domain configuration file already exists and has size > 0 and may not be overwritten unless --remove-existing-domain-config is also specified.");
        }
        boolean emptyHost = emptyHostConfig.isPresent(parsedCmd);
        boolean removeHost = removeExistingHostConfig.isPresent(parsedCmd);
        if (emptyHost) {
            cmdsList.add(EMPTY_HOST_CONFIG);
        }
        if (removeHost) {
            cmdsList.add(REMOVE_EXISTING_HOST_CONFIG);
        }
        File hostXmlCfgFile = new File(controllerCfgDir + File.separator + (hostConfig.isPresent(parsedCmd) ? hostXml : "host.xml"));
        if (emptyHost && !removeHost && hostXmlCfgFile.exists() && hostXmlCfgFile.length() != 0) {
            throw new CommandFormatException("The specified host configuration file already exists and has size > 0 and may not be overwritten unless --remove-existing-host-config is also specified.");
        }
        String[] cmds = cmdsList.toArray(new String[cmdsList.size()]);
        final Configuration.Builder configBuilder;
        if (this.jbossHome == null) {
            // Modular environment, note that the jbossHome here is resolved from the JBOSS_HOME environment
            // variable and should never be null according to the getJBossHome() method.
            configBuilder = Configuration.Builder.of(jbossHome).setModuleLoader(ModuleLoader.forClass(getClass())).setCommandArguments(cmds);
        } else {
            configBuilder = Configuration.Builder.of(jbossHome.getAbsoluteFile()).addSystemPackages(EmbeddedControllerHandlerRegistrar.EXTENDED_SYSTEM_PKGS).setCommandArguments(cmds);
        }
        // Disables the logging subsystem from registering an embedded log context if the subsystem is present
        WildFlySecurityManager.setPropertyPrivileged("org.wildfly.logging.embedded", "false");
        final EmbeddedManagedProcess hostController = EmbeddedProcessFactory.createHostController(configBuilder.build());
        hostController.start();
        hostControllerReference.set(new EmbeddedProcessLaunch(hostController, restorer, true));
        ModelControllerClient mcc = new ThreadContextsModelControllerClient(hostController.getModelControllerClient(), contextSelector);
        if (hostController.canQueryProcessState()) {
            // the process state and wait for it even if we are on EMPTY_HOST_CONFIG scenario.
            if (bootTimeout == null || bootTimeout > 0) {
                long expired = bootTimeout == null ? Long.MAX_VALUE : System.nanoTime() + bootTimeout;
                String status;
                do {
                    status = hostController.getProcessState();
                    if (status == null || "starting".equals(status)) {
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            throw new CommandLineException("Interrupted while waiting for embedded server to start");
                        }
                    } else {
                        break;
                    }
                } while (System.nanoTime() < expired);
                if (status == null || "starting".equals(status)) {
                    // we'll assume the loop didn't run for decades
                    assert bootTimeout != null;
                    // Stop server and restore environment
                    StopEmbeddedHostControllerHandler.cleanup(hostControllerReference);
                    throw new CommandLineException("Embedded host controller did not exit 'starting' status within " + TimeUnit.NANOSECONDS.toSeconds(bootTimeout) + " seconds");
                }
            }
        } else {
            // See https://issues.redhat.com/browse/WFLY-13276 for some context.
            if (!emptyHost && (bootTimeout == null || bootTimeout > 0)) {
                long expired = bootTimeout == null ? Long.MAX_VALUE : System.nanoTime() + bootTimeout;
                String status = "starting";
                // read out the host controller name
                final ModelNode getNameOp = new ModelNode();
                getNameOp.get(ClientConstants.OP).set(ClientConstants.READ_ATTRIBUTE_OPERATION);
                getNameOp.get(ClientConstants.NAME).set(Util.LOCAL_HOST_NAME);
                final ModelNode getStateOp = new ModelNode();
                getStateOp.get(ClientConstants.OP).set(ClientConstants.READ_ATTRIBUTE_OPERATION);
                ModelNode address = getStateOp.get(ClientConstants.ADDRESS);
                getStateOp.get(ClientConstants.NAME).set(ClientConstants.HOST_STATE);
                do {
                    try {
                        final ModelNode nameResponse = mcc.execute(getNameOp);
                        if (Util.isSuccess(nameResponse)) {
                            // read out the connected HC name
                            final String localName = nameResponse.get(ClientConstants.RESULT).asString();
                            address.set(ClientConstants.HOST, localName);
                            final ModelNode stateResponse = mcc.execute(getStateOp);
                            if (Util.isSuccess(stateResponse)) {
                                status = stateResponse.get(ClientConstants.RESULT).asString();
                            }
                        }
                    } catch (Exception e) {
                    // ignore and try again
                    }
                    if ("starting".equals(status)) {
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            throw new CommandLineException("Interrupted while waiting for embedded server to start");
                        }
                    } else {
                        break;
                    }
                } while (System.nanoTime() < expired);
                if ("starting".equals(status)) {
                    // we'll assume the loop didn't run for decades
                    assert bootTimeout != null;
                    // Stop server and restore environment
                    StopEmbeddedHostControllerHandler.cleanup(hostControllerReference);
                    throw new CommandLineException("Embedded host controller did not exit 'starting' status within " + TimeUnit.NANOSECONDS.toSeconds(bootTimeout) + " seconds");
                }
            }
        }
        // Expose the client to the rest of the CLI last so nothing can be done with
        // it until we're ready
        ctx.bindClient(mcc);
        // Stop the server on any disconnect event
        ctx.addEventListener(new CliEventListener() {

            @Override
            public void cliEvent(CliEvent event, CommandContext ctx) {
                if (event == CliEvent.DISCONNECTED) {
                    StopEmbeddedHostControllerHandler.cleanup(hostControllerReference);
                }
            }
        });
        ok = true;
    } catch (RuntimeException | EmbeddedProcessStartException e) {
        throw new CommandLineException("Cannot start embedded Host Controller", e);
    } finally {
        if (!ok) {
            ctx.disconnectController();
            restorer.restoreEnvironment();
        } else if (contextSelector != null) {
            contextSelector.restore(null);
        }
    }
}
Also used : EmbeddedProcessStartException(org.wildfly.core.embedded.EmbeddedProcessStartException) Configuration(org.wildfly.core.embedded.Configuration) CommandContext(org.jboss.as.cli.CommandContext) CliEventListener(org.jboss.as.cli.CliEventListener) ArrayList(java.util.ArrayList) EmbeddedManagedProcess(org.wildfly.core.embedded.EmbeddedManagedProcess) StdioContext(org.jboss.stdio.StdioContext) CommandLineException(org.jboss.as.cli.CommandLineException) ModelControllerClient(org.jboss.as.controller.client.ModelControllerClient) PrintStream(java.io.PrintStream) LogContext(org.jboss.logmanager.LogContext) EmbeddedProcessStartException(org.wildfly.core.embedded.EmbeddedProcessStartException) CommandLineException(org.jboss.as.cli.CommandLineException) CommandFormatException(org.jboss.as.cli.CommandFormatException) CommandFormatException(org.jboss.as.cli.CommandFormatException) ParsedCommandLine(org.jboss.as.cli.operation.ParsedCommandLine) CliEvent(org.jboss.as.cli.CliEvent) ModelNode(org.jboss.dmr.ModelNode) File(java.io.File)

Aggregations

File (java.io.File)2 PrintStream (java.io.PrintStream)2 ArrayList (java.util.ArrayList)2 CliEvent (org.jboss.as.cli.CliEvent)2 CliEventListener (org.jboss.as.cli.CliEventListener)2 CommandContext (org.jboss.as.cli.CommandContext)2 CommandFormatException (org.jboss.as.cli.CommandFormatException)2 CommandLineException (org.jboss.as.cli.CommandLineException)2 ParsedCommandLine (org.jboss.as.cli.operation.ParsedCommandLine)2 ModelControllerClient (org.jboss.as.controller.client.ModelControllerClient)2 ModelNode (org.jboss.dmr.ModelNode)2 LogContext (org.jboss.logmanager.LogContext)2 StdioContext (org.jboss.stdio.StdioContext)2 Configuration (org.wildfly.core.embedded.Configuration)2 EmbeddedManagedProcess (org.wildfly.core.embedded.EmbeddedManagedProcess)2 EmbeddedProcessStartException (org.wildfly.core.embedded.EmbeddedProcessStartException)2