Search in sources :

Example 21 with LogContext

use of org.jboss.logmanager.LogContext in project wildfly-core by wildfly.

the class WildFlyLogContextSelectorImpl method getLogContext.

@Override
public LogContext getLogContext() {
    final LogContext localContext = this.localContext.get();
    if (localContext != null) {
        return localContext;
    }
    final int counter;
    synchronized (this) {
        counter = this.counter;
    }
    // default selector, however in most cases it should perform better.
    return counter > 0 ? contextSelector.getLogContext() : defaultLogContextSelector.getLogContext();
}
Also used : LogContext(org.jboss.logmanager.LogContext)

Example 22 with LogContext

use of org.jboss.logmanager.LogContext 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)

Example 23 with LogContext

use of org.jboss.logmanager.LogContext in project wildfly-core by wildfly.

the class EmbeddedLogContext method clearLogContext.

/**
 * Attempts to clear the global log context used for embedded servers.
 */
static synchronized void clearLogContext() {
    final LogContext embeddedLogContext = Holder.LOG_CONTEXT;
    // Remove the configurator and clear the log context
    final Configurator configurator = embeddedLogContext.getLogger("").detach(Configurator.ATTACHMENT_KEY);
    // If this was a PropertyConfigurator we can use the LogContextConfiguration API to tear down the LogContext
    if (configurator instanceof PropertyConfigurator) {
        final LogContextConfiguration logContextConfiguration = ((PropertyConfigurator) configurator).getLogContextConfiguration();
        clearLogContext(logContextConfiguration);
    } else if (configurator instanceof LogContextConfiguration) {
        clearLogContext((LogContextConfiguration) configurator);
    } else {
        // Remove all the handlers and close them as well as reset the loggers
        final List<String> loggerNames = Collections.list(embeddedLogContext.getLoggerNames());
        for (String name : loggerNames) {
            final Logger logger = embeddedLogContext.getLoggerIfExists(name);
            if (logger != null) {
                final Handler[] handlers = logger.clearHandlers();
                if (handlers != null) {
                    for (Handler handler : handlers) {
                        handler.close();
                    }
                }
                logger.setFilter(null);
                logger.setUseParentFilters(false);
                logger.setUseParentHandlers(true);
                logger.setLevel(Level.INFO);
            }
        }
    }
}
Also used : LogContextConfiguration(org.jboss.logmanager.config.LogContextConfiguration) PropertyConfigurator(org.jboss.logmanager.PropertyConfigurator) Configurator(org.jboss.logmanager.Configurator) LogContext(org.jboss.logmanager.LogContext) Handler(java.util.logging.Handler) List(java.util.List) Logger(org.jboss.logmanager.Logger) PropertyConfigurator(org.jboss.logmanager.PropertyConfigurator)

Example 24 with LogContext

use of org.jboss.logmanager.LogContext in project wildfly-core by wildfly.

the class EnvironmentRestorer method restoreLogContextSelector.

synchronized void restoreLogContextSelector() {
    if (!logContextSelectorRestored) {
        final LogContext logContext = defaultContexts.getLogContext();
        if (logContext == LogContext.getSystemLogContext()) {
            LogContext.setLogContextSelector(LogContext.DEFAULT_LOG_CONTEXT_SELECTOR);
        } else {
            LogContext.setLogContextSelector(new LogContextSelector() {

                @Override
                public LogContext getLogContext() {
                    return logContext;
                }
            });
        }
        EmbeddedLogContext.clearLogContext();
        logContextSelectorRestored = true;
    }
}
Also used : LogContext(org.jboss.logmanager.LogContext) LogContextSelector(org.jboss.logmanager.LogContextSelector)

Example 25 with LogContext

use of org.jboss.logmanager.LogContext in project wildfly-core by wildfly.

the class ThreadLocalContextSelector method getLogContext.

@Override
public LogContext getLogContext() {
    // CLI loggers should only use the default stdio context regardless if the thread-local context is set This
    // allows the context configured for CLI, e.g. jboss-cli-logging.properties.
    final ClassLoader tccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
    if (tccl != null && tccl.equals(cliClassLoader)) {
        return defaultContexts.getLogContext();
    }
    Contexts threadContext = threadLocal.get();
    LogContext local = threadContext != null ? threadContext.getLogContext() : null;
    return local == null ? defaultContexts.getLogContext() : local;
}
Also used : LogContext(org.jboss.logmanager.LogContext)

Aggregations

LogContext (org.jboss.logmanager.LogContext)33 ModelNode (org.jboss.dmr.ModelNode)7 PathAddress (org.jboss.as.controller.PathAddress)6 ConfigurationPersistence (org.jboss.as.logging.logmanager.ConfigurationPersistence)6 Logger (org.jboss.logmanager.Logger)6 ArrayList (java.util.ArrayList)5 Level (java.util.logging.Level)5 PropertyConfigurator (org.jboss.logmanager.PropertyConfigurator)5 File (java.io.File)4 InputStream (java.io.InputStream)4 LogContextConfiguration (org.jboss.logmanager.config.LogContextConfiguration)4 StdioContext (org.jboss.stdio.StdioContext)4 IOException (java.io.IOException)3 Path (java.nio.file.Path)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 Properties (java.util.Properties)3 Handler (java.util.logging.Handler)3 DeploymentUnit (org.jboss.as.server.deployment.DeploymentUnit)3 Configurator (org.jboss.logmanager.Configurator)3