View Javadoc

1   /**
2   * Licensed to the Apache Software Foundation (ASF) under one
3   * or more contributor license agreements.  See the NOTICE file
4   * distributed with this work for additional information
5   * regarding copyright ownership.  The ASF licenses this file
6   * to you under the Apache License, Version 2.0 (the
7   * "License"); you may not use this file except in compliance
8   * with the License.  You may obtain a copy of the License at
9   *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18  package org.apache.hadoop.hbase.http.log;
19  
20  import static org.junit.Assert.assertEquals;
21  import static org.junit.Assert.assertFalse;
22  import static org.junit.Assert.assertNotEquals;
23  import static org.junit.Assert.assertTrue;
24  import static org.junit.Assert.fail;
25  
26  import java.io.File;
27  import java.net.BindException;
28  import java.net.SocketException;
29  import java.net.URI;
30  import java.security.PrivilegedExceptionAction;
31  import java.util.Properties;
32  import javax.net.ssl.SSLException;
33  
34  import org.apache.commons.io.FileUtils;
35  import org.apache.hadoop.HadoopIllegalArgumentException;
36  import org.apache.hadoop.conf.Configuration;
37  import org.apache.hadoop.fs.CommonConfigurationKeys;
38  import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
39  import org.apache.hadoop.fs.FileUtil;
40  import org.apache.hadoop.hbase.HBaseCommonTestingUtility;
41  import org.apache.hadoop.hbase.http.HttpConfig;
42  import org.apache.hadoop.hbase.http.HttpServer;
43  import org.apache.hadoop.hbase.http.log.LogLevel.CLI;
44  import org.apache.hadoop.hbase.http.ssl.KeyStoreTestUtil;
45  import org.apache.hadoop.hbase.testclassification.MiscTests;
46  import org.apache.hadoop.hbase.testclassification.SmallTests;
47  import org.apache.hadoop.hdfs.DFSConfigKeys;
48  import org.apache.hadoop.minikdc.MiniKdc;
49  import org.apache.hadoop.net.NetUtils;
50  import org.apache.hadoop.security.UserGroupInformation;
51  import org.apache.hadoop.security.authorize.AccessControlList;
52  import org.apache.hadoop.security.ssl.SSLFactory;
53  import org.apache.hadoop.test.GenericTestUtils;
54  import org.apache.log4j.Level;
55  import org.apache.log4j.LogManager;
56  import org.apache.log4j.Logger;
57  
58  import org.junit.AfterClass;
59  import org.junit.BeforeClass;
60  import org.junit.Test;
61  import org.junit.experimental.categories.Category;
62  
63  /**
64   * Test LogLevel.
65   */
66  @Category({MiscTests.class, SmallTests.class})
67  public class TestLogLevel {
68    private static File BASEDIR;
69    private static String keystoresDir;
70    private static String sslConfDir;
71    private static Configuration serverConf;
72    private static Configuration clientConf;
73    private static Configuration sslConf;
74    private static final String logName = TestLogLevel.class.getName();
75    private static final Logger log = LogManager.getLogger(logName);
76    private final static String PRINCIPAL = "loglevel.principal";
77    private final static String KEYTAB  = "loglevel.keytab";
78  
79    private static MiniKdc kdc;
80    private static HBaseCommonTestingUtility htu = new HBaseCommonTestingUtility();
81  
82    private static final String LOCALHOST = "localhost";
83    private static final String clientPrincipal = "client/" + LOCALHOST;
84    private static String HTTP_PRINCIPAL = "HTTP/" + LOCALHOST;
85  
86    private static final File KEYTAB_FILE = new File(
87        htu.getDataTestDir("keytab").toUri().getPath());
88  
89    @BeforeClass
90    public static void setUp() throws Exception {
91      BASEDIR = new File(htu.getDataTestDir().toUri().getPath());
92  
93      FileUtil.fullyDelete(BASEDIR);
94      if (!BASEDIR.mkdirs()) {
95        throw new Exception("unable to create the base directory for testing");
96      }
97      serverConf = new Configuration();
98      clientConf = new Configuration();
99  
100     setupSSL(BASEDIR);
101 
102     kdc = setupMiniKdc();
103     // Create two principles: a client and a HTTP principal
104     kdc.createPrincipal(KEYTAB_FILE, clientPrincipal, HTTP_PRINCIPAL);
105   }
106 
107   /**
108    * Sets up {@link MiniKdc} for testing security.
109    * Copied from HBaseTestingUtility#setupMiniKdc().
110    */
111   static private MiniKdc setupMiniKdc() throws Exception {
112     Properties conf = MiniKdc.createConf();
113     conf.put(MiniKdc.DEBUG, true);
114     MiniKdc kdc = null;
115     File dir = null;
116     // There is time lag between selecting a port and trying to bind with it. It's possible that
117     // another service captures the port in between which'll result in BindException.
118     boolean bindException;
119     int numTries = 0;
120     do {
121       try {
122         bindException = false;
123         dir = new File(htu.getDataTestDir("kdc").toUri().getPath());
124         kdc = new MiniKdc(conf, dir);
125         kdc.start();
126       } catch (BindException e) {
127         FileUtils.deleteDirectory(dir);  // clean directory
128         numTries++;
129         if (numTries == 3) {
130           log.error("Failed setting up MiniKDC. Tried " + numTries + " times.");
131           throw e;
132         }
133         log.error("BindException encountered when setting up MiniKdc. Trying again.");
134         bindException = true;
135       }
136     } while (bindException);
137     return kdc;
138   }
139 
140   static private void setupSSL(File base) throws Exception {
141     Configuration conf = new Configuration();
142     conf.set(DFSConfigKeys.DFS_HTTP_POLICY_KEY, HttpConfig.Policy.HTTPS_ONLY.name());
143     conf.set(DFSConfigKeys.DFS_NAMENODE_HTTPS_ADDRESS_KEY, "localhost:0");
144     conf.set(DFSConfigKeys.DFS_DATANODE_HTTPS_ADDRESS_KEY, "localhost:0");
145 
146     keystoresDir = base.getAbsolutePath();
147     sslConfDir = KeyStoreTestUtil.getClasspathDir(TestLogLevel.class);
148     KeyStoreTestUtil.setupSSLConfig(keystoresDir, sslConfDir, conf, false);
149 
150     sslConf = getSslConfig();
151   }
152 
153   /**
154    * Get the SSL configuration.
155    * This method is copied from KeyStoreTestUtil#getSslConfig() in Hadoop.
156    * @return {@link Configuration} instance with ssl configs loaded.
157    */
158   private static Configuration getSslConfig() {
159     Configuration sslConf = new Configuration(false);
160     String sslServerConfFile = "ssl-server.xml";
161     String sslClientConfFile = "ssl-client.xml";
162     sslConf.addResource(sslServerConfFile);
163     sslConf.addResource(sslClientConfFile);
164     sslConf.set(SSLFactory.SSL_SERVER_CONF_KEY, sslServerConfFile);
165     sslConf.set(SSLFactory.SSL_CLIENT_CONF_KEY, sslClientConfFile);
166     return sslConf;
167   }
168 
169   @AfterClass
170   public static void tearDown() {
171     if (kdc != null) {
172       kdc.stop();
173     }
174 
175     FileUtil.fullyDelete(BASEDIR);
176   }
177 
178   /**
179    * Test client command line options. Does not validate server behavior.
180    * @throws Exception if commands return unexpected results.
181    */
182   @Test(timeout=120000)
183   public void testCommandOptions() throws Exception {
184     final String className = this.getClass().getName();
185 
186     assertFalse(validateCommand(new String[] {"-foo" }));
187     // fail due to insufficient number of arguments
188     assertFalse(validateCommand(new String[] {}));
189     assertFalse(validateCommand(new String[] {"-getlevel" }));
190     assertFalse(validateCommand(new String[] {"-setlevel" }));
191     assertFalse(validateCommand(new String[] {"-getlevel", "foo.bar:8080" }));
192 
193     // valid command arguments
194     assertTrue(validateCommand(
195         new String[] {"-getlevel", "foo.bar:8080", className }));
196     assertTrue(validateCommand(
197         new String[] {"-setlevel", "foo.bar:8080", className, "DEBUG" }));
198     assertTrue(validateCommand(
199         new String[] {"-getlevel", "foo.bar:8080", className }));
200     assertTrue(validateCommand(
201         new String[] {"-setlevel", "foo.bar:8080", className, "DEBUG" }));
202 
203     // fail due to the extra argument
204     assertFalse(validateCommand(
205         new String[] {"-getlevel", "foo.bar:8080", className, "blah" }));
206     assertFalse(validateCommand(
207         new String[] {"-setlevel", "foo.bar:8080", className, "DEBUG", "blah" }));
208     assertFalse(validateCommand(
209         new String[] {
210           "-getlevel", "foo.bar:8080", className, "-setlevel", "foo.bar:8080", className }));
211   }
212 
213   /**
214    * Check to see if a command can be accepted.
215    *
216    * @param args a String array of arguments
217    * @return true if the command can be accepted, false if not.
218    */
219   private boolean validateCommand(String[] args) {
220     CLI cli = new CLI(clientConf);
221     try {
222       cli.parseArguments(args);
223     } catch (HadoopIllegalArgumentException e) {
224       return false;
225     } catch (Exception e) {
226       // this is used to verify the command arguments only.
227       // no HadoopIllegalArgumentException = the arguments are good.
228       return true;
229     }
230     return true;
231   }
232 
233   /**
234    * Creates and starts a Jetty server binding at an ephemeral port to run
235    * LogLevel servlet.
236    * @param protocol "http" or "https"
237    * @param isSpnego true if SPNEGO is enabled
238    * @return a created HttpServer object
239    * @throws Exception if unable to create or start a Jetty server
240    */
241   private HttpServer createServer(String protocol, boolean isSpnego)
242       throws Exception {
243     HttpServer.Builder builder = new HttpServer.Builder()
244         .setName("..")
245         .addEndpoint(new URI(protocol + "://localhost:0"))
246         .setFindPort(true)
247         .setConf(serverConf);
248     if (isSpnego) {
249       // Set up server Kerberos credentials.
250       // Since the server may fall back to simple authentication,
251       // use ACL to make sure the connection is Kerberos/SPNEGO authenticated.
252       builder.setSecurityEnabled(true)
253           .setUsernameConfKey(PRINCIPAL)
254           .setKeytabConfKey(KEYTAB)
255           .setACL(new AccessControlList("client"));
256     }
257 
258     // if using HTTPS, configure keystore/truststore properties.
259     if (protocol.equals(LogLevel.PROTOCOL_HTTPS)) {
260       builder = builder.keyPassword(sslConf.get("ssl.server.keystore.keypassword"))
261                        .keyStore(sslConf.get("ssl.server.keystore.location"),
262                          sslConf.get("ssl.server.keystore.password"),
263                          sslConf.get("ssl.server.keystore.type", "jks"))
264                        .trustStore(sslConf.get("ssl.server.truststore.location"),
265                          sslConf.get("ssl.server.truststore.password"),
266                          sslConf.get("ssl.server.truststore.type", "jks"));
267     }
268 
269     HttpServer server = builder.build();
270     server.start();
271     return server;
272   }
273 
274   private void testDynamicLogLevel(final String bindProtocol, final String connectProtocol,
275       final boolean isSpnego) throws Exception {
276     testDynamicLogLevel(bindProtocol, connectProtocol, isSpnego, Level.DEBUG.toString());
277   }
278 
279   /**
280    * Run both client and server using the given protocol.
281    *
282    * @param bindProtocol specify either http or https for server
283    * @param connectProtocol specify either http or https for client
284    * @param isSpnego true if SPNEGO is enabled
285    * @throws Exception if client can't accesss server.
286    */
287   private void testDynamicLogLevel(final String bindProtocol, final String connectProtocol,
288       final boolean isSpnego, final String newLevel) throws Exception {
289     if (!LogLevel.isValidProtocol(bindProtocol)) {
290       throw new Exception("Invalid server protocol " + bindProtocol);
291     }
292     if (!LogLevel.isValidProtocol(connectProtocol)) {
293       throw new Exception("Invalid client protocol " + connectProtocol);
294     }
295     Level oldLevel = log.getEffectiveLevel();
296     assertNotEquals("Get default Log Level which shouldn't be ERROR.",
297         Level.ERROR, oldLevel);
298 
299     // configs needed for SPNEGO at server side
300     if (isSpnego) {
301       serverConf.set(PRINCIPAL, HTTP_PRINCIPAL);
302       serverConf.set(KEYTAB, KEYTAB_FILE.getAbsolutePath());
303       serverConf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos");
304       serverConf.setBoolean(CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, true);
305       UserGroupInformation.setConfiguration(serverConf);
306     } else {
307       serverConf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "simple");
308       serverConf.setBoolean(CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, false);
309       UserGroupInformation.setConfiguration(serverConf);
310     }
311 
312     final HttpServer server = createServer(bindProtocol, isSpnego);
313     // get server port
314     final String authority = NetUtils.getHostPortString(server.getConnectorAddress(0));
315 
316     String keytabFilePath = KEYTAB_FILE.getAbsolutePath();
317 
318     UserGroupInformation clientUGI = UserGroupInformation.
319         loginUserFromKeytabAndReturnUGI(clientPrincipal, keytabFilePath);
320     try {
321       clientUGI.doAs(new PrivilegedExceptionAction<Void>() {
322         @Override public Void run() throws Exception {
323           // client command line
324           getLevel(connectProtocol, authority);
325           setLevel(connectProtocol, authority, newLevel);
326           return null;
327         }
328       });
329     } finally {
330       server.stop();
331     }
332 
333     // restore log level
334     GenericTestUtils.setLogLevel(log, oldLevel);
335   }
336 
337   /**
338    * Run LogLevel command line to start a client to get log level of this test
339    * class.
340    *
341    * @param protocol specify either http or https
342    * @param authority daemon's web UI address
343    * @throws Exception if unable to connect
344    */
345   private void getLevel(String protocol, String authority) throws Exception {
346     String[] getLevelArgs = {"-getlevel", authority, logName, "-protocol", protocol};
347     CLI cli = new CLI(clientConf);
348     cli.run(getLevelArgs);
349   }
350 
351   /**
352    * Run LogLevel command line to start a client to set log level of this test
353    * class to debug.
354    *
355    * @param protocol specify either http or https
356    * @param authority daemon's web UI address
357    * @throws Exception if unable to run or log level does not change as expected
358    */
359   private void setLevel(String protocol, String authority, String newLevel)
360       throws Exception {
361     String[] setLevelArgs = {"-setlevel", authority, logName, newLevel, "-protocol", protocol};
362     CLI cli = new CLI(clientConf);
363     cli.run(setLevelArgs);
364 
365     assertEquals("new level not equal to expected: ", newLevel.toUpperCase(),
366         log.getEffectiveLevel().toString());
367   }
368 
369   /**
370    * Test setting log level to "Info".
371    *
372    * @throws Exception if client can't set log level to INFO.
373    */
374   @Test(timeout=60000)
375   public void testInfoLogLevel() throws Exception {
376     testDynamicLogLevel(LogLevel.PROTOCOL_HTTP, LogLevel.PROTOCOL_HTTP, true, "INFO");
377   }
378 
379   /**
380    * Test setting log level to "Error".
381    *
382    * @throws Exception if client can't set log level to ERROR.
383    */
384   @Test(timeout=60000)
385   public void testErrorLogLevel() throws Exception {
386     testDynamicLogLevel(LogLevel.PROTOCOL_HTTP, LogLevel.PROTOCOL_HTTP, true, "ERROR");
387   }
388 
389   /**
390    * Server runs HTTP, no SPNEGO.
391    *
392    * @throws Exception if http client can't access http server.
393    *   or http client can access https server.
394    */
395   @Test(timeout=60000)
396   public void testLogLevelByHttp() throws Exception {
397     testDynamicLogLevel(LogLevel.PROTOCOL_HTTP, LogLevel.PROTOCOL_HTTP, false);
398     try {
399       testDynamicLogLevel(LogLevel.PROTOCOL_HTTP, LogLevel.PROTOCOL_HTTPS, false);
400       fail("A HTTPS Client should not have succeeded in connecting to a HTTP server");
401     } catch (SSLException e) {
402       GenericTestUtils.assertExceptionContains("Unrecognized SSL message", e);
403     }
404   }
405 
406   /**
407    * Server runs HTTP + SPNEGO.
408    *
409    * @throws Exception if http client can't access http server,
410    *   or http client can access https server.
411    */
412   @Test(timeout=60000)
413   public void testLogLevelByHttpWithSpnego() throws Exception {
414     testDynamicLogLevel(LogLevel.PROTOCOL_HTTP, LogLevel.PROTOCOL_HTTP, true);
415     try {
416       testDynamicLogLevel(LogLevel.PROTOCOL_HTTP, LogLevel.PROTOCOL_HTTPS, true);
417       fail("A HTTPS Client should not have succeeded in connecting to a HTTP server");
418     } catch (SSLException e) {
419       GenericTestUtils.assertExceptionContains("Unrecognized SSL message", e);
420     }
421   }
422 
423   /**
424    * Server runs HTTPS, no SPNEGO.
425    *
426    * @throws Exception if https client can't access https server,
427    *   or https client can access http server.
428    */
429   @Test(timeout=60000)
430   public void testLogLevelByHttps() throws Exception {
431     testDynamicLogLevel(LogLevel.PROTOCOL_HTTPS, LogLevel.PROTOCOL_HTTPS, false);
432     try {
433       testDynamicLogLevel(LogLevel.PROTOCOL_HTTPS, LogLevel.PROTOCOL_HTTP, false);
434       fail("A HTTP Client should not have succeeded in connecting to a HTTPS server");
435     } catch (SocketException e) {
436       GenericTestUtils.assertExceptionContains("Unexpected end of file from server", e);
437     }
438   }
439 
440   /**
441    * Server runs HTTPS + SPNEGO.
442    *
443    * @throws Exception if https client can't access https server,
444    *   or https client can access http server.
445    */
446   @Test(timeout=60000)
447   public void testLogLevelByHttpsWithSpnego() throws Exception {
448     testDynamicLogLevel(LogLevel.PROTOCOL_HTTPS, LogLevel.PROTOCOL_HTTPS, true);
449     try {
450       testDynamicLogLevel(LogLevel.PROTOCOL_HTTPS, LogLevel.PROTOCOL_HTTP, true);
451       fail("A HTTP Client should not have succeeded in connecting to a HTTPS server");
452     } catch (SocketException e) {
453       GenericTestUtils.assertExceptionContains("Unexpected end of file from server", e);
454     }
455   }
456 }