Search in sources :

Example 1 with LogContext

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

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

the class EmbeddedLogContext method configureLogContext.

/**
 * Configures the log context for the server and returns the configured log context.
 *
 * @param logDir             the logging directory, from jboss.server|domain.log.dir standalone default {@code $JBOSS_HOME/standalone/log}
 * @param configDir          the configuration directory from jboss.server|domain.config.dir, standalone default {@code $JBOSS_HOME/standalone/configuration}
 * @param defaultLogFileName the name of the log file to pass to {@code org.jboss.boot.log.file}
 * @param ctx                the command context used to report errors to
 *
 * @return the configured log context
 */
static synchronized LogContext configureLogContext(final File logDir, final File configDir, final String defaultLogFileName, final CommandContext ctx) {
    final LogContext embeddedLogContext = Holder.LOG_CONTEXT;
    final Path bootLog = logDir.toPath().resolve(Paths.get(defaultLogFileName));
    final Path loggingProperties = configDir.toPath().resolve(Paths.get("logging.properties"));
    if (Files.exists(loggingProperties)) {
        WildFlySecurityManager.setPropertyPrivileged("org.jboss.boot.log.file", bootLog.toAbsolutePath().toString());
        try (final InputStream in = Files.newInputStream(loggingProperties)) {
            // Attempt to get the configurator from the root logger
            Configurator configurator = embeddedLogContext.getAttachment("", Configurator.ATTACHMENT_KEY);
            if (configurator == null) {
                configurator = new PropertyConfigurator(embeddedLogContext);
                final Configurator existing = embeddedLogContext.getLogger("").attachIfAbsent(Configurator.ATTACHMENT_KEY, configurator);
                if (existing != null) {
                    configurator = existing;
                }
            }
            configurator.configure(in);
        } catch (IOException e) {
            ctx.printLine(String.format("Unable to configure logging from configuration file %s. Reason: %s", loggingProperties, e.getLocalizedMessage()));
        }
    }
    return embeddedLogContext;
}
Also used : Path(java.nio.file.Path) InputStream(java.io.InputStream) PropertyConfigurator(org.jboss.logmanager.PropertyConfigurator) Configurator(org.jboss.logmanager.Configurator) LogContext(org.jboss.logmanager.LogContext) IOException(java.io.IOException) PropertyConfigurator(org.jboss.logmanager.PropertyConfigurator)

Example 3 with LogContext

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

the class LoggingConfigDeploymentProcessor method configure.

/**
 * Configures the log context.
 *
 * @param configFile  the configuration file
 * @param classLoader the class loader to use for the configuration
 * @param logContext  the log context to configure
 *
 * @return {@code true} if the log context was successfully configured, otherwise {@code false}
 *
 * @throws DeploymentUnitProcessingException if the configuration fails
 */
