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.joran;
15  
16  import java.io.File;
17  import java.net.URL;
18  import java.util.List;
19  import java.util.concurrent.ScheduledFuture;
20  
21  import ch.qos.logback.classic.LoggerContext;
22  import ch.qos.logback.core.CoreConstants;
23  import ch.qos.logback.core.joran.spi.ConfigurationWatchList;
24  import ch.qos.logback.core.joran.spi.JoranException;
25  import ch.qos.logback.core.joran.util.ConfigurationWatchListUtil;
26  import ch.qos.logback.core.model.Model;
27  import ch.qos.logback.core.model.ModelUtil;
28  import ch.qos.logback.core.spi.ConfigurationEvent;
29  import ch.qos.logback.core.spi.ContextAwareBase;
30  import ch.qos.logback.core.status.StatusUtil;
31  
32  import static ch.qos.logback.core.CoreConstants.PROPERTIES_FILE_EXTENSION;
33  import static ch.qos.logback.core.spi.ConfigurationEvent.*;
34  
35  public class ReconfigureOnChangeTask extends ContextAwareBase implements Runnable {
36  
37      public static final String DETECTED_CHANGE_IN_CONFIGURATION_FILES = "Detected change in configuration files.";
38      public static final String RE_REGISTERING_PREVIOUS_SAFE_CONFIGURATION = "Re-registering previous fallback configuration once more as a fallback configuration point";
39      public static final String FALLING_BACK_TO_SAFE_CONFIGURATION = "Given previous errors, falling back to previously registered safe configuration.";
40  
41      long birthdate = System.currentTimeMillis();
42      List<ReconfigureOnChangeTaskListener> listeners = null;
43  
44      ScheduledFuture<?> scheduledFuture;
45  
46      @Override
47      public void run() {
48          context.fireConfigurationEvent(newConfigurationChangeDetectorRunningEvent(this));
49  
50          ConfigurationWatchList configurationWatchList = ConfigurationWatchListUtil.getConfigurationWatchList(context);
51          if (configurationWatchList == null) {
52              addWarn("Empty ConfigurationWatchList in context");
53              return;
54          }
55  
56          if (configurationWatchList.emptyWatchLists()) {
57              addInfo("Both watch lists are empty. Disabling ");
58              return;
59          }
60  
61          File changedFile = configurationWatchList.changeDetectedInFile();
62          URL changedURL = configurationWatchList.changeDetectedInURL();
63  
64          if (changedFile == null && changedURL == null) {
65              return;
66          }
67  
68          context.fireConfigurationEvent(ConfigurationEvent.newConfigurationChangeDetectedEvent(this));
69          addInfo(DETECTED_CHANGE_IN_CONFIGURATION_FILES);
70  
71          if(changedFile != null) {
72              changeInFile(changedFile, configurationWatchList);
73          }
74  
75          if(changedURL != null) {
76              changeInURL(changedURL);
77          }
78      }
79  
80      private void changeInURL(URL url) {
81          String path = url.getPath();
82          if(path.endsWith(PROPERTIES_FILE_EXTENSION)) {
83              runPropertiesConfigurator(url);
84          }
85      }
86      private void changeInFile(File changedFile, ConfigurationWatchList configurationWatchList) {
87          if(changedFile.getName().endsWith(PROPERTIES_FILE_EXTENSION)) {
88              runPropertiesConfigurator(changedFile);
89              return;
90          }
91  
92          // ======== fuller processing below
93          addInfo(CoreConstants.RESET_MSG_PREFIX + "named [" + context.getName() + "]");
94          cancelFutureInvocationsOfThisTaskInstance();
95          URL mainConfigurationURL = configurationWatchList.getMainURL();
96  
97          LoggerContext lc = (LoggerContext) context;
98          if (mainConfigurationURL.toString().endsWith("xml")) {
99              performXMLConfiguration(lc, mainConfigurationURL);
100         } else if (mainConfigurationURL.toString().endsWith("groovy")) {
101             addError("Groovy configuration disabled due to Java 9 compilation issues.");
102         }
103     }
104 
105     private void runPropertiesConfigurator(Object changedObject) {
106         addInfo("Will run PropertyConfigurator on "+changedObject);
107         PropertiesConfigurator propertiesConfigurator = new PropertiesConfigurator();
108         propertiesConfigurator.setContext(context);
109         try {
110             if(changedObject instanceof File) {
111                 File changedFile = (File) changedObject;
112                 propertiesConfigurator.doConfigure(changedFile);
113             } else if(changedObject instanceof URL) {
114                 URL changedURL = (URL) changedObject;
115                 propertiesConfigurator.doConfigure(changedURL);
116             }
117             context.fireConfigurationEvent(newPartialConfigurationEndedSuccessfullyEvent(this));
118         } catch (JoranException e) {
119             addError("Failed to reload "+ changedObject);
120         }
121     }
122 
123     private void cancelFutureInvocationsOfThisTaskInstance() {
124         boolean result = scheduledFuture.cancel(false);
125         if(!result) {
126             addWarn("could not cancel "+ this.toString());
127         }
128     }
129 
130     private void performXMLConfiguration(LoggerContext lc, URL mainConfigurationURL) {
131         JoranConfigurator jc = new JoranConfigurator();
132         jc.setContext(context);
133         StatusUtil statusUtil = new StatusUtil(context);
134         Model failsafeTop = jc.recallSafeConfiguration();
135         URL mainURL = ConfigurationWatchListUtil.getMainWatchURL(context);
136         addInfo("Resetting loggerContext ["+lc.getName()+"]");
137         lc.reset();
138         long threshold = System.currentTimeMillis();
139         try {
140             jc.doConfigure(mainConfigurationURL);
141             // e.g. IncludeAction will add a status regarding XML parsing errors but no exception will reach here
142             if (statusUtil.hasXMLParsingErrors(threshold)) {
143                 fallbackConfiguration(lc, failsafeTop, mainURL);
144             }
145         } catch (JoranException e) {
146             addWarn("Exception occurred during reconfiguration", e);
147             fallbackConfiguration(lc, failsafeTop, mainURL);
148         }
149     }
150 
151     private void fallbackConfiguration(LoggerContext lc, Model failsafeTop, URL mainURL) {
152         // failsafe events are used only in case of errors. Therefore, we must *not*
153         // invoke file inclusion since the included files may be the cause of the error.
154 
155         // List<SaxEvent> failsafeEvents = removeIncludeEvents(eventList);
156         JoranConfigurator joranConfigurator = new JoranConfigurator();
157         joranConfigurator.setContext(context);
158         ConfigurationWatchList oldCWL = ConfigurationWatchListUtil.getConfigurationWatchList(context);
159         ConfigurationWatchList newCWL = oldCWL.buildClone();
160 
161         if (failsafeTop == null) {
162             addWarn("No previous configuration to fall back on.");
163             return;
164         } else {
165             addWarn(FALLING_BACK_TO_SAFE_CONFIGURATION);
166             addInfo("Safe model "+failsafeTop);
167             try {
168                 lc.reset();
169                 ConfigurationWatchListUtil.registerConfigurationWatchList(context, newCWL);
170                 ModelUtil.resetForReuse(failsafeTop);
171                 joranConfigurator.processModel(failsafeTop);
172                 addInfo(RE_REGISTERING_PREVIOUS_SAFE_CONFIGURATION);
173                 joranConfigurator.registerSafeConfiguration(failsafeTop);
174                 context.fireConfigurationEvent(newConfigurationEndedSuccessfullyEvent(this));
175             } catch (Exception e) {
176                 addError("Unexpected exception thrown by a configuration considered safe.", e);
177             }
178         }
179     }
180 
181     @Override
182     public String toString() {
183         return "ReconfigureOnChangeTask(born:" + birthdate + ")";
184     }
185 
186 
187     public void setScheduredFuture(ScheduledFuture<?> aScheduledFuture) {
188         this.scheduledFuture = aScheduledFuture;
189     }
190 }