1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2022, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.classic.model.processor;
15  
16  import ch.qos.logback.classic.joran.ReconfigureOnChangeTask;
17  import ch.qos.logback.classic.model.ConfigurationModel;
18  import ch.qos.logback.core.Context;
19  import ch.qos.logback.core.joran.util.ConfigurationWatchListUtil;
20  import ch.qos.logback.core.model.Model;
21  import ch.qos.logback.core.model.processor.ModelHandlerBase;
22  import ch.qos.logback.core.model.processor.ModelHandlerException;
23  import ch.qos.logback.core.model.processor.ModelInterpretationContext;
24  import ch.qos.logback.core.spi.ConfigurationEvent;
25  import ch.qos.logback.core.util.Duration;
26  import ch.qos.logback.core.util.OptionHelper;
27  
28  import java.net.URL;
29  import java.util.concurrent.ScheduledExecutorService;
30  import java.util.concurrent.ScheduledFuture;
31  import java.util.concurrent.TimeUnit;
32  
33  /**
34   * This is a subclass of {@link ConfigurationModelHandler} offering configuration reloading support.
35   *
36   */
37  public class ConfigurationModelHandlerFull extends ConfigurationModelHandler {
38  
39      public static String FAILED_WATCH_PREDICATE_MESSAGE_1 = "Missing watchable .xml or .properties files.";
40      public static String FAILED_WATCH_PREDICATE_MESSAGE_2 = "Watching .xml files requires that the main configuration file is reachable as a URL";
41  
42      public ConfigurationModelHandlerFull(Context context) {
43          super(context);
44      }
45  
46      static public ModelHandlerBase makeInstance2(Context context, ModelInterpretationContext mic) {
47          return new ConfigurationModelHandlerFull(context);
48      }
49  
50      @Override
51      protected void processScanAttrib(ModelInterpretationContext mic, ConfigurationModel configurationModel) {
52          // override parent to do nothing
53      }
54  
55      @Override
56      public void postHandle(ModelInterpretationContext mic, Model model) throws ModelHandlerException {
57          ConfigurationModel configurationModel = (ConfigurationModel) model;
58          // post handling of scan attribute works even we need to watch for included files because the main url is
59          // set in GenericXMLConfigurator very early in the configuration process
60          postProcessScanAttrib(mic, configurationModel);
61      }
62  
63      protected void postProcessScanAttrib(ModelInterpretationContext mic, ConfigurationModel configurationModel) {
64          String scanStr = mic.subst(configurationModel.getScanStr());
65          String scanPeriodStr = mic.subst(configurationModel.getScanPeriodStr());
66          detachedPostProcess(scanStr, scanPeriodStr);
67      }
68  
69      /**
70       * This method is called from this class but also from logback-tyler.
71       *
72       * This method assumes that the variables scanStr and scanPeriodStr have undergone variable substitution
73       * as applicable to their current environment
74       *
75       * @param scanStr
76       * @param scanPeriodStr
77       * @since 1.5.0
78       */
79      public void detachedPostProcess(String scanStr, String scanPeriodStr) {
80          if (!OptionHelper.isNullOrEmptyOrAllSpaces(scanStr) && !"false".equalsIgnoreCase(scanStr)) {
81              ScheduledExecutorService scheduledExecutorService = context.getScheduledExecutorService();
82              boolean watchPredicateFulfilled = ConfigurationWatchListUtil.watchPredicateFulfilled(context);
83              if (!watchPredicateFulfilled) {
84                  addWarn(FAILED_WATCH_PREDICATE_MESSAGE_1);
85                  addWarn(FAILED_WATCH_PREDICATE_MESSAGE_2);
86                  return;
87              }
88              ReconfigureOnChangeTask rocTask = new ReconfigureOnChangeTask();
89              rocTask.setContext(context);
90  
91              addInfo("Registering a new ReconfigureOnChangeTask " + rocTask);
92  
93              context.fireConfigurationEvent(ConfigurationEvent.newConfigurationChangeDetectorRegisteredEvent(rocTask));
94  
95              Duration duration = getDurationOfScanPeriodAttribute(scanPeriodStr, SCAN_PERIOD_DEFAULT);
96  
97              addInfo("Will scan for changes in [" + ConfigurationWatchListUtil.getConfigurationWatchList(context) + "] ");
98              // Given that included files are encountered at a later phase, the complete list
99              // of files to scan can only be determined when the configuration is loaded in full.
100             // However, scan can be active if mainURL is set. Otherwise, when changes are
101             // detected the top level config file cannot be accessed.
102             addInfo("Setting ReconfigureOnChangeTask scanning period to " + duration);
103 
104             ScheduledFuture<?> scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(rocTask, duration.getMilliseconds(), duration.getMilliseconds(),
105                             TimeUnit.MILLISECONDS);
106             rocTask.setScheduredFuture(scheduledFuture);
107             context.addScheduledFuture(scheduledFuture);
108         }
109 
110     }
111 
112     private Duration getDurationOfScanPeriodAttribute(String scanPeriodAttrib, Duration defaultDuration) {
113         Duration duration = null;
114 
115         if (!OptionHelper.isNullOrEmptyOrAllSpaces(scanPeriodAttrib)) {
116             try {
117                 duration = Duration.valueOf(scanPeriodAttrib);
118             } catch (IllegalStateException | IllegalArgumentException e) {
119                 addWarn("Failed to parse 'scanPeriod' attribute [" + scanPeriodAttrib + "]", e);
120                 // default duration will be set below
121             }
122         }
123 
124         if (duration == null) {
125             addInfo("No 'scanPeriod' specified. Defaulting to " + defaultDuration.toString());
126             duration = defaultDuration;
127         }
128         return duration;
129     }
130 }