Search in sources :

Example 41 with DistributionConfig

use of org.apache.geode.distributed.internal.DistributionConfig in project geode by apache.

the class LogWriterAppenders method createLogWriterAppender.

/**
   * Creates the log writer appender for a distributed system based on the system's parsed
   * configuration. The initial banner and messages are also entered into the log by this method.
   * 
   * @param isLoner Whether the distributed system is a loner or not
   * @param isSecurity Whether a log for security related messages has to be created
   * @param config The DistributionConfig for the target distributed system
   * @param logConfig if true log the configuration
   * @throws GemFireIOException if the log file can't be opened for writing
   */
static LogWriterAppender createLogWriterAppender(final boolean appendToFile, final boolean isLoner, final boolean isSecurity, final LogConfig config, final boolean logConfig) {
    final boolean isDistributionConfig = config instanceof DistributionConfig;
    final DistributionConfig dsConfig = isDistributionConfig ? (DistributionConfig) config : null;
    File logFile = config.getLogFile();
    String firstMsg = null;
    boolean firstMsgWarning = false;
    AlertAppender.getInstance().setAlertingDisabled(isLoner);
    // security-log-file is specified in DistributionConfig
    if (isSecurity) {
        if (isDistributionConfig) {
            File tmpLogFile = dsConfig.getSecurityLogFile();
            if (tmpLogFile != null && !tmpLogFile.equals(new File(""))) {
                logFile = tmpLogFile;
            }
        } else {
            throw new IllegalArgumentException("DistributionConfig is expected for SecurityLogWriter");
        }
    }
    // log-file is NOT specified in DistributionConfig
    if (logFile == null || logFile.equals(new File(""))) {
        // out = System.out;
        return null;
    }
    // if logFile exists attempt to rename it for rolling
    if (logFile.exists()) {
        final boolean useChildLogging = config.getLogFile() != null && !config.getLogFile().equals(new File("")) && config.getLogFileSizeLimit() != 0;
        final boolean statArchivesRolling = isDistributionConfig && dsConfig.getStatisticArchiveFile() != null && !dsConfig.getStatisticArchiveFile().equals(new File("")) && dsConfig.getArchiveFileSizeLimit() != 0 && dsConfig.getStatisticSamplingEnabled();
        if (!appendToFile || useChildLogging || statArchivesRolling) {
            // check useChildLogging for
            // bug 50659
            final File oldMain = ManagerLogWriter.getLogNameForOldMainLog(logFile, isSecurity || useChildLogging || statArchivesRolling);
            final boolean succeeded = LogFileUtils.renameAggressively(logFile, oldMain);
            if (succeeded) {
                firstMsg = LocalizedStrings.InternalDistributedSystem_RENAMED_OLD_LOG_FILE_TO_0.toLocalizedString(oldMain);
            } else {
                firstMsgWarning = true;
                firstMsg = LocalizedStrings.InternalDistributedSystem_COULD_NOT_RENAME_0_TO_1.toLocalizedString(new Object[] { logFile, oldMain });
            }
        }
    }
    // create a FileOutputStream to the logFile
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(logFile, true);
    } catch (FileNotFoundException ex) {
        String s = LocalizedStrings.InternalDistributedSystem_COULD_NOT_OPEN_LOG_FILE_0.toLocalizedString(logFile);
        throw new GemFireIOException(s, ex);
    }
    final PrintStream out = new PrintStream(fos);
    // create the ManagerLogWriter that LogWriterAppender will wrap
    ManagerLogWriter mlw = null;
    String logWriterLoggerName = null;
    if (isSecurity) {
        mlw = new SecurityManagerLogWriter(dsConfig.getSecurityLogLevel(), out, config.getName());
        logWriterLoggerName = LogService.SECURITY_LOGGER_NAME;
    } else {
        mlw = new ManagerLogWriter(config.getLogLevel(), out, config.getName());
        logWriterLoggerName = LogService.MAIN_LOGGER_NAME;
    }
    mlw.setConfig(config);
    // if (mlw.infoEnabled()) { -- skip here and instead do this in LogWriterFactory when creating
    // the LogWriterLogger
    // if (!isLoner /* do this on a loner to fix bug 35602 */
    // || !Boolean.getBoolean(InternalLocator.INHIBIT_DM_BANNER)) {
    // mlw.info(Banner.getString(null));
    // }
    // }
    AppenderContext[] appenderContext = new AppenderContext[1];
    if (isSecurity) {
        appenderContext[0] = LogService.getAppenderContext(LogService.SECURITY_LOGGER_NAME);
    } else {
        // ROOT or
        appenderContext[0] = LogService.getAppenderContext();
    // gemfire.logging.appenders.LOGGER
    }
    // create the LogWriterAppender that delegates to ManagerLogWriter;
    final LogWriterAppender appender = LogWriterAppender.create(appenderContext, logWriterLoggerName, mlw, fos);
    // #51819
    if (!isSecurity && LogService.MAIN_LOGGER_NAME.equals(logWriterLoggerName) && LogService.isUsingGemFireDefaultConfig()) {
        LogService.removeConsoleAppender();
    }
    // log the first msg about renaming logFile for rolling if it pre-existed
    final InternalLogWriter logWriter = mlw;
    if (firstMsg != null) {
        if (firstMsgWarning) {
            logWriter.warning(firstMsg);
        } else {
            logWriter.info(firstMsg);
        }
    }
    // log the config
    if (logConfig) {
        if (!isLoner) {
            // LOG:CONFIG: changed from config to info
            logWriter.info(LocalizedStrings.InternalDistributedSystem_STARTUP_CONFIGURATIONN_0, config.toLoggerString());
        }
    }
    // LOG: do NOT allow redirectOutput
    if (ALLOW_REDIRECT) {
        // fix #46493 by moving redirectOutput invocation here
        if (ProcessLauncherContext.isRedirectingOutput()) {
            try {
                OSProcess.redirectOutput(config.getLogFile());
            } catch (IOException e) {
                logWriter.error(e);
            // throw new GemFireIOException("Unable to redirect output to " + config.getLogFile(), e);
            }
        }
    }
    return appender;
}
Also used : GemFireIOException(org.apache.geode.GemFireIOException) DistributionConfig(org.apache.geode.distributed.internal.DistributionConfig) GemFireIOException(org.apache.geode.GemFireIOException)

