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 */
018package org.apache.hadoop.log;
019
020import java.io.*;
021import java.net.*;
022import java.util.regex.Pattern;
023
024import javax.servlet.*;
025import javax.servlet.http.*;
026
027import org.apache.commons.logging.*;
028import org.apache.commons.logging.impl.*;
029import org.apache.hadoop.classification.InterfaceAudience;
030import org.apache.hadoop.classification.InterfaceStability;
031import org.apache.hadoop.conf.Configuration;
032import org.apache.hadoop.http.HttpServer2;
033import org.apache.hadoop.security.UserGroupInformation;
034import org.apache.hadoop.util.ServletUtil;
035
036/**
037 * Change log level in runtime.
038 */
039@InterfaceStability.Evolving
040public class LogLevel {
041  public static final String USAGES = "\nUsage: General options are:\n"
042      + "\t[-getlevel <host:httpPort> <name>]\n"
043      + "\t[-setlevel <host:httpPort> <name> <level>]\n";
044
045  /**
046   * A command line implementation
047   */
048  public static void main(String[] args) {
049    String httpScheme = UserGroupInformation.isSecurityEnabled()
050      ? "https://"
051      : "http://";
052
053    if (args.length == 3 && "-getlevel".equals(args[0])) {
054      process(httpScheme + args[1] + "/logLevel?log=" + args[2]);
055      return;
056    }
057    else if (args.length == 4 && "-setlevel".equals(args[0])) {
058      process(httpScheme + args[1] + "/logLevel?log=" + args[2]
059              + "&level=" + args[3]);
060      return;
061    }
062
063    System.err.println(USAGES);
064    System.exit(-1);
065  }
066
067  private static void process(String urlstring) {
068    try {
069      URL url = new URL(urlstring);
070      System.out.println("Connecting to " + url);
071
072      URLConnection connection = UserGroupInformation.isSecurityEnabled()
073        ? SecureHTTPURLConnectionProvider.openConnection(url)
074        : url.openConnection();
075
076      connection.connect();
077
078      BufferedReader in = new BufferedReader(new InputStreamReader(
079          connection.getInputStream()));
080      for(String line; (line = in.readLine()) != null; )
081        if (line.startsWith(MARKER)) {
082          System.out.println(TAG.matcher(line).replaceAll(""));
083        }
084      in.close();
085    } catch (IOException ioe) {
086      System.err.println("" + ioe);
087    }
088  }
089
090  static final String MARKER = "<!-- OUTPUT -->";
091  static final Pattern TAG = Pattern.compile("<[^>]*>");
092
093  /**
094   * A servlet implementation
095   */
096  @InterfaceAudience.LimitedPrivate({"HDFS", "MapReduce"})
097  @InterfaceStability.Unstable
098  public static class Servlet extends HttpServlet {
099    private static final long serialVersionUID = 1L;
100
101    @Override
102    public void doGet(HttpServletRequest request, HttpServletResponse response
103        ) throws ServletException, IOException {
104
105      // Do the authorization
106      if (!HttpServer2.hasAdministratorAccess(getServletContext(), request,
107          response)) {
108        return;
109      }
110
111      PrintWriter out = ServletUtil.initHTML(response, "Log Level");
112      String logName = ServletUtil.getParameter(request, "log");
113      String level = ServletUtil.getParameter(request, "level");
114
115      if (logName != null) {
116        out.println("<br /><hr /><h3>Results</h3>");
117        out.println(MARKER
118            + "Submitted Log Name: <b>" + logName + "</b><br />");
119
120        Log log = LogFactory.getLog(logName);
121        out.println(MARKER
122            + "Log Class: <b>" + log.getClass().getName() +"</b><br />");
123        if (level != null) {
124          out.println(MARKER + "Submitted Level: <b>" + level + "</b><br />");
125        }
126
127        if (log instanceof Log4JLogger) {
128          process(((Log4JLogger)log).getLogger(), level, out);
129        }
130        else if (log instanceof Jdk14Logger) {
131          process(((Jdk14Logger)log).getLogger(), level, out);
132        }
133        else {
134          out.println("Sorry, " + log.getClass() + " not supported.<br />");
135        }
136      }
137
138      out.println(FORMS);
139      out.println(ServletUtil.HTML_TAIL);
140    }
141
142    static final String FORMS = "\n<br /><hr /><h3>Get / Set</h3>"
143        + "\n<form>Log: <input type='text' size='50' name='log' /> "
144        + "<input type='submit' value='Get Log Level' />"
145        + "</form>"
146        + "\n<form>Log: <input type='text' size='50' name='log' /> "
147        + "Level: <input type='text' name='level' /> "
148        + "<input type='submit' value='Set Log Level' />"
149        + "</form>";
150
151    private static void process(org.apache.log4j.Logger log, String level,
152        PrintWriter out) throws IOException {
153      if (level != null) {
154        if (!level.equals(org.apache.log4j.Level.toLevel(level).toString())) {
155          out.println(MARKER + "Bad level : <b>" + level + "</b><br />");
156        } else {
157          log.setLevel(org.apache.log4j.Level.toLevel(level));
158          out.println(MARKER + "Setting Level to " + level + " ...<br />");
159        }
160      }
161      out.println(MARKER
162          + "Effective level: <b>" + log.getEffectiveLevel() + "</b><br />");
163    }
164
165    private static void process(java.util.logging.Logger log, String level,
166        PrintWriter out) throws IOException {
167      if (level != null) {
168        log.setLevel(java.util.logging.Level.parse(level));
169        out.println(MARKER + "Setting Level to " + level + " ...<br />");
170      }
171
172      java.util.logging.Level lev;
173      for(; (lev = log.getLevel()) == null; log = log.getParent());
174      out.println(MARKER + "Effective level: <b>" + lev + "</b><br />");
175    }
176  }
177}