001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *      http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.apache.oozie.service;
020
021import org.apache.commons.logging.LogFactory;
022import org.apache.log4j.LogManager;
023import org.apache.log4j.PropertyConfigurator;
024import org.apache.oozie.util.XLogFilter;
025import org.apache.oozie.util.Instrumentable;
026import org.apache.oozie.util.Instrumentation;
027import org.apache.oozie.util.XLog;
028import org.apache.oozie.util.XConfiguration;
029import org.apache.oozie.BuildInfo;
030import org.apache.oozie.ErrorCode;
031import org.apache.hadoop.conf.Configuration;
032
033import java.io.File;
034import java.io.FileInputStream;
035import java.io.IOException;
036import java.io.InputStream;
037import java.net.URL;
038import java.util.Properties;
039import java.util.Map;
040import java.util.regex.Pattern;
041
042/**
043 * Built-in service that initializes and manages Logging via Log4j.
044 * <p/>
045 * Oozie Lo4gj default configuration file is <code>oozie-log4j.properties</code>.
046 * <p/>
047 * The file name can be changed by setting the Java System property <code>oozie.log4j.file</code>.
048 * <p/>
049 * The Log4j configuration files must be a properties file.
050 * <p/>
051 * The Log4j configuration file is first looked in the Oozie configuration directory see {@link ConfigurationService}.
052 * If the file is not found there, it is looked in the classpath.
053 * <p/>
054 * If the Log4j configuration file is loaded from Oozie configuration directory, automatic reloading is enabled.
055 * <p/>
056 * If the Log4j configuration file is loaded from the classpath, automatic reloading is disabled.
057 * <p/>
058 * the automatic reloading interval is defined by the Java System property <code>oozie.log4j.reload</code>. The default
059 * value is 10 seconds.
060 * <p>
061 * <p>
062 * Unlike most of the other Services, XLogService isn't easily overridable because Services depends on XLogService being available
063 */
064public class XLogService implements Service, Instrumentable {
065    private static final String INSTRUMENTATION_GROUP = "logging";
066
067    /**
068     * System property that indicates the logs directory.
069     */
070    public static final String OOZIE_LOG_DIR = "oozie.log.dir";
071
072    /**
073     * System property that indicates the log4j configuration file to load.
074     */
075    public static final String LOG4J_FILE = "oozie.log4j.file";
076
077    /**
078     * System property that indicates the reload interval of the configuration file.
079     */
080    public static final String LOG4J_RELOAD = "oozie.log4j.reload";
081
082    /**
083     * Default value for the log4j configuration file if {@link #LOG4J_FILE} is not set.
084     */
085    public static final String DEFAULT_LOG4J_PROPERTIES = "oozie-log4j.properties";
086
087    /**
088     * Default value for the reload interval if {@link #LOG4J_RELOAD} is not set.
089     */
090    public static final String DEFAULT_RELOAD_INTERVAL = "10";
091
092    private XLog log;
093    private long interval;
094    private boolean fromClasspath;
095    private String log4jFileName;
096    private boolean logOverWS = true;
097
098    private static final String STARTUP_MESSAGE = "{E}"
099            + " ******************************************************************************* {E}"
100            + "  STARTUP MSG: Oozie BUILD_VERSION [{0}] compiled by [{1}] on [{2}]{E}"
101            + "  STARTUP MSG:       revision [{3}]@[{4}]{E}"
102            + "*******************************************************************************";
103
104    private String oozieLogPath;
105    private String oozieLogName;
106    private int oozieLogRotation = -1;
107
108    public XLogService() {
109    }
110    
111    public String getOozieLogPath() {
112        return oozieLogPath;
113    }
114    
115    public String getOozieLogName() {
116        return oozieLogName;
117    }
118
119    /**
120     * Initialize the log service.
121     *
122     * @param services services instance.
123     * @throws ServiceException thrown if the log service could not be initialized.
124     */
125    public void init(Services services) throws ServiceException {
126        String oozieHome = Services.getOozieHome();
127        String oozieLogs = System.getProperty(OOZIE_LOG_DIR, oozieHome + "/logs");
128        System.setProperty(OOZIE_LOG_DIR, oozieLogs);
129        try {
130            LogManager.resetConfiguration();
131            log4jFileName = System.getProperty(LOG4J_FILE, DEFAULT_LOG4J_PROPERTIES);
132            if (log4jFileName.contains("/")) {
133                throw new ServiceException(ErrorCode.E0011, log4jFileName);
134            }
135            if (!log4jFileName.endsWith(".properties")) {
136                throw new ServiceException(ErrorCode.E0012, log4jFileName);
137            }
138            String configPath = ConfigurationService.getConfigurationDirectory();
139            File log4jFile = new File(configPath, log4jFileName);
140            if (log4jFile.exists()) {
141                fromClasspath = false;
142            }
143            else {
144                ClassLoader cl = Thread.currentThread().getContextClassLoader();
145                URL log4jUrl = cl.getResource(log4jFileName);
146                if (log4jUrl == null) {
147                    throw new ServiceException(ErrorCode.E0013, log4jFileName, configPath);
148                }
149                fromClasspath = true;
150            }
151
152            if (fromClasspath) {
153                ClassLoader cl = Thread.currentThread().getContextClassLoader();
154                URL log4jUrl = cl.getResource(log4jFileName);
155                PropertyConfigurator.configure(log4jUrl);
156            }
157            else {
158                interval = Long.parseLong(System.getProperty(LOG4J_RELOAD, DEFAULT_RELOAD_INTERVAL));
159                PropertyConfigurator.configureAndWatch(log4jFile.toString(), interval * 1000);
160            }
161
162            log = new XLog(LogFactory.getLog(getClass()));
163
164            log.info(XLog.OPS, STARTUP_MESSAGE, BuildInfo.getBuildInfo().getProperty(BuildInfo.BUILD_VERSION),
165                    BuildInfo.getBuildInfo().getProperty(BuildInfo.BUILD_USER_NAME), BuildInfo.getBuildInfo()
166                            .getProperty(BuildInfo.BUILD_TIME), BuildInfo.getBuildInfo().getProperty(
167                            BuildInfo.BUILD_VC_REVISION), BuildInfo.getBuildInfo().getProperty(BuildInfo.BUILD_VC_URL));
168
169            String from = (fromClasspath) ? "CLASSPATH" : configPath;
170            String reload = (fromClasspath) ? "disabled" : Long.toString(interval) + " sec";
171            log.info("Log4j configuration file [{0}]", log4jFileName);
172            log.info("Log4j configuration file loaded from [{0}]", from);
173            log.info("Log4j reload interval [{0}]", reload);
174
175            XLog.Info.reset();
176            XLog.Info.defineParameter(USER);
177            XLog.Info.defineParameter(GROUP);
178            XLogFilter.reset();
179            XLogFilter.defineParameter(USER);
180            XLogFilter.defineParameter(GROUP);
181
182            // Getting configuration for oozie log via WS
183            ClassLoader cl = Thread.currentThread().getContextClassLoader();
184            InputStream is = (fromClasspath) ? cl.getResourceAsStream(log4jFileName) : new FileInputStream(log4jFile);
185            extractInfoForLogWebService(is);
186        }
187        catch (IOException ex) {
188            throw new ServiceException(ErrorCode.E0010, ex.getMessage(), ex);
189        }
190    }
191
192    private void extractInfoForLogWebService(InputStream is) throws IOException {
193        logOverWS = true;
194        Properties props = new Properties();
195        props.load(is);
196
197        Configuration conf = new XConfiguration();
198        for (Map.Entry entry : props.entrySet()) {
199            conf.set((String) entry.getKey(), (String) entry.getValue());
200        }
201        String logFile = conf.get("log4j.appender.oozie.File");
202        if (logFile == null) {
203            log.warn("Oozie WS log will be disabled, missing property 'log4j.appender.oozie.File' for 'oozie' "
204                    + "appender");
205            logOverWS = false;
206        }
207        else {
208            logFile = logFile.trim();
209            int i = logFile.lastIndexOf("/");
210            if (i == -1) {
211                log.warn("Oozie WS log will be disabled, log file is not an absolute path [{0}] for 'oozie' appender",
212                        logFile);
213                logOverWS = false;
214            }
215            else {
216                String appenderClass = conf.get("log4j.appender.oozie");
217                if (appenderClass == null) {
218                    log.warn("Oozie WS log will be disabled, missing property [log4j.appender.oozie]");
219                    logOverWS = false;
220                }
221                else if (appenderClass.equals("org.apache.log4j.DailyRollingFileAppender")) {
222                    String pattern = conf.get("log4j.appender.oozie.DatePattern");
223                    if (pattern == null) {
224                        log.warn("Oozie WS log will be disabled, missing property [log4j.appender.oozie.DatePattern]");
225                        logOverWS = false;
226                    }
227                    else {
228                        pattern = pattern.trim();
229                        if (pattern.endsWith("HH")) {
230                            oozieLogRotation = 60 * 60;
231                        }
232                        else if (pattern.endsWith("dd")) {
233                                oozieLogRotation = 60 * 60 * 24;
234                        }
235                        else {
236                            log.warn("Oozie WS log will be disabled, DatePattern [{0}] should end with 'HH' or 'dd'",
237                                    pattern);
238                            logOverWS = false;
239                        }
240                        if (oozieLogRotation > 0) {
241                            oozieLogPath = logFile.substring(0, i);
242                            oozieLogName = logFile.substring(i + 1);
243                        }
244                    }
245                }
246                else if (appenderClass.equals("org.apache.log4j.rolling.RollingFileAppender")) {
247                    String pattern = conf.get("log4j.appender.oozie.RollingPolicy.FileNamePattern");
248                    if (pattern == null) {
249                        log.warn("Oozie WS log will be disabled, missing property "
250                                + "[log4j.appender.oozie.RollingPolicy.FileNamePattern]");
251                        logOverWS = false;
252                    }
253                    else {
254                        pattern = pattern.trim();
255                        if (pattern.matches(Pattern.quote(logFile) + ".*-%d\\{yyyy-MM-dd-HH\\}(\\.gz)?")) {
256                            oozieLogRotation = 60 * 60;
257                        }
258                        else {
259                            log.warn("Oozie WS log will be disabled, RollingPolicy.FileNamePattern [{0}] should end with " 
260                                    + "'-%d{yyyy-MM-dd-HH}' or '-%d{yyyy-MM-dd-HH}.gz' and also start with the value of "
261                                    + "log4j.appender.oozie.File [{1}]", pattern, logFile);
262                            logOverWS = false;
263                        }
264                        if (oozieLogRotation > 0) {
265                            oozieLogPath = logFile.substring(0, i);
266                            oozieLogName = logFile.substring(i + 1);
267                        }
268                    }
269                }
270                else {
271                    log.warn("Oozie WS log will be disabled, log4j.appender.oozie [" + appenderClass + "] should be "
272                            + "either org.apache.log4j.DailyRollingFileAppender or org.apache.log4j.rolling.RollingFileAppender "
273                            + "to enable it");
274                    logOverWS = false;
275                }
276            }
277        }
278    }
279
280    /**
281     * Destroy the log service.
282     */
283    public void destroy() {
284        LogManager.shutdown();
285        XLog.Info.reset();
286        XLogFilter.reset();
287    }
288
289    /**
290     * Group log info constant.
291     */
292    public static final String USER = "USER";
293
294    /**
295     * Group log info constant.
296     */
297    public static final String GROUP = "GROUP";
298
299    /**
300     * Return the public interface for log service.
301     *
302     * @return {@link XLogService}.
303     */
304    public Class<? extends Service> getInterface() {
305        return XLogService.class;
306    }
307
308    /**
309     * Instruments the log service.
310     * <p/>
311     * It sets instrumentation variables indicating the config file, reload interval and if loaded from the classpath.
312     *
313     * @param instr instrumentation to use.
314     */
315    public void instrument(Instrumentation instr) {
316        instr.addVariable(INSTRUMENTATION_GROUP, "config.file", new Instrumentation.Variable<String>() {
317            public String getValue() {
318                return log4jFileName;
319            }
320        });
321        instr.addVariable(INSTRUMENTATION_GROUP, "reload.interval", new Instrumentation.Variable<Long>() {
322            public Long getValue() {
323                return interval;
324            }
325        });
326        instr.addVariable(INSTRUMENTATION_GROUP, "from.classpath", new Instrumentation.Variable<Boolean>() {
327            public Boolean getValue() {
328                return fromClasspath;
329            }
330        });
331        instr.addVariable(INSTRUMENTATION_GROUP, "log.over.web-service", new Instrumentation.Variable<Boolean>() {
332            public Boolean getValue() {
333                return logOverWS;
334            }
335        });
336    }
337
338    boolean getLogOverWS() {
339        return logOverWS;
340    }
341
342    int getOozieLogRotation() {
343        return oozieLogRotation;
344    }
345
346    String getLog4jProperties() {
347        return log4jFileName;
348    }
349
350    boolean getFromClasspath() {
351        return fromClasspath;
352    }
353
354}