Example 42 with DistributionConfig

use of org.apache.geode.distributed.internal.DistributionConfig in project geode by apache.

the class AlterRuntimeConfigFunction method execute.

@Override
public void execute(FunctionContext context) {
    String memberId = "";
    try {
        Object arg = context.getArguments();
        InternalCache cache = getCache();
        DistributionConfig config = cache.getInternalDistributedSystem().getConfig();
        memberId = cache.getDistributedSystem().getDistributedMember().getId();
        Map<String, String> runtimeAttributes = (Map<String, String>) arg;
        Set<Entry<String, String>> entries = runtimeAttributes.entrySet();
        for (Entry<String, String> entry : entries) {
            String attributeName = entry.getKey();
            String attributeValue = entry.getValue();
            if (attributeName.equals(CliStrings.ALTER_RUNTIME_CONFIG__COPY__ON__READ)) {
                cache.setCopyOnRead(Boolean.parseBoolean(attributeValue));
            } else if (attributeName.equals(CliStrings.ALTER_RUNTIME_CONFIG__LOCK__LEASE)) {
                cache.setLockLease(Integer.parseInt(attributeValue));
            } else if (attributeName.equals(CliStrings.ALTER_RUNTIME_CONFIG__LOCK__TIMEOUT)) {
                int lockTimeout = Integer.parseInt(attributeValue);
                cache.setLockTimeout(lockTimeout);
            } else if (attributeName.equals(CliStrings.ALTER_RUNTIME_CONFIG__SEARCH__TIMEOUT)) {
                cache.setSearchTimeout(Integer.parseInt(attributeValue));
            } else if (attributeName.equals(CliStrings.ALTER_RUNTIME_CONFIG__MESSAGE__SYNC__INTERVAL)) {
                cache.setMessageSyncInterval(Integer.parseInt(attributeValue));
            } else {
                config.setAttribute(attributeName, attributeValue, ConfigSource.runtime());
            }
        }
        CliFunctionResult cliFuncResult = new CliFunctionResult(memberId, true, null);
        context.getResultSender().lastResult(cliFuncResult);
    } catch (CacheClosedException cce) {
        CliFunctionResult result = new CliFunctionResult(memberId, false, null);
        context.getResultSender().lastResult(result);
    } catch (Exception e) {
        logger.error("Exception happened on : " + memberId, e);
        CliFunctionResult cliFuncResult = new CliFunctionResult(memberId, e, CliUtil.stackTraceAsString(e));
        context.getResultSender().lastResult(cliFuncResult);
    }
}
Also used : InternalCache(org.apache.geode.internal.cache.InternalCache) CacheClosedException(org.apache.geode.cache.CacheClosedException) CacheClosedException(org.apache.geode.cache.CacheClosedException) DistributionConfig(org.apache.geode.distributed.internal.DistributionConfig) Entry(java.util.Map.Entry) Map(java.util.Map)