private LoggingConfigurationService configure(final ResourceRoot root, final VirtualFile configFile, final ClassLoader classLoader, final LogContext logContext) throws DeploymentUnitProcessingException {
    InputStream configStream = null;
    try {
        LoggingLogger.ROOT_LOGGER.debugf("Found logging configuration file: %s", configFile);
        // Get the filname and open the stream
        final String fileName = configFile.getName();
        configStream = configFile.openStream();
        // Check the type of the configuration file
        if (isLog4jConfiguration(fileName)) {
            LoggingLogger.ROOT_LOGGER.usageOfLog4j1Config(configFile.getPathName(), root.getRootName());
            final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
            final LogContext old = logContextSelector.setLocalContext(logContext);
            try {
                WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader);
                if (LOG4J_XML.equals(fileName) || JBOSS_LOG4J_XML.equals(fileName)) {
                    new DOMConfigurator().doConfigure(configStream, org.apache.log4j.JBossLogManagerFacade.getLoggerRepository(logContext));
                } else {
                    final Properties properties = new Properties();
                    properties.load(new InputStreamReader(configStream, ENCODING));
                    new org.apache.log4j.PropertyConfigurator().doConfigure(properties, org.apache.log4j.JBossLogManagerFacade.getLoggerRepository(logContext));
                }
            } finally {
                logContextSelector.setLocalContext(old);
                WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current);
            }
            return new LoggingConfigurationService(null, resolveRelativePath(root, configFile));
        } else {
            // Create a properties file
            final Properties properties = new Properties();
            properties.load(new InputStreamReader(configStream, ENCODING));
            // Attempt to see if this is a J.U.L. configuration file
            if (isJulConfiguration(properties)) {
                LoggingLogger.ROOT_LOGGER.julConfigurationFileFound(configFile.getName());
            } else {
                // Load non-log4j types
                final PropertyConfigurator propertyConfigurator = new PropertyConfigurator(logContext);
                propertyConfigurator.configure(properties);
                return new LoggingConfigurationService(propertyConfigurator.getLogContextConfiguration(), resolveRelativePath(root, configFile));
            }
        }
    } catch (Exception e) {
        throw LoggingLogger.ROOT_LOGGER.failedToConfigureLogging(e, configFile.getName());
    } finally {
        safeClose(configStream);
    }
    return null;
}
Also used : DOMConfigurator(org.apache.log4j.xml.DOMConfigurator) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) LogContext(org.jboss.logmanager.LogContext) Properties(java.util.Properties) PropertyConfigurator(org.jboss.logmanager.PropertyConfigurator) DeploymentUnitProcessingException(org.jboss.as.server.deployment.DeploymentUnitProcessingException) IOException(java.io.IOException)

Example 4 with LogContext

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

the class LoggingConfigDeploymentProcessor method processDeployment.

@Override
protected void processDeployment(final DeploymentPhaseContext phaseContext, final DeploymentUnit deploymentUnit, final ResourceRoot root) throws DeploymentUnitProcessingException {
    boolean process = this.process;
    // Get the system properties
    final Properties systemProps = WildFlySecurityManager.getSystemPropertiesPrivileged();
    if (systemProps.containsKey(PER_DEPLOYMENT_LOGGING)) {
        LoggingLogger.ROOT_LOGGER.perDeploymentPropertyDeprecated(PER_DEPLOYMENT_LOGGING, attributeName);
        if (process) {
            process = Boolean.valueOf(WildFlySecurityManager.getPropertyPrivileged(PER_DEPLOYMENT_LOGGING, Boolean.toString(true)));
        } else {
            LoggingLogger.ROOT_LOGGER.perLoggingDeploymentIgnored(PER_DEPLOYMENT_LOGGING, attributeName, deploymentUnit.getName());
        }
    }
    LoggingConfigurationService loggingConfigurationService = null;
    // Check that per-deployment logging is not turned off
    if (process) {
        LoggingLogger.ROOT_LOGGER.trace("Scanning for logging configuration files.");
        final List<DeploymentUnit> subDeployments = getSubDeployments(deploymentUnit);
        // Check for a config file
        final VirtualFile configFile = findConfigFile(root);
        if (configFile != null) {
            // Get the module
            final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
            // Create the log context and load into the selector for the module and keep a strong reference
            final LogContext logContext;
            if (isLog4jConfiguration(configFile.getName())) {
                logContext = LogContext.create(true);
            } else {
                logContext = LogContext.create();
            }
            boolean processSubdeployments = true;
            // Configure the deployments logging based on the top-level configuration file
            loggingConfigurationService = configure(root, configFile, module.getClassLoader(), logContext);
            if (loggingConfigurationService != null) {
                registerLogContext(deploymentUnit, module, logContext);
            } else {
                processSubdeployments = false;
            }
            if (processSubdeployments) {
                // Process the sub-deployments
                for (DeploymentUnit subDeployment : subDeployments) {
                    if (subDeployment.hasAttachment(Attachments.DEPLOYMENT_ROOT)) {
                        processDeployment(phaseContext, subDeployment, subDeployment.getAttachment(Attachments.DEPLOYMENT_ROOT));
                    }
                    // No configuration file found, use the top-level configuration
                    if (!hasRegisteredLogContext(subDeployment)) {
                        final Module subDeploymentModule = subDeployment.getAttachment(Attachments.MODULE);
                        registerLogContext(subDeployment, subDeploymentModule, logContext);
                    }
                    // Add the parent's logging service if it should be inherited
                    if (!subDeployment.hasAttachment(LoggingDeploymentResourceProcessor.LOGGING_CONFIGURATION_SERVICE_KEY)) {
                        subDeployment.putAttachment(LoggingDeploymentResourceProcessor.LOGGING_CONFIGURATION_SERVICE_KEY, loggingConfigurationService);
                    }
                }
            }
        } else {
            // No configuration was found, process sub-deployments for configuration files
            for (DeploymentUnit subDeployment : subDeployments) {
                if (subDeployment.hasAttachment(Attachments.DEPLOYMENT_ROOT)) {
                    processDeployment(phaseContext, subDeployment, subDeployment.getAttachment(Attachments.DEPLOYMENT_ROOT));
                }
            }
        }
    }
    // Add the configuration service
    if (loggingConfigurationService != null) {
        // Add the service to the deployment unit
        deploymentUnit.putAttachment(LoggingDeploymentResourceProcessor.LOGGING_CONFIGURATION_SERVICE_KEY, loggingConfigurationService);
    }
}
Also used : VirtualFile(org.jboss.vfs.VirtualFile) LogContext(org.jboss.logmanager.LogContext) Properties(java.util.Properties) Module(org.jboss.modules.Module) DeploymentUnit(org.jboss.as.server.deployment.DeploymentUnit)

