001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2022, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.classic.model.processor;
015
016import ch.qos.logback.classic.joran.ReconfigureOnChangeTask;
017import ch.qos.logback.classic.model.ConfigurationModel;
018import ch.qos.logback.core.Context;
019import ch.qos.logback.core.joran.util.ConfigurationWatchListUtil;
020import ch.qos.logback.core.model.Model;
021import ch.qos.logback.core.model.processor.ModelHandlerBase;
022import ch.qos.logback.core.model.processor.ModelHandlerException;
023import ch.qos.logback.core.model.processor.ModelInterpretationContext;
024import ch.qos.logback.core.spi.ConfigurationEvent;
025import ch.qos.logback.core.util.Duration;
026import ch.qos.logback.core.util.OptionHelper;
027
028import java.net.URL;
029import java.util.concurrent.ScheduledExecutorService;
030import java.util.concurrent.ScheduledFuture;
031import java.util.concurrent.TimeUnit;
032
033/**
034 * This is a subclass of {@link ConfigurationModelHandler} offering configuration reloading support.
035 *
036 */
037public class ConfigurationModelHandlerFull extends ConfigurationModelHandler {
038
039    public static String FAILED_WATCH_PREDICATE_MESSAGE_1 = "Missing watchable .xml or .properties files.";
040    public static String FAILED_WATCH_PREDICATE_MESSAGE_2 = "Watching .xml files requires that the main configuration file is reachable as a URL";
041
042    public ConfigurationModelHandlerFull(Context context) {
043        super(context);
044    }
045
046    static public ModelHandlerBase makeInstance2(Context context, ModelInterpretationContext mic) {
047        return new ConfigurationModelHandlerFull(context);
048    }
049
050    @Override
051    protected void processScanAttrib(ModelInterpretationContext mic, ConfigurationModel configurationModel) {
052
053    }
054
055    @Override
056    public void postHandle(ModelInterpretationContext mic, Model model) throws ModelHandlerException {
057        ConfigurationModel configurationModel = (ConfigurationModel) model;
058        postProcessScanAttrib(mic, configurationModel);
059    }
060
061    protected void postProcessScanAttrib(ModelInterpretationContext mic, ConfigurationModel configurationModel) {
062        String scanStr = mic.subst(configurationModel.getScanStr());
063        String scanPeriodStr = mic.subst(configurationModel.getScanPeriodStr());
064        detachedPostProcess(scanStr, scanPeriodStr);
065    }
066
067    /**
068     * This method is called from this class but also from logback-tyler.
069     *
070     * This method assumes that the variables scanStr and scanPeriodStr have undergone variable substitution
071     * as applicable to their current environment
072     *
073     * @param scanStr
074     * @param scanPeriodStr
075     * @since 1.5.0
076     */
077    public void detachedPostProcess(String scanStr, String scanPeriodStr) {
078        if (!OptionHelper.isNullOrEmptyOrAllSpaces(scanStr) && !"false".equalsIgnoreCase(scanStr)) {
079            ScheduledExecutorService scheduledExecutorService = context.getScheduledExecutorService();
080            boolean watchPredicateFulfilled = ConfigurationWatchListUtil.watchPredicateFulfilled(context);
081            if (!watchPredicateFulfilled) {
082                addWarn(FAILED_WATCH_PREDICATE_MESSAGE_1);
083                addWarn(FAILED_WATCH_PREDICATE_MESSAGE_2);
084                return;
085            }
086            ReconfigureOnChangeTask rocTask = new ReconfigureOnChangeTask();
087            rocTask.setContext(context);
088
089            addInfo("Registering a new ReconfigureOnChangeTask " + rocTask);
090
091            context.fireConfigurationEvent(ConfigurationEvent.newConfigurationChangeDetectorRegisteredEvent(rocTask));
092
093            Duration duration = getDurationOfScanPeriodAttribute(scanPeriodStr, SCAN_PERIOD_DEFAULT);
094
095            addInfo("Will scan for changes in [" + ConfigurationWatchListUtil.getConfigurationWatchList(context) + "] ");
096            // Given that included files are encountered at a later phase, the complete list
097            // of files to scan can only be determined when the configuration is loaded in full.
098            // However, scan can be active if mainURL is set. Otherwise, when changes are
099            // detected the top level config file cannot be accessed.
100            addInfo("Setting ReconfigureOnChangeTask scanning period to " + duration);
101
102            ScheduledFuture<?> scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(rocTask, duration.getMilliseconds(), duration.getMilliseconds(),
103                            TimeUnit.MILLISECONDS);
104            rocTask.setScheduredFuture(scheduledFuture);
105            context.addScheduledFuture(scheduledFuture);
106        }
107
108    }
109
110    private Duration getDurationOfScanPeriodAttribute(String scanPeriodAttrib, Duration defaultDuration) {
111        Duration duration = null;
112
113        if (!OptionHelper.isNullOrEmptyOrAllSpaces(scanPeriodAttrib)) {
114            try {
115                duration = Duration.valueOf(scanPeriodAttrib);
116            } catch (IllegalStateException | IllegalArgumentException e) {
117                addWarn("Failed to parse 'scanPeriod' attribute [" + scanPeriodAttrib + "]", e);
118                // default duration will be set below
119            }
120        }
121
122        if (duration == null) {
123            addInfo("No 'scanPeriod' specified. Defaulting to " + defaultDuration.toString());
124            duration = defaultDuration;
125        }
126        return duration;
127    }
128}