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 package org.apache.hadoop.security; 019 020 import static org.apache.hadoop.fs.CommonConfigurationKeys.HADOOP_SECURITY_AUTHENTICATION; 021 022 import java.io.IOException; 023 import java.lang.reflect.UndeclaredThrowableException; 024 import java.security.AccessControlContext; 025 import java.security.AccessController; 026 import java.security.Principal; 027 import java.security.PrivilegedAction; 028 import java.security.PrivilegedActionException; 029 import java.security.PrivilegedExceptionAction; 030 import java.util.Arrays; 031 import java.util.Collection; 032 import java.util.Collections; 033 import java.util.HashMap; 034 import java.util.List; 035 import java.util.Map; 036 import java.util.Set; 037 038 import javax.security.auth.Subject; 039 import javax.security.auth.callback.CallbackHandler; 040 import javax.security.auth.kerberos.KerberosKey; 041 import javax.security.auth.kerberos.KerberosPrincipal; 042 import javax.security.auth.kerberos.KerberosTicket; 043 import javax.security.auth.login.AppConfigurationEntry; 044 import javax.security.auth.login.LoginContext; 045 import javax.security.auth.login.LoginException; 046 import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag; 047 import javax.security.auth.spi.LoginModule; 048 049 import org.apache.commons.logging.Log; 050 import org.apache.commons.logging.LogFactory; 051 import org.apache.hadoop.classification.InterfaceAudience; 052 import org.apache.hadoop.classification.InterfaceStability; 053 import org.apache.hadoop.conf.Configuration; 054 import org.apache.hadoop.fs.Path; 055 import org.apache.hadoop.io.Text; 056 import org.apache.hadoop.metrics2.annotation.Metric; 057 import org.apache.hadoop.metrics2.annotation.Metrics; 058 import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; 059 import org.apache.hadoop.metrics2.lib.MutableRate; 060 import org.apache.hadoop.security.authentication.util.KerberosName; 061 import org.apache.hadoop.security.authentication.util.KerberosUtil; 062 import org.apache.hadoop.security.token.Token; 063 import org.apache.hadoop.security.token.TokenIdentifier; 064 import org.apache.hadoop.util.Shell; 065 import org.apache.hadoop.util.Time; 066 067 /** 068 * User and group information for Hadoop. 069 * This class wraps around a JAAS Subject and provides methods to determine the 070 * user's username and groups. It supports both the Windows, Unix and Kerberos 071 * login modules. 072 */ 073 @InterfaceAudience.LimitedPrivate({"HDFS", "MapReduce", "HBase", "Hive", "Oozie"}) 074 @InterfaceStability.Evolving 075 public class UserGroupInformation { 076 private static final Log LOG = LogFactory.getLog(UserGroupInformation.class); 077 /** 078 * Percentage of the ticket window to use before we renew ticket. 079 */ 080 private static final float TICKET_RENEW_WINDOW = 0.80f; 081 static final String HADOOP_USER_NAME = "HADOOP_USER_NAME"; 082 083 /** 084 * UgiMetrics maintains UGI activity statistics 085 * and publishes them through the metrics interfaces. 086 */ 087 @Metrics(about="User and group related metrics", context="ugi") 088 static class UgiMetrics { 089 @Metric("Rate of successful kerberos logins and latency (milliseconds)") 090 MutableRate loginSuccess; 091 @Metric("Rate of failed kerberos logins and latency (milliseconds)") 092 MutableRate loginFailure; 093 094 static UgiMetrics create() { 095 return DefaultMetricsSystem.instance().register(new UgiMetrics()); 096 } 097 } 098 099 /** 100 * A login module that looks at the Kerberos, Unix, or Windows principal and 101 * adds the corresponding UserName. 102 */ 103 @InterfaceAudience.Private 104 public static class HadoopLoginModule implements LoginModule { 105 private Subject subject; 106 107 @Override 108 public boolean abort() throws LoginException { 109 return true; 110 } 111 112 private <T extends Principal> T getCanonicalUser(Class<T> cls) { 113 for(T user: subject.getPrincipals(cls)) { 114 return user; 115 } 116 return null; 117 } 118 119 @Override 120 public boolean commit() throws LoginException { 121 if (LOG.isDebugEnabled()) { 122 LOG.debug("hadoop login commit"); 123 } 124 // if we already have a user, we are done. 125 if (!subject.getPrincipals(User.class).isEmpty()) { 126 if (LOG.isDebugEnabled()) { 127 LOG.debug("using existing subject:"+subject.getPrincipals()); 128 } 129 return true; 130 } 131 Principal user = null; 132 // if we are using kerberos, try it out 133 if (useKerberos) { 134 user = getCanonicalUser(KerberosPrincipal.class); 135 if (LOG.isDebugEnabled()) { 136 LOG.debug("using kerberos user:"+user); 137 } 138 } 139 //If we don't have a kerberos user and security is disabled, check 140 //if user is specified in the environment or properties 141 if (!isSecurityEnabled() && (user == null)) { 142 String envUser = System.getenv(HADOOP_USER_NAME); 143 if (envUser == null) { 144 envUser = System.getProperty(HADOOP_USER_NAME); 145 } 146 user = envUser == null ? null : new User(envUser); 147 } 148 // use the OS user 149 if (user == null) { 150 user = getCanonicalUser(OS_PRINCIPAL_CLASS); 151 if (LOG.isDebugEnabled()) { 152 LOG.debug("using local user:"+user); 153 } 154 } 155 // if we found the user, add our principal 156 if (user != null) { 157 subject.getPrincipals().add(new User(user.getName())); 158 return true; 159 } 160 LOG.error("Can't find user in " + subject); 161 throw new LoginException("Can't find user name"); 162 } 163 164 @Override 165 public void initialize(Subject subject, CallbackHandler callbackHandler, 166 Map<String, ?> sharedState, Map<String, ?> options) { 167 this.subject = subject; 168 } 169 170 @Override 171 public boolean login() throws LoginException { 172 if (LOG.isDebugEnabled()) { 173 LOG.debug("hadoop login"); 174 } 175 return true; 176 } 177 178 @Override 179 public boolean logout() throws LoginException { 180 if (LOG.isDebugEnabled()) { 181 LOG.debug("hadoop logout"); 182 } 183 return true; 184 } 185 } 186 187 /** Metrics to track UGI activity */ 188 static UgiMetrics metrics = UgiMetrics.create(); 189 /** Are the static variables that depend on configuration initialized? */ 190 private static boolean isInitialized = false; 191 /** Should we use Kerberos configuration? */ 192 private static boolean useKerberos; 193 /** Server-side groups fetching service */ 194 private static Groups groups; 195 /** The configuration to use */ 196 private static Configuration conf; 197 198 199 /** Leave 10 minutes between relogin attempts. */ 200 private static final long MIN_TIME_BEFORE_RELOGIN = 10 * 60 * 1000L; 201 202 /**Environment variable pointing to the token cache file*/ 203 public static final String HADOOP_TOKEN_FILE_LOCATION = 204 "HADOOP_TOKEN_FILE_LOCATION"; 205 206 /** 207 * A method to initialize the fields that depend on a configuration. 208 * Must be called before useKerberos or groups is used. 209 */ 210 private static synchronized void ensureInitialized() { 211 if (!isInitialized) { 212 initialize(new Configuration(), KerberosName.hasRulesBeenSet()); 213 } 214 } 215 216 /** 217 * Initialize UGI and related classes. 218 * @param conf the configuration to use 219 */ 220 private static synchronized void initialize(Configuration conf, boolean skipRulesSetting) { 221 initUGI(conf); 222 // give the configuration on how to translate Kerberos names 223 try { 224 if (!skipRulesSetting) { 225 HadoopKerberosName.setConfiguration(conf); 226 } 227 } catch (IOException ioe) { 228 throw new RuntimeException("Problem with Kerberos auth_to_local name " + 229 "configuration", ioe); 230 } 231 } 232 233 /** 234 * Set the configuration values for UGI. 235 * @param conf the configuration to use 236 */ 237 private static synchronized void initUGI(Configuration conf) { 238 String value = conf.get(HADOOP_SECURITY_AUTHENTICATION); 239 if (value == null || "simple".equals(value)) { 240 useKerberos = false; 241 } else if ("kerberos".equals(value)) { 242 useKerberos = true; 243 } else { 244 throw new IllegalArgumentException("Invalid attribute value for " + 245 HADOOP_SECURITY_AUTHENTICATION + 246 " of " + value); 247 } 248 // If we haven't set up testing groups, use the configuration to find it 249 if (!(groups instanceof TestingGroups)) { 250 groups = Groups.getUserToGroupsMappingService(conf); 251 } 252 isInitialized = true; 253 UserGroupInformation.conf = conf; 254 } 255 256 /** 257 * Set the static configuration for UGI. 258 * In particular, set the security authentication mechanism and the 259 * group look up service. 260 * @param conf the configuration to use 261 */ 262 @InterfaceAudience.Public 263 @InterfaceStability.Evolving 264 public static void setConfiguration(Configuration conf) { 265 initialize(conf, false); 266 } 267 268 /** 269 * Determine if UserGroupInformation is using Kerberos to determine 270 * user identities or is relying on simple authentication 271 * 272 * @return true if UGI is working in a secure environment 273 */ 274 public static boolean isSecurityEnabled() { 275 ensureInitialized(); 276 return useKerberos; 277 } 278 279 /** 280 * Information about the logged in user. 281 */ 282 private static UserGroupInformation loginUser = null; 283 private static String keytabPrincipal = null; 284 private static String keytabFile = null; 285 286 private final Subject subject; 287 // All non-static fields must be read-only caches that come from the subject. 288 private final User user; 289 private final boolean isKeytab; 290 private final boolean isKrbTkt; 291 292 private static String OS_LOGIN_MODULE_NAME; 293 private static Class<? extends Principal> OS_PRINCIPAL_CLASS; 294 private static final boolean windows = 295 System.getProperty("os.name").startsWith("Windows"); 296 /* Return the OS login module class name */ 297 private static String getOSLoginModuleName() { 298 if (System.getProperty("java.vendor").contains("IBM")) { 299 return windows ? "com.ibm.security.auth.module.NTLoginModule" 300 : "com.ibm.security.auth.module.LinuxLoginModule"; 301 } else { 302 return windows ? "com.sun.security.auth.module.NTLoginModule" 303 : "com.sun.security.auth.module.UnixLoginModule"; 304 } 305 } 306 307 /* Return the OS principal class */ 308 @SuppressWarnings("unchecked") 309 private static Class<? extends Principal> getOsPrincipalClass() { 310 ClassLoader cl = ClassLoader.getSystemClassLoader(); 311 try { 312 if (System.getProperty("java.vendor").contains("IBM")) { 313 if (windows) { 314 return (Class<? extends Principal>) 315 cl.loadClass("com.ibm.security.auth.UsernamePrincipal"); 316 } else { 317 return (Class<? extends Principal>) 318 (System.getProperty("os.arch").contains("64") 319 ? cl.loadClass("com.ibm.security.auth.UsernamePrincipal") 320 : cl.loadClass("com.ibm.security.auth.LinuxPrincipal")); 321 } 322 } else { 323 return (Class<? extends Principal>) (windows 324 ? cl.loadClass("com.sun.security.auth.NTUserPrincipal") 325 : cl.loadClass("com.sun.security.auth.UnixPrincipal")); 326 } 327 } catch (ClassNotFoundException e) { 328 LOG.error("Unable to find JAAS classes:" + e.getMessage()); 329 } 330 return null; 331 } 332 static { 333 OS_LOGIN_MODULE_NAME = getOSLoginModuleName(); 334 OS_PRINCIPAL_CLASS = getOsPrincipalClass(); 335 } 336 337 private static class RealUser implements Principal { 338 private final UserGroupInformation realUser; 339 340 RealUser(UserGroupInformation realUser) { 341 this.realUser = realUser; 342 } 343 344 @Override 345 public String getName() { 346 return realUser.getUserName(); 347 } 348 349 public UserGroupInformation getRealUser() { 350 return realUser; 351 } 352 353 @Override 354 public boolean equals(Object o) { 355 if (this == o) { 356 return true; 357 } else if (o == null || getClass() != o.getClass()) { 358 return false; 359 } else { 360 return realUser.equals(((RealUser) o).realUser); 361 } 362 } 363 364 @Override 365 public int hashCode() { 366 return realUser.hashCode(); 367 } 368 369 @Override 370 public String toString() { 371 return realUser.toString(); 372 } 373 } 374 375 /** 376 * A JAAS configuration that defines the login modules that we want 377 * to use for login. 378 */ 379 private static class HadoopConfiguration 380 extends javax.security.auth.login.Configuration { 381 private static final String SIMPLE_CONFIG_NAME = "hadoop-simple"; 382 private static final String USER_KERBEROS_CONFIG_NAME = 383 "hadoop-user-kerberos"; 384 private static final String KEYTAB_KERBEROS_CONFIG_NAME = 385 "hadoop-keytab-kerberos"; 386 387 private static final Map<String, String> BASIC_JAAS_OPTIONS = 388 new HashMap<String,String>(); 389 static { 390 String jaasEnvVar = System.getenv("HADOOP_JAAS_DEBUG"); 391 if (jaasEnvVar != null && "true".equalsIgnoreCase(jaasEnvVar)) { 392 BASIC_JAAS_OPTIONS.put("debug", "true"); 393 } 394 } 395 396 private static final AppConfigurationEntry OS_SPECIFIC_LOGIN = 397 new AppConfigurationEntry(OS_LOGIN_MODULE_NAME, 398 LoginModuleControlFlag.REQUIRED, 399 BASIC_JAAS_OPTIONS); 400 private static final AppConfigurationEntry HADOOP_LOGIN = 401 new AppConfigurationEntry(HadoopLoginModule.class.getName(), 402 LoginModuleControlFlag.REQUIRED, 403 BASIC_JAAS_OPTIONS); 404 private static final Map<String,String> USER_KERBEROS_OPTIONS = 405 new HashMap<String,String>(); 406 static { 407 USER_KERBEROS_OPTIONS.put("doNotPrompt", "true"); 408 USER_KERBEROS_OPTIONS.put("useTicketCache", "true"); 409 USER_KERBEROS_OPTIONS.put("renewTGT", "true"); 410 String ticketCache = System.getenv("KRB5CCNAME"); 411 if (ticketCache != null) { 412 USER_KERBEROS_OPTIONS.put("ticketCache", ticketCache); 413 } 414 USER_KERBEROS_OPTIONS.putAll(BASIC_JAAS_OPTIONS); 415 } 416 private static final AppConfigurationEntry USER_KERBEROS_LOGIN = 417 new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(), 418 LoginModuleControlFlag.OPTIONAL, 419 USER_KERBEROS_OPTIONS); 420 private static final Map<String,String> KEYTAB_KERBEROS_OPTIONS = 421 new HashMap<String,String>(); 422 static { 423 KEYTAB_KERBEROS_OPTIONS.put("doNotPrompt", "true"); 424 KEYTAB_KERBEROS_OPTIONS.put("useKeyTab", "true"); 425 KEYTAB_KERBEROS_OPTIONS.put("storeKey", "true"); 426 KEYTAB_KERBEROS_OPTIONS.put("refreshKrb5Config", "true"); 427 KEYTAB_KERBEROS_OPTIONS.putAll(BASIC_JAAS_OPTIONS); 428 } 429 private static final AppConfigurationEntry KEYTAB_KERBEROS_LOGIN = 430 new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(), 431 LoginModuleControlFlag.REQUIRED, 432 KEYTAB_KERBEROS_OPTIONS); 433 434 private static final AppConfigurationEntry[] SIMPLE_CONF = 435 new AppConfigurationEntry[]{OS_SPECIFIC_LOGIN, HADOOP_LOGIN}; 436 437 private static final AppConfigurationEntry[] USER_KERBEROS_CONF = 438 new AppConfigurationEntry[]{OS_SPECIFIC_LOGIN, USER_KERBEROS_LOGIN, 439 HADOOP_LOGIN}; 440 441 private static final AppConfigurationEntry[] KEYTAB_KERBEROS_CONF = 442 new AppConfigurationEntry[]{KEYTAB_KERBEROS_LOGIN, HADOOP_LOGIN}; 443 444 @Override 445 public AppConfigurationEntry[] getAppConfigurationEntry(String appName) { 446 if (SIMPLE_CONFIG_NAME.equals(appName)) { 447 return SIMPLE_CONF; 448 } else if (USER_KERBEROS_CONFIG_NAME.equals(appName)) { 449 return USER_KERBEROS_CONF; 450 } else if (KEYTAB_KERBEROS_CONFIG_NAME.equals(appName)) { 451 KEYTAB_KERBEROS_OPTIONS.put("keyTab", keytabFile); 452 KEYTAB_KERBEROS_OPTIONS.put("principal", keytabPrincipal); 453 return KEYTAB_KERBEROS_CONF; 454 } 455 return null; 456 } 457 } 458 459 /** 460 * Represents a javax.security configuration that is created at runtime. 461 */ 462 private static class DynamicConfiguration 463 extends javax.security.auth.login.Configuration { 464 private AppConfigurationEntry[] ace; 465 466 DynamicConfiguration(AppConfigurationEntry[] ace) { 467 this.ace = ace; 468 } 469 470 @Override 471 public AppConfigurationEntry[] getAppConfigurationEntry(String appName) { 472 return ace; 473 } 474 } 475 476 private static LoginContext 477 newLoginContext(String appName, Subject subject, 478 javax.security.auth.login.Configuration loginConf) 479 throws LoginException { 480 // Temporarily switch the thread's ContextClassLoader to match this 481 // class's classloader, so that we can properly load HadoopLoginModule 482 // from the JAAS libraries. 483 Thread t = Thread.currentThread(); 484 ClassLoader oldCCL = t.getContextClassLoader(); 485 t.setContextClassLoader(HadoopLoginModule.class.getClassLoader()); 486 try { 487 return new LoginContext(appName, subject, null, loginConf); 488 } finally { 489 t.setContextClassLoader(oldCCL); 490 } 491 } 492 493 private LoginContext getLogin() { 494 return user.getLogin(); 495 } 496 497 private void setLogin(LoginContext login) { 498 user.setLogin(login); 499 } 500 501 /** 502 * Create a UserGroupInformation for the given subject. 503 * This does not change the subject or acquire new credentials. 504 * @param subject the user's subject 505 */ 506 UserGroupInformation(Subject subject) { 507 this.subject = subject; 508 this.user = subject.getPrincipals(User.class).iterator().next(); 509 this.isKeytab = !subject.getPrivateCredentials(KerberosKey.class).isEmpty(); 510 this.isKrbTkt = !subject.getPrivateCredentials(KerberosTicket.class).isEmpty(); 511 } 512 513 /** 514 * checks if logged in using kerberos 515 * @return true if the subject logged via keytab or has a Kerberos TGT 516 */ 517 public boolean hasKerberosCredentials() { 518 return isKeytab || isKrbTkt; 519 } 520 521 /** 522 * Return the current user, including any doAs in the current stack. 523 * @return the current user 524 * @throws IOException if login fails 525 */ 526 @InterfaceAudience.Public 527 @InterfaceStability.Evolving 528 public synchronized 529 static UserGroupInformation getCurrentUser() throws IOException { 530 AccessControlContext context = AccessController.getContext(); 531 Subject subject = Subject.getSubject(context); 532 if (subject == null || subject.getPrincipals(User.class).isEmpty()) { 533 return getLoginUser(); 534 } else { 535 return new UserGroupInformation(subject); 536 } 537 } 538 539 /** 540 * Find the most appropriate UserGroupInformation to use 541 * 542 * @param ticketCachePath The Kerberos ticket cache path, or NULL 543 * if none is specfied 544 * @param user The user name, or NULL if none is specified. 545 * 546 * @return The most appropriate UserGroupInformation 547 */ 548 public static UserGroupInformation getBestUGI( 549 String ticketCachePath, String user) throws IOException { 550 if (ticketCachePath != null) { 551 return getUGIFromTicketCache(ticketCachePath, user); 552 } else if (user == null) { 553 return getCurrentUser(); 554 } else { 555 return createRemoteUser(user); 556 } 557 } 558 559 /** 560 * Create a UserGroupInformation from a Kerberos ticket cache. 561 * 562 * @param user The principal name to load from the ticket 563 * cache 564 * @param ticketCachePath the path to the ticket cache file 565 * 566 * @throws IOException if the kerberos login fails 567 */ 568 @InterfaceAudience.Public 569 @InterfaceStability.Evolving 570 public static UserGroupInformation getUGIFromTicketCache( 571 String ticketCache, String user) throws IOException { 572 if (!isSecurityEnabled()) { 573 return getBestUGI(null, user); 574 } 575 try { 576 Map<String,String> krbOptions = new HashMap<String,String>(); 577 krbOptions.put("doNotPrompt", "true"); 578 krbOptions.put("useTicketCache", "true"); 579 krbOptions.put("useKeyTab", "false"); 580 krbOptions.put("renewTGT", "false"); 581 krbOptions.put("ticketCache", ticketCache); 582 krbOptions.putAll(HadoopConfiguration.BASIC_JAAS_OPTIONS); 583 AppConfigurationEntry ace = new AppConfigurationEntry( 584 KerberosUtil.getKrb5LoginModuleName(), 585 LoginModuleControlFlag.REQUIRED, 586 krbOptions); 587 DynamicConfiguration dynConf = 588 new DynamicConfiguration(new AppConfigurationEntry[]{ ace }); 589 LoginContext login = newLoginContext( 590 HadoopConfiguration.USER_KERBEROS_CONFIG_NAME, null, dynConf); 591 login.login(); 592 593 Subject loginSubject = login.getSubject(); 594 Set<Principal> loginPrincipals = loginSubject.getPrincipals(); 595 if (loginPrincipals.isEmpty()) { 596 throw new RuntimeException("No login principals found!"); 597 } 598 if (loginPrincipals.size() != 1) { 599 LOG.warn("found more than one principal in the ticket cache file " + 600 ticketCache); 601 } 602 User ugiUser = new User(loginPrincipals.iterator().next().getName(), 603 AuthenticationMethod.KERBEROS, login); 604 loginSubject.getPrincipals().add(ugiUser); 605 UserGroupInformation ugi = new UserGroupInformation(loginSubject); 606 ugi.setLogin(login); 607 ugi.setAuthenticationMethod(AuthenticationMethod.KERBEROS); 608 return ugi; 609 } catch (LoginException le) { 610 throw new IOException("failure to login using ticket cache file " + 611 ticketCache, le); 612 } 613 } 614 615 /** 616 * Get the currently logged in user. 617 * @return the logged in user 618 * @throws IOException if login fails 619 */ 620 @InterfaceAudience.Public 621 @InterfaceStability.Evolving 622 public synchronized 623 static UserGroupInformation getLoginUser() throws IOException { 624 if (loginUser == null) { 625 try { 626 Subject subject = new Subject(); 627 LoginContext login; 628 if (isSecurityEnabled()) { 629 login = newLoginContext(HadoopConfiguration.USER_KERBEROS_CONFIG_NAME, 630 subject, new HadoopConfiguration()); 631 } else { 632 login = newLoginContext(HadoopConfiguration.SIMPLE_CONFIG_NAME, 633 subject, new HadoopConfiguration()); 634 } 635 login.login(); 636 loginUser = new UserGroupInformation(subject); 637 loginUser.setLogin(login); 638 loginUser.setAuthenticationMethod(isSecurityEnabled() ? 639 AuthenticationMethod.KERBEROS : 640 AuthenticationMethod.SIMPLE); 641 loginUser = new UserGroupInformation(login.getSubject()); 642 String fileLocation = System.getenv(HADOOP_TOKEN_FILE_LOCATION); 643 if (fileLocation != null) { 644 // load the token storage file and put all of the tokens into the 645 // user. 646 Credentials cred = Credentials.readTokenStorageFile( 647 new Path("file:///" + fileLocation), conf); 648 loginUser.addCredentials(cred); 649 } 650 loginUser.spawnAutoRenewalThreadForUserCreds(); 651 } catch (LoginException le) { 652 throw new IOException("failure to login", le); 653 } 654 if (LOG.isDebugEnabled()) { 655 LOG.debug("UGI loginUser:"+loginUser); 656 } 657 } 658 return loginUser; 659 } 660 661 /** 662 * Is this user logged in from a keytab file? 663 * @return true if the credentials are from a keytab file. 664 */ 665 public boolean isFromKeytab() { 666 return isKeytab; 667 } 668 669 /** 670 * Get the Kerberos TGT 671 * @return the user's TGT or null if none was found 672 */ 673 private synchronized KerberosTicket getTGT() { 674 Set<KerberosTicket> tickets = subject 675 .getPrivateCredentials(KerberosTicket.class); 676 for (KerberosTicket ticket : tickets) { 677 if (SecurityUtil.isOriginalTGT(ticket)) { 678 if (LOG.isDebugEnabled()) { 679 LOG.debug("Found tgt " + ticket); 680 } 681 return ticket; 682 } 683 } 684 return null; 685 } 686 687 private long getRefreshTime(KerberosTicket tgt) { 688 long start = tgt.getStartTime().getTime(); 689 long end = tgt.getEndTime().getTime(); 690 return start + (long) ((end - start) * TICKET_RENEW_WINDOW); 691 } 692 693 /**Spawn a thread to do periodic renewals of kerberos credentials*/ 694 private void spawnAutoRenewalThreadForUserCreds() { 695 if (isSecurityEnabled()) { 696 //spawn thread only if we have kerb credentials 697 if (user.getAuthenticationMethod() == AuthenticationMethod.KERBEROS && 698 !isKeytab) { 699 Thread t = new Thread(new Runnable() { 700 701 @Override 702 public void run() { 703 String cmd = conf.get("hadoop.kerberos.kinit.command", 704 "kinit"); 705 KerberosTicket tgt = getTGT(); 706 if (tgt == null) { 707 return; 708 } 709 long nextRefresh = getRefreshTime(tgt); 710 while (true) { 711 try { 712 long now = Time.now(); 713 if(LOG.isDebugEnabled()) { 714 LOG.debug("Current time is " + now); 715 LOG.debug("Next refresh is " + nextRefresh); 716 } 717 if (now < nextRefresh) { 718 Thread.sleep(nextRefresh - now); 719 } 720 Shell.execCommand(cmd, "-R"); 721 if(LOG.isDebugEnabled()) { 722 LOG.debug("renewed ticket"); 723 } 724 reloginFromTicketCache(); 725 tgt = getTGT(); 726 if (tgt == null) { 727 LOG.warn("No TGT after renewal. Aborting renew thread for " + 728 getUserName()); 729 return; 730 } 731 nextRefresh = Math.max(getRefreshTime(tgt), 732 now + MIN_TIME_BEFORE_RELOGIN); 733 } catch (InterruptedException ie) { 734 LOG.warn("Terminating renewal thread"); 735 return; 736 } catch (IOException ie) { 737 LOG.warn("Exception encountered while running the" + 738 " renewal command. Aborting renew thread. " + ie); 739 return; 740 } 741 } 742 } 743 }); 744 t.setDaemon(true); 745 t.setName("TGT Renewer for " + getUserName()); 746 t.start(); 747 } 748 } 749 } 750 /** 751 * Log a user in from a keytab file. Loads a user identity from a keytab 752 * file and logs them in. They become the currently logged-in user. 753 * @param user the principal name to load from the keytab 754 * @param path the path to the keytab file 755 * @throws IOException if the keytab file can't be read 756 */ 757 @InterfaceAudience.Public 758 @InterfaceStability.Evolving 759 public synchronized 760 static void loginUserFromKeytab(String user, 761 String path 762 ) throws IOException { 763 if (!isSecurityEnabled()) 764 return; 765 766 keytabFile = path; 767 keytabPrincipal = user; 768 Subject subject = new Subject(); 769 LoginContext login; 770 long start = 0; 771 try { 772 login = newLoginContext(HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, 773 subject, new HadoopConfiguration()); 774 start = Time.now(); 775 login.login(); 776 metrics.loginSuccess.add(Time.now() - start); 777 loginUser = new UserGroupInformation(subject); 778 loginUser.setLogin(login); 779 loginUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS); 780 } catch (LoginException le) { 781 if (start > 0) { 782 metrics.loginFailure.add(Time.now() - start); 783 } 784 throw new IOException("Login failure for " + user + " from keytab " + 785 path, le); 786 } 787 LOG.info("Login successful for user " + keytabPrincipal 788 + " using keytab file " + keytabFile); 789 } 790 791 /** 792 * Re-login a user from keytab if TGT is expired or is close to expiry. 793 * 794 * @throws IOException 795 */ 796 public synchronized void checkTGTAndReloginFromKeytab() throws IOException { 797 if (!isSecurityEnabled() 798 || user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS 799 || !isKeytab) 800 return; 801 KerberosTicket tgt = getTGT(); 802 if (tgt != null && Time.now() < getRefreshTime(tgt)) { 803 return; 804 } 805 reloginFromKeytab(); 806 } 807 808 /** 809 * Re-Login a user in from a keytab file. Loads a user identity from a keytab 810 * file and logs them in. They become the currently logged-in user. This 811 * method assumes that {@link #loginUserFromKeytab(String, String)} had 812 * happened already. 813 * The Subject field of this UserGroupInformation object is updated to have 814 * the new credentials. 815 * @throws IOException on a failure 816 */ 817 @InterfaceAudience.Public 818 @InterfaceStability.Evolving 819 public synchronized void reloginFromKeytab() 820 throws IOException { 821 if (!isSecurityEnabled() || 822 user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS || 823 !isKeytab) 824 return; 825 826 long now = Time.now(); 827 if (!hasSufficientTimeElapsed(now)) { 828 return; 829 } 830 831 KerberosTicket tgt = getTGT(); 832 //Return if TGT is valid and is not going to expire soon. 833 if (tgt != null && now < getRefreshTime(tgt)) { 834 return; 835 } 836 837 LoginContext login = getLogin(); 838 if (login == null || keytabFile == null) { 839 throw new IOException("loginUserFromKeyTab must be done first"); 840 } 841 842 long start = 0; 843 // register most recent relogin attempt 844 user.setLastLogin(now); 845 try { 846 LOG.info("Initiating logout for " + getUserName()); 847 synchronized (UserGroupInformation.class) { 848 // clear up the kerberos state. But the tokens are not cleared! As per 849 // the Java kerberos login module code, only the kerberos credentials 850 // are cleared 851 login.logout(); 852 // login and also update the subject field of this instance to 853 // have the new credentials (pass it to the LoginContext constructor) 854 login = newLoginContext( 855 HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, getSubject(), 856 new HadoopConfiguration()); 857 LOG.info("Initiating re-login for " + keytabPrincipal); 858 start = Time.now(); 859 login.login(); 860 metrics.loginSuccess.add(Time.now() - start); 861 setLogin(login); 862 } 863 } catch (LoginException le) { 864 if (start > 0) { 865 metrics.loginFailure.add(Time.now() - start); 866 } 867 throw new IOException("Login failure for " + keytabPrincipal + 868 " from keytab " + keytabFile, le); 869 } 870 } 871 872 /** 873 * Re-Login a user in from the ticket cache. This 874 * method assumes that login had happened already. 875 * The Subject field of this UserGroupInformation object is updated to have 876 * the new credentials. 877 * @throws IOException on a failure 878 */ 879 @InterfaceAudience.Public 880 @InterfaceStability.Evolving 881 public synchronized void reloginFromTicketCache() 882 throws IOException { 883 if (!isSecurityEnabled() || 884 user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS || 885 !isKrbTkt) 886 return; 887 LoginContext login = getLogin(); 888 if (login == null) { 889 throw new IOException("login must be done first"); 890 } 891 long now = Time.now(); 892 if (!hasSufficientTimeElapsed(now)) { 893 return; 894 } 895 // register most recent relogin attempt 896 user.setLastLogin(now); 897 try { 898 LOG.info("Initiating logout for " + getUserName()); 899 //clear up the kerberos state. But the tokens are not cleared! As per 900 //the Java kerberos login module code, only the kerberos credentials 901 //are cleared 902 login.logout(); 903 //login and also update the subject field of this instance to 904 //have the new credentials (pass it to the LoginContext constructor) 905 login = 906 newLoginContext(HadoopConfiguration.USER_KERBEROS_CONFIG_NAME, 907 getSubject(), new HadoopConfiguration()); 908 LOG.info("Initiating re-login for " + getUserName()); 909 login.login(); 910 setLogin(login); 911 } catch (LoginException le) { 912 throw new IOException("Login failure for " + getUserName(), le); 913 } 914 } 915 916 917 /** 918 * Log a user in from a keytab file. Loads a user identity from a keytab 919 * file and login them in. This new user does not affect the currently 920 * logged-in user. 921 * @param user the principal name to load from the keytab 922 * @param path the path to the keytab file 923 * @throws IOException if the keytab file can't be read 924 */ 925 public synchronized 926 static UserGroupInformation loginUserFromKeytabAndReturnUGI(String user, 927 String path 928 ) throws IOException { 929 if (!isSecurityEnabled()) 930 return UserGroupInformation.getCurrentUser(); 931 String oldKeytabFile = null; 932 String oldKeytabPrincipal = null; 933 934 long start = 0; 935 try { 936 oldKeytabFile = keytabFile; 937 oldKeytabPrincipal = keytabPrincipal; 938 keytabFile = path; 939 keytabPrincipal = user; 940 Subject subject = new Subject(); 941 942 LoginContext login = newLoginContext( 943 HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, subject, 944 new HadoopConfiguration()); 945 946 start = Time.now(); 947 login.login(); 948 metrics.loginSuccess.add(Time.now() - start); 949 UserGroupInformation newLoginUser = new UserGroupInformation(subject); 950 newLoginUser.setLogin(login); 951 newLoginUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS); 952 953 return newLoginUser; 954 } catch (LoginException le) { 955 if (start > 0) { 956 metrics.loginFailure.add(Time.now() - start); 957 } 958 throw new IOException("Login failure for " + user + " from keytab " + 959 path, le); 960 } finally { 961 if(oldKeytabFile != null) keytabFile = oldKeytabFile; 962 if(oldKeytabPrincipal != null) keytabPrincipal = oldKeytabPrincipal; 963 } 964 } 965 966 private boolean hasSufficientTimeElapsed(long now) { 967 if (now - user.getLastLogin() < MIN_TIME_BEFORE_RELOGIN ) { 968 LOG.warn("Not attempting to re-login since the last re-login was " + 969 "attempted less than " + (MIN_TIME_BEFORE_RELOGIN/1000) + " seconds"+ 970 " before."); 971 return false; 972 } 973 return true; 974 } 975 976 /** 977 * Did the login happen via keytab 978 * @return true or false 979 */ 980 @InterfaceAudience.Public 981 @InterfaceStability.Evolving 982 public synchronized static boolean isLoginKeytabBased() throws IOException { 983 return getLoginUser().isKeytab; 984 } 985 986 /** 987 * Create a user from a login name. It is intended to be used for remote 988 * users in RPC, since it won't have any credentials. 989 * @param user the full user principal name, must not be empty or null 990 * @return the UserGroupInformation for the remote user. 991 */ 992 @InterfaceAudience.Public 993 @InterfaceStability.Evolving 994 public static UserGroupInformation createRemoteUser(String user) { 995 if (user == null || "".equals(user)) { 996 throw new IllegalArgumentException("Null user"); 997 } 998 Subject subject = new Subject(); 999 subject.getPrincipals().add(new User(user)); 1000 UserGroupInformation result = new UserGroupInformation(subject); 1001 result.setAuthenticationMethod(AuthenticationMethod.SIMPLE); 1002 return result; 1003 } 1004 1005 /** 1006 * existing types of authentications' methods 1007 */ 1008 @InterfaceAudience.Public 1009 @InterfaceStability.Evolving 1010 public static enum AuthenticationMethod { 1011 SIMPLE, 1012 KERBEROS, 1013 TOKEN, 1014 CERTIFICATE, 1015 KERBEROS_SSL, 1016 PROXY; 1017 } 1018 1019 /** 1020 * Create a proxy user using username of the effective user and the ugi of the 1021 * real user. 1022 * @param user 1023 * @param realUser 1024 * @return proxyUser ugi 1025 */ 1026 @InterfaceAudience.Public 1027 @InterfaceStability.Evolving 1028 public static UserGroupInformation createProxyUser(String user, 1029 UserGroupInformation realUser) { 1030 if (user == null || "".equals(user)) { 1031 throw new IllegalArgumentException("Null user"); 1032 } 1033 if (realUser == null) { 1034 throw new IllegalArgumentException("Null real user"); 1035 } 1036 Subject subject = new Subject(); 1037 Set<Principal> principals = subject.getPrincipals(); 1038 principals.add(new User(user)); 1039 principals.add(new RealUser(realUser)); 1040 UserGroupInformation result =new UserGroupInformation(subject); 1041 result.setAuthenticationMethod(AuthenticationMethod.PROXY); 1042 return result; 1043 } 1044 1045 /** 1046 * get RealUser (vs. EffectiveUser) 1047 * @return realUser running over proxy user 1048 */ 1049 @InterfaceAudience.Public 1050 @InterfaceStability.Evolving 1051 public UserGroupInformation getRealUser() { 1052 for (RealUser p: subject.getPrincipals(RealUser.class)) { 1053 return p.getRealUser(); 1054 } 1055 return null; 1056 } 1057 1058 1059 1060 /** 1061 * This class is used for storing the groups for testing. It stores a local 1062 * map that has the translation of usernames to groups. 1063 */ 1064 private static class TestingGroups extends Groups { 1065 private final Map<String, List<String>> userToGroupsMapping = 1066 new HashMap<String,List<String>>(); 1067 private Groups underlyingImplementation; 1068 1069 private TestingGroups(Groups underlyingImplementation) { 1070 super(new org.apache.hadoop.conf.Configuration()); 1071 this.underlyingImplementation = underlyingImplementation; 1072 } 1073 1074 @Override 1075 public List<String> getGroups(String user) throws IOException { 1076 List<String> result = userToGroupsMapping.get(user); 1077 1078 if (result == null) { 1079 result = underlyingImplementation.getGroups(user); 1080 } 1081 1082 return result; 1083 } 1084 1085 private void setUserGroups(String user, String[] groups) { 1086 userToGroupsMapping.put(user, Arrays.asList(groups)); 1087 } 1088 } 1089 1090 /** 1091 * Create a UGI for testing HDFS and MapReduce 1092 * @param user the full user principal name 1093 * @param userGroups the names of the groups that the user belongs to 1094 * @return a fake user for running unit tests 1095 */ 1096 @InterfaceAudience.Public 1097 @InterfaceStability.Evolving 1098 public static UserGroupInformation createUserForTesting(String user, 1099 String[] userGroups) { 1100 ensureInitialized(); 1101 UserGroupInformation ugi = createRemoteUser(user); 1102 // make sure that the testing object is setup 1103 if (!(groups instanceof TestingGroups)) { 1104 groups = new TestingGroups(groups); 1105 } 1106 // add the user groups 1107 ((TestingGroups) groups).setUserGroups(ugi.getShortUserName(), userGroups); 1108 return ugi; 1109 } 1110 1111 1112 /** 1113 * Create a proxy user UGI for testing HDFS and MapReduce 1114 * 1115 * @param user 1116 * the full user principal name for effective user 1117 * @param realUser 1118 * UGI of the real user 1119 * @param userGroups 1120 * the names of the groups that the user belongs to 1121 * @return a fake user for running unit tests 1122 */ 1123 public static UserGroupInformation createProxyUserForTesting(String user, 1124 UserGroupInformation realUser, String[] userGroups) { 1125 ensureInitialized(); 1126 UserGroupInformation ugi = createProxyUser(user, realUser); 1127 // make sure that the testing object is setup 1128 if (!(groups instanceof TestingGroups)) { 1129 groups = new TestingGroups(groups); 1130 } 1131 // add the user groups 1132 ((TestingGroups) groups).setUserGroups(ugi.getShortUserName(), userGroups); 1133 return ugi; 1134 } 1135 1136 /** 1137 * Get the user's login name. 1138 * @return the user's name up to the first '/' or '@'. 1139 */ 1140 public String getShortUserName() { 1141 for (User p: subject.getPrincipals(User.class)) { 1142 return p.getShortName(); 1143 } 1144 return null; 1145 } 1146 1147 /** 1148 * Get the user's full principal name. 1149 * @return the user's full principal name. 1150 */ 1151 @InterfaceAudience.Public 1152 @InterfaceStability.Evolving 1153 public String getUserName() { 1154 return user.getName(); 1155 } 1156 1157 /** 1158 * Add a TokenIdentifier to this UGI. The TokenIdentifier has typically been 1159 * authenticated by the RPC layer as belonging to the user represented by this 1160 * UGI. 1161 * 1162 * @param tokenId 1163 * tokenIdentifier to be added 1164 * @return true on successful add of new tokenIdentifier 1165 */ 1166 public synchronized boolean addTokenIdentifier(TokenIdentifier tokenId) { 1167 return subject.getPublicCredentials().add(tokenId); 1168 } 1169 1170 /** 1171 * Get the set of TokenIdentifiers belonging to this UGI 1172 * 1173 * @return the set of TokenIdentifiers belonging to this UGI 1174 */ 1175 public synchronized Set<TokenIdentifier> getTokenIdentifiers() { 1176 return subject.getPublicCredentials(TokenIdentifier.class); 1177 } 1178 1179 /** 1180 * Add a token to this UGI 1181 * 1182 * @param token Token to be added 1183 * @return true on successful add of new token 1184 */ 1185 public synchronized boolean addToken(Token<? extends TokenIdentifier> token) { 1186 return (token != null) ? addToken(token.getService(), token) : false; 1187 } 1188 1189 /** 1190 * Add a named token to this UGI 1191 * 1192 * @param alias Name of the token 1193 * @param token Token to be added 1194 * @return true on successful add of new token 1195 */ 1196 public synchronized boolean addToken(Text alias, 1197 Token<? extends TokenIdentifier> token) { 1198 getCredentialsInternal().addToken(alias, token); 1199 return true; 1200 } 1201 1202 /** 1203 * Obtain the collection of tokens associated with this user. 1204 * 1205 * @return an unmodifiable collection of tokens associated with user 1206 */ 1207 public synchronized 1208 Collection<Token<? extends TokenIdentifier>> getTokens() { 1209 return Collections.unmodifiableCollection( 1210 getCredentialsInternal().getAllTokens()); 1211 } 1212 1213 /** 1214 * Obtain the tokens in credentials form associated with this user. 1215 * 1216 * @return Credentials of tokens associated with this user 1217 */ 1218 public synchronized Credentials getCredentials() { 1219 return new Credentials(getCredentialsInternal()); 1220 } 1221 1222 /** 1223 * Add the given Credentials to this user. 1224 * @param credentials of tokens and secrets 1225 */ 1226 public synchronized void addCredentials(Credentials credentials) { 1227 getCredentialsInternal().addAll(credentials); 1228 } 1229 1230 private synchronized Credentials getCredentialsInternal() { 1231 final Credentials credentials; 1232 final Set<Credentials> credentialsSet = 1233 subject.getPrivateCredentials(Credentials.class); 1234 if (!credentialsSet.isEmpty()){ 1235 credentials = credentialsSet.iterator().next(); 1236 } else { 1237 credentials = new Credentials(); 1238 subject.getPrivateCredentials().add(credentials); 1239 } 1240 return credentials; 1241 } 1242 1243 /** 1244 * Get the group names for this user. 1245 * @return the list of users with the primary group first. If the command 1246 * fails, it returns an empty list. 1247 */ 1248 public synchronized String[] getGroupNames() { 1249 ensureInitialized(); 1250 try { 1251 List<String> result = groups.getGroups(getShortUserName()); 1252 return result.toArray(new String[result.size()]); 1253 } catch (IOException ie) { 1254 LOG.warn("No groups available for user " + getShortUserName()); 1255 return new String[0]; 1256 } 1257 } 1258 1259 /** 1260 * Return the username. 1261 */ 1262 @Override 1263 public String toString() { 1264 StringBuilder sb = new StringBuilder(getUserName()); 1265 sb.append(" (auth:"+getAuthenticationMethod()+")"); 1266 if (getRealUser() != null) { 1267 sb.append(" via ").append(getRealUser().toString()); 1268 } 1269 return sb.toString(); 1270 } 1271 1272 /** 1273 * Sets the authentication method in the subject 1274 * 1275 * @param authMethod 1276 */ 1277 public synchronized 1278 void setAuthenticationMethod(AuthenticationMethod authMethod) { 1279 user.setAuthenticationMethod(authMethod); 1280 } 1281 1282 /** 1283 * Get the authentication method from the subject 1284 * 1285 * @return AuthenticationMethod in the subject, null if not present. 1286 */ 1287 public synchronized AuthenticationMethod getAuthenticationMethod() { 1288 return user.getAuthenticationMethod(); 1289 } 1290 1291 /** 1292 * Returns the authentication method of a ugi. If the authentication method is 1293 * PROXY, returns the authentication method of the real user. 1294 * 1295 * @param ugi 1296 * @return AuthenticationMethod 1297 */ 1298 public static AuthenticationMethod getRealAuthenticationMethod( 1299 UserGroupInformation ugi) { 1300 AuthenticationMethod authMethod = ugi.getAuthenticationMethod(); 1301 if (authMethod == AuthenticationMethod.PROXY) { 1302 authMethod = ugi.getRealUser().getAuthenticationMethod(); 1303 } 1304 return authMethod; 1305 } 1306 1307 /** 1308 * Compare the subjects to see if they are equal to each other. 1309 */ 1310 @Override 1311 public boolean equals(Object o) { 1312 if (o == this) { 1313 return true; 1314 } else if (o == null || getClass() != o.getClass()) { 1315 return false; 1316 } else { 1317 return subject == ((UserGroupInformation) o).subject; 1318 } 1319 } 1320 1321 /** 1322 * Return the hash of the subject. 1323 */ 1324 @Override 1325 public int hashCode() { 1326 return System.identityHashCode(subject); 1327 } 1328 1329 /** 1330 * Get the underlying subject from this ugi. 1331 * @return the subject that represents this user. 1332 */ 1333 protected Subject getSubject() { 1334 return subject; 1335 } 1336 1337 /** 1338 * Run the given action as the user. 1339 * @param <T> the return type of the run method 1340 * @param action the method to execute 1341 * @return the value from the run method 1342 */ 1343 @InterfaceAudience.Public 1344 @InterfaceStability.Evolving 1345 public <T> T doAs(PrivilegedAction<T> action) { 1346 logPrivilegedAction(subject, action); 1347 return Subject.doAs(subject, action); 1348 } 1349 1350 /** 1351 * Run the given action as the user, potentially throwing an exception. 1352 * @param <T> the return type of the run method 1353 * @param action the method to execute 1354 * @return the value from the run method 1355 * @throws IOException if the action throws an IOException 1356 * @throws Error if the action throws an Error 1357 * @throws RuntimeException if the action throws a RuntimeException 1358 * @throws InterruptedException if the action throws an InterruptedException 1359 * @throws UndeclaredThrowableException if the action throws something else 1360 */ 1361 @InterfaceAudience.Public 1362 @InterfaceStability.Evolving 1363 public <T> T doAs(PrivilegedExceptionAction<T> action 1364 ) throws IOException, InterruptedException { 1365 try { 1366 logPrivilegedAction(subject, action); 1367 return Subject.doAs(subject, action); 1368 } catch (PrivilegedActionException pae) { 1369 Throwable cause = pae.getCause(); 1370 LOG.error("PriviledgedActionException as:"+this+" cause:"+cause); 1371 if (cause instanceof IOException) { 1372 throw (IOException) cause; 1373 } else if (cause instanceof Error) { 1374 throw (Error) cause; 1375 } else if (cause instanceof RuntimeException) { 1376 throw (RuntimeException) cause; 1377 } else if (cause instanceof InterruptedException) { 1378 throw (InterruptedException) cause; 1379 } else { 1380 throw new UndeclaredThrowableException(pae,"Unknown exception in doAs"); 1381 } 1382 } 1383 } 1384 1385 private void logPrivilegedAction(Subject subject, Object action) { 1386 if (LOG.isDebugEnabled()) { 1387 // would be nice if action included a descriptive toString() 1388 String where = new Throwable().getStackTrace()[2].toString(); 1389 LOG.debug("PrivilegedAction as:"+this+" from:"+where); 1390 } 1391 } 1392 1393 private void print() throws IOException { 1394 System.out.println("User: " + getUserName()); 1395 System.out.print("Group Ids: "); 1396 System.out.println(); 1397 String[] groups = getGroupNames(); 1398 System.out.print("Groups: "); 1399 for(int i=0; i < groups.length; i++) { 1400 System.out.print(groups[i] + " "); 1401 } 1402 System.out.println(); 1403 } 1404 1405 /** 1406 * A test method to print out the current user's UGI. 1407 * @param args if there are two arguments, read the user from the keytab 1408 * and print it out. 1409 * @throws Exception 1410 */ 1411 public static void main(String [] args) throws Exception { 1412 System.out.println("Getting UGI for current user"); 1413 UserGroupInformation ugi = getCurrentUser(); 1414 ugi.print(); 1415 System.out.println("UGI: " + ugi); 1416 System.out.println("Auth method " + ugi.user.getAuthenticationMethod()); 1417 System.out.println("Keytab " + ugi.isKeytab); 1418 System.out.println("============================================================"); 1419 1420 if (args.length == 2) { 1421 System.out.println("Getting UGI from keytab...."); 1422 loginUserFromKeytab(args[0], args[1]); 1423 getCurrentUser().print(); 1424 System.out.println("Keytab: " + ugi); 1425 System.out.println("Auth method " + loginUser.user.getAuthenticationMethod()); 1426 System.out.println("Keytab " + loginUser.isKeytab); 1427 } 1428 } 1429 1430 }