Example 43 with DistributionConfig

use of org.apache.geode.distributed.internal.DistributionConfig in project geode by apache.

the class ExportLogsFunction method execute.

@Override
public void execute(final FunctionContext context) {
    try {
        InternalCache cache = GemFireCacheImpl.getInstance();
        DistributionConfig config = cache.getInternalDistributedSystem().getConfig();
        String memberId = cache.getDistributedSystem().getMemberId();
        logger.info("ExportLogsFunction started for member {}", memberId);
        Region exportLogsRegion = createOrGetExistingExportLogsRegion(false, cache);
        Args args = (Args) context.getArguments();
        File baseLogFile = null;
        File baseStatsFile = null;
        if (args.isIncludeLogs() && !config.getLogFile().toString().isEmpty()) {
            baseLogFile = config.getLogFile().getAbsoluteFile();
        }
        if (args.isIncludeStats() && !config.getStatisticArchiveFile().toString().isEmpty()) {
            baseStatsFile = config.getStatisticArchiveFile().getAbsoluteFile();
        }
        LogFilter logFilter = new LogFilter(args.getLogLevel(), args.isThisLogLevelOnly(), args.getStartTime(), args.getEndTime());
        Path exportedZipFile = new LogExporter(logFilter, baseLogFile, baseStatsFile).export();
        // nothing to return back
        if (exportedZipFile == null) {
            context.getResultSender().lastResult(null);
            return;
        }
        logger.info("Streaming zipped file: " + exportedZipFile.toString());
        try (FileInputStream inputStream = new FileInputStream(exportedZipFile.toFile())) {
            byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) > 0) {
                if (bytesRead == BUFFER_SIZE) {
                    exportLogsRegion.put(memberId, buffer);
                } else {
                    exportLogsRegion.put(memberId, Arrays.copyOfRange(buffer, 0, bytesRead));
                }
            }
        }
        context.getResultSender().lastResult(null);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e);
        context.getResultSender().sendException(e);
    }
}
Also used : Path(java.nio.file.Path) InternalCache(org.apache.geode.internal.cache.InternalCache) FileInputStream(java.io.FileInputStream) ParseException(java.text.ParseException) IOException(java.io.IOException) DistributionConfig(org.apache.geode.distributed.internal.DistributionConfig) LogExporter(org.apache.geode.management.internal.cli.util.LogExporter) Region(org.apache.geode.cache.Region) File(java.io.File) LogFilter(org.apache.geode.management.internal.cli.util.LogFilter)

Example 44 with DistributionConfig

use of org.apache.geode.distributed.internal.DistributionConfig in project geode by apache.

the class FetchHostResponse method create.

/**
   * Returns a <code>FetchHostResponse</code> that will be returned to the specified recipient. The
   * message will contains a copy of this vm's local host.
   */
public static FetchHostResponse create(DistributionManager dm, InternalDistributedMember recipient) {
    FetchHostResponse m = new FetchHostResponse();
    m.setRecipient(recipient);
    try {
        InetAddress host = null;
        String bindAddress = dm.getConfig().getBindAddress();
        try {
            if (bindAddress != null && !bindAddress.equals(DistributionConfig.DEFAULT_BIND_ADDRESS)) {
                host = InetAddress.getByName(bindAddress);
            }
        } catch (UnknownHostException uhe) {
        // handled in the finally block
        } finally {
            if (host == null) {
                host = SocketCreator.getLocalHost();
            }
        }
        m.host = host;
        m.isDedicatedCacheServer = CacheServerLauncher.isDedicatedCacheServer;
        DistributionConfig config = dm.getSystem().getConfig();
        m.name = config.getName();
        m.workingDir = new File(System.getProperty("user.dir")).getAbsoluteFile();
        URL url = GemFireVersion.getJarURL();
        if (url == null) {
            throw new IllegalStateException(LocalizedStrings.FetchHostResponse_COULD_NOT_FIND_GEMFIREJAR.toLocalizedString());
        }
        String path = url.getPath();
        if (path.startsWith("file:")) {
            path = path.substring("file:".length());
        }
        File gemfireJar = new File(path);
        File lib = gemfireJar.getParentFile();
        File product = lib.getParentFile();
        // may thro' IOException if url is not in a proper
        m.geodeHomeDir = product.getCanonicalFile();
    // format
    } catch (Exception ex) {
        if (dm != null && !dm.getCancelCriterion().isCancelInProgress()) {
            logger.debug(ex.getMessage(), ex);
        }
        m.name = m.name != null ? m.name : DistributionConfig.DEFAULT_NAME;
        m.host = m.host != null ? m.host : null;
        m.geodeHomeDir = m.geodeHomeDir != null ? m.geodeHomeDir : new File("");
        m.workingDir = m.workingDir != null ? m.workingDir : new File(System.getProperty("user.dir")).getAbsoluteFile();
    }
    return m;
}
Also used : DistributionConfig(org.apache.geode.distributed.internal.DistributionConfig) UnknownHostException(java.net.UnknownHostException) InetAddress(java.net.InetAddress) File(java.io.File) URL(java.net.URL) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException)