Example 5 with LogContext

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

the class LoggingDeploymentResourceProcessor method deploy.

@Override
public final void deploy(final DeploymentPhaseContext phaseContext) {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    if (deploymentUnit.hasAttachment(Attachments.MODULE)) {
        LoggingConfigurationService loggingConfigurationService;
        if (deploymentUnit.hasAttachment(LOGGING_CONFIGURATION_SERVICE_KEY)) {
            loggingConfigurationService = deploymentUnit.getAttachment(LOGGING_CONFIGURATION_SERVICE_KEY);
            // Remove the attachment as it should no longer be needed
            deploymentUnit.removeAttachment(LOGGING_CONFIGURATION_SERVICE_KEY);
        } else {
            // Get the module
            final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
            // Set the deployments class loader to ensure we get the correct log context
            final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
            try {
                WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(module.getClassLoader());
                LogContextConfiguration logContextConfiguration = null;
                final LogContext logContext = LogContext.getLogContext();
                final Configurator configurator = logContext.getAttachment(CommonAttributes.ROOT_LOGGER_NAME, Configurator.ATTACHMENT_KEY);
                if (configurator instanceof LogContextConfiguration) {
                    logContextConfiguration = (LogContextConfiguration) configurator;
                } else if (configurator instanceof PropertyConfigurator) {
                    logContextConfiguration = ((PropertyConfigurator) configurator).getLogContextConfiguration();
                }
                loggingConfigurationService = new LoggingConfigurationService(logContextConfiguration, "default");
            } finally {
                WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current);
            }
        }
        final DeploymentResourceSupport deploymentResourceSupport = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_RESOURCE_SUPPORT);
        // Register the resources
        LoggingDeploymentResources.registerDeploymentResource(deploymentResourceSupport, loggingConfigurationService);
        phaseContext.getServiceTarget().addService(deploymentUnit.getServiceName().append("logging", "configuration"), loggingConfigurationService).install();
    }
}
Also used : LogContextConfiguration(org.jboss.logmanager.config.LogContextConfiguration) DeploymentResourceSupport(org.jboss.as.server.deployment.DeploymentResourceSupport) PropertyConfigurator(org.jboss.logmanager.PropertyConfigurator) Configurator(org.jboss.logmanager.Configurator) LogContext(org.jboss.logmanager.LogContext) Module(org.jboss.modules.Module) DeploymentUnit(org.jboss.as.server.deployment.DeploymentUnit) PropertyConfigurator(org.jboss.logmanager.PropertyConfigurator)

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