Example 45 with DistributionConfig

use of org.apache.geode.distributed.internal.DistributionConfig in project geode by apache.

the class JmxManagerAdvisee method fillInProfile.

@Override
public void fillInProfile(Profile profile) {
    assert profile instanceof JmxManagerProfile;
    JmxManagerProfile jmxp = (JmxManagerProfile) profile;
    DistributionConfig dc = getSystem().getConfig();
    boolean jmxManager = dc.getJmxManager();
    String host = "";
    int port = 0;
    boolean ssl = false;
    boolean started = false;
    SystemManagementService service = (SystemManagementService) ManagementService.getExistingManagementService(this.cache);
    if (service != null) {
        jmxManager = service.isManagerCreated();
        started = service.isManager();
    }
    if (jmxManager) {
        port = dc.getJmxManagerPort();
        boolean usingJdkConfig = false;
        if (port == 0) {
            port = Integer.getInteger("com.sun.management.jmxremote.port", 0);
            if (port != 0) {
                usingJdkConfig = true;
                // the jdk default
                ssl = true;
                if (System.getProperty("com.sun.management.jmxremote.ssl") != null) {
                    ssl = Boolean.getBoolean("com.sun.management.jmxremote.ssl");
                }
            }
        }
        if (port != 0) {
            if (!usingJdkConfig) {
                SSLConfig jmxSSL = SSLConfigurationFactory.getSSLConfigForComponent(SecurableCommunicationChannel.JMX);
                ssl = jmxSSL.isEnabled();
                host = dc.getJmxManagerHostnameForClients();
                if (host == null || host.equals("")) {
                    host = dc.getJmxManagerBindAddress();
                }
            }
            if (host == null || host.equals("")) {
                try {
                    // fixes 46317
                    host = SocketCreator.getLocalHost().getHostAddress();
                } catch (UnknownHostException ex) {
                    host = "127.0.0.1";
                }
            }
        }
    }
    jmxp.setInfo(jmxManager, host, port, ssl, started);
    this.myMostRecentProfile = jmxp;
}
Also used : JmxManagerProfile(org.apache.geode.management.internal.JmxManagerAdvisor.JmxManagerProfile) SSLConfig(org.apache.geode.internal.admin.SSLConfig) DistributionConfig(org.apache.geode.distributed.internal.DistributionConfig) UnknownHostException(java.net.UnknownHostException)

Aggregations

DistributionConfig (org.apache.geode.distributed.internal.DistributionConfig)45 InternalDistributedSystem (org.apache.geode.distributed.internal.InternalDistributedSystem)19 Properties (java.util.Properties)17 File (java.io.File)14 Test (org.junit.Test)14 ConfigurationProperties (org.apache.geode.distributed.ConfigurationProperties)12 LogWriterLogger (org.apache.geode.internal.logging.log4j.LogWriterLogger)9 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)9 WaitCriterion (org.apache.geode.test.dunit.WaitCriterion)8 FileInputStream (java.io.FileInputStream)7 IOException (java.io.IOException)7 FastLogger (org.apache.geode.internal.logging.log4j.FastLogger)7 Logger (org.apache.logging.log4j.Logger)7 DistributionConfigImpl (org.apache.geode.distributed.internal.DistributionConfigImpl)5 DistributedTest (org.apache.geode.test.junit.categories.DistributedTest)5 UnknownHostException (java.net.UnknownHostException)4 Cache (org.apache.geode.cache.Cache)4 GemFireCacheImpl (org.apache.geode.internal.cache.GemFireCacheImpl)4 InternalCache (org.apache.geode.internal.cache.InternalCache)4 CommandResult (org.apache.geode.management.internal.cli.result.CommandResult)4