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.security;
019
020import static org.apache.hadoop.fs.CommonConfigurationKeys.HADOOP_USER_GROUP_METRICS_PERCENTILES_INTERVALS;
021import static org.apache.hadoop.util.PlatformName.IBM_JAVA;
022
023import com.google.common.annotations.VisibleForTesting;
024
025import java.io.File;
026import java.io.IOException;
027import java.lang.reflect.UndeclaredThrowableException;
028import java.security.AccessControlContext;
029import java.security.AccessController;
030import java.security.Principal;
031import java.security.PrivilegedAction;
032import java.security.PrivilegedActionException;
033import java.security.PrivilegedExceptionAction;
034import java.util.ArrayList;
035import java.util.Arrays;
036import java.util.Collection;
037import java.util.Collections;
038import java.util.HashMap;
039import java.util.Iterator;
040import java.util.List;
041import java.util.Map;
042import java.util.Set;
043
044import javax.security.auth.DestroyFailedException;
045import javax.security.auth.Subject;
046import javax.security.auth.callback.CallbackHandler;
047import javax.security.auth.kerberos.KerberosPrincipal;
048import javax.security.auth.kerberos.KerberosTicket;
049import javax.security.auth.kerberos.KeyTab;
050import javax.security.auth.login.AppConfigurationEntry;
051import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag;
052import javax.security.auth.login.LoginContext;
053import javax.security.auth.login.LoginException;
054import javax.security.auth.spi.LoginModule;
055
056import org.apache.commons.logging.Log;
057import org.apache.commons.logging.LogFactory;
058import org.apache.hadoop.classification.InterfaceAudience;
059import org.apache.hadoop.classification.InterfaceStability;
060import org.apache.hadoop.conf.Configuration;
061import org.apache.hadoop.io.Text;
062import org.apache.hadoop.metrics2.annotation.Metric;
063import org.apache.hadoop.metrics2.annotation.Metrics;
064import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
065import org.apache.hadoop.metrics2.lib.MetricsRegistry;
066import org.apache.hadoop.metrics2.lib.MutableQuantiles;
067import org.apache.hadoop.metrics2.lib.MutableRate;
068import org.apache.hadoop.security.SaslRpcServer.AuthMethod;
069import org.apache.hadoop.security.authentication.util.KerberosUtil;
070import org.apache.hadoop.security.token.Token;
071import org.apache.hadoop.security.token.TokenIdentifier;
072import org.apache.hadoop.util.Shell;
073import org.apache.hadoop.util.StringUtils;
074import org.apache.hadoop.util.Time;
075
076/**
077 * User and group information for Hadoop.
078 * This class wraps around a JAAS Subject and provides methods to determine the
079 * user's username and groups. It supports both the Windows, Unix and Kerberos 
080 * login modules.
081 */
082@InterfaceAudience.LimitedPrivate({"HDFS", "MapReduce", "HBase", "Hive", "Oozie"})
083@InterfaceStability.Evolving
084public class UserGroupInformation {
085  private static final Log LOG =  LogFactory.getLog(UserGroupInformation.class);
086  /**
087   * Percentage of the ticket window to use before we renew ticket.
088   */
089  private static final float TICKET_RENEW_WINDOW = 0.80f;
090  private static boolean shouldRenewImmediatelyForTests = false;
091  static final String HADOOP_USER_NAME = "HADOOP_USER_NAME";
092  static final String HADOOP_PROXY_USER = "HADOOP_PROXY_USER";
093
094  /**
095   * For the purposes of unit tests, we want to test login
096   * from keytab and don't want to wait until the renew
097   * window (controlled by TICKET_RENEW_WINDOW).
098   * @param immediate true if we should login without waiting for ticket window
099   */
100  @VisibleForTesting
101  static void setShouldRenewImmediatelyForTests(boolean immediate) {
102    shouldRenewImmediatelyForTests = immediate;
103  }
104
105  /** 
106   * UgiMetrics maintains UGI activity statistics
107   * and publishes them through the metrics interfaces.
108   */
109  @Metrics(about="User and group related metrics", context="ugi")
110  static class UgiMetrics {
111    final MetricsRegistry registry = new MetricsRegistry("UgiMetrics");
112
113    @Metric("Rate of successful kerberos logins and latency (milliseconds)")
114    MutableRate loginSuccess;
115    @Metric("Rate of failed kerberos logins and latency (milliseconds)")
116    MutableRate loginFailure;
117    @Metric("GetGroups") MutableRate getGroups;
118    MutableQuantiles[] getGroupsQuantiles;
119
120    static UgiMetrics create() {
121      return DefaultMetricsSystem.instance().register(new UgiMetrics());
122    }
123
124    void addGetGroups(long latency) {
125      getGroups.add(latency);
126      if (getGroupsQuantiles != null) {
127        for (MutableQuantiles q : getGroupsQuantiles) {
128          q.add(latency);
129        }
130      }
131    }
132  }
133  
134  /**
135   * A login module that looks at the Kerberos, Unix, or Windows principal and
136   * adds the corresponding UserName.
137   */
138  @InterfaceAudience.Private
139  public static class HadoopLoginModule implements LoginModule {
140    private Subject subject;
141
142    @Override
143    public boolean abort() throws LoginException {
144      return true;
145    }
146
147    private <T extends Principal> T getCanonicalUser(Class<T> cls) {
148      for(T user: subject.getPrincipals(cls)) {
149        return user;
150      }
151      return null;
152    }
153
154    @Override
155    public boolean commit() throws LoginException {
156      if (LOG.isDebugEnabled()) {
157        LOG.debug("hadoop login commit");
158      }
159      // if we already have a user, we are done.
160      if (!subject.getPrincipals(User.class).isEmpty()) {
161        if (LOG.isDebugEnabled()) {
162          LOG.debug("using existing subject:"+subject.getPrincipals());
163        }
164        return true;
165      }
166      Principal user = null;
167      // if we are using kerberos, try it out
168      if (isAuthenticationMethodEnabled(AuthenticationMethod.KERBEROS)) {
169        user = getCanonicalUser(KerberosPrincipal.class);
170        if (LOG.isDebugEnabled()) {
171          LOG.debug("using kerberos user:"+user);
172        }
173      }
174      //If we don't have a kerberos user and security is disabled, check
175      //if user is specified in the environment or properties
176      if (!isSecurityEnabled() && (user == null)) {
177        String envUser = System.getenv(HADOOP_USER_NAME);
178        if (envUser == null) {
179          envUser = System.getProperty(HADOOP_USER_NAME);
180        }
181        user = envUser == null ? null : new User(envUser);
182      }
183      // use the OS user
184      if (user == null) {
185        user = getCanonicalUser(OS_PRINCIPAL_CLASS);
186        if (LOG.isDebugEnabled()) {
187          LOG.debug("using local user:"+user);
188        }
189      }
190      // if we found the user, add our principal
191      if (user != null) {
192        if (LOG.isDebugEnabled()) {
193          LOG.debug("Using user: \"" + user + "\" with name " + user.getName());
194        }
195
196        User userEntry = null;
197        try {
198          userEntry = new User(user.getName());
199        } catch (Exception e) {
200          throw (LoginException)(new LoginException(e.toString()).initCause(e));
201        }
202        if (LOG.isDebugEnabled()) {
203          LOG.debug("User entry: \"" + userEntry.toString() + "\"" );
204        }
205
206        subject.getPrincipals().add(userEntry);
207        return true;
208      }
209      LOG.error("Can't find user in " + subject);
210      throw new LoginException("Can't find user name");
211    }
212
213    @Override
214    public void initialize(Subject subject, CallbackHandler callbackHandler,
215                           Map<String, ?> sharedState, Map<String, ?> options) {
216      this.subject = subject;
217    }
218
219    @Override
220    public boolean login() throws LoginException {
221      if (LOG.isDebugEnabled()) {
222        LOG.debug("hadoop login");
223      }
224      return true;
225    }
226
227    @Override
228    public boolean logout() throws LoginException {
229      if (LOG.isDebugEnabled()) {
230        LOG.debug("hadoop logout");
231      }
232      return true;
233    }
234  }
235
236  /** Metrics to track UGI activity */
237  static UgiMetrics metrics = UgiMetrics.create();
238  /** The auth method to use */
239  private static AuthenticationMethod authenticationMethod;
240  /** Server-side groups fetching service */
241  private static Groups groups;
242  /** The configuration to use */
243  private static Configuration conf;
244
245  
246  /** Leave 10 minutes between relogin attempts. */
247  private static final long MIN_TIME_BEFORE_RELOGIN = 10 * 60 * 1000L;
248  
249  /**Environment variable pointing to the token cache file*/
250  public static final String HADOOP_TOKEN_FILE_LOCATION = 
251    "HADOOP_TOKEN_FILE_LOCATION";
252  
253  /** 
254   * A method to initialize the fields that depend on a configuration.
255   * Must be called before useKerberos or groups is used.
256   */
257  private static void ensureInitialized() {
258    if (conf == null) {
259      synchronized(UserGroupInformation.class) {
260        if (conf == null) { // someone might have beat us
261          initialize(new Configuration(), false);
262        }
263      }
264    }
265  }
266
267  /**
268   * Initialize UGI and related classes.
269   * @param conf the configuration to use
270   */
271  private static synchronized void initialize(Configuration conf,
272                                              boolean overrideNameRules) {
273    authenticationMethod = SecurityUtil.getAuthenticationMethod(conf);
274    if (overrideNameRules || !HadoopKerberosName.hasRulesBeenSet()) {
275      try {
276        HadoopKerberosName.setConfiguration(conf);
277      } catch (IOException ioe) {
278        throw new RuntimeException(
279            "Problem with Kerberos auth_to_local name configuration", ioe);
280      }
281    }
282    // If we haven't set up testing groups, use the configuration to find it
283    if (!(groups instanceof TestingGroups)) {
284      groups = Groups.getUserToGroupsMappingService(conf);
285    }
286    UserGroupInformation.conf = conf;
287
288    if (metrics.getGroupsQuantiles == null) {
289      int[] intervals = conf.getInts(HADOOP_USER_GROUP_METRICS_PERCENTILES_INTERVALS);
290      if (intervals != null && intervals.length > 0) {
291        final int length = intervals.length;
292        MutableQuantiles[] getGroupsQuantiles = new MutableQuantiles[length];
293        for (int i = 0; i < length; i++) {
294          getGroupsQuantiles[i] = metrics.registry.newQuantiles(
295            "getGroups" + intervals[i] + "s",
296            "Get groups", "ops", "latency", intervals[i]);
297        }
298        metrics.getGroupsQuantiles = getGroupsQuantiles;
299      }
300    }
301  }
302
303  /**
304   * Set the static configuration for UGI.
305   * In particular, set the security authentication mechanism and the
306   * group look up service.
307   * @param conf the configuration to use
308   */
309  @InterfaceAudience.Public
310  @InterfaceStability.Evolving
311  public static void setConfiguration(Configuration conf) {
312    initialize(conf, true);
313  }
314  
315  @InterfaceAudience.Private
316  @VisibleForTesting
317  public static void reset() {
318    authenticationMethod = null;
319    conf = null;
320    groups = null;
321    setLoginUser(null);
322    HadoopKerberosName.setRules(null);
323  }
324  
325  /**
326   * Determine if UserGroupInformation is using Kerberos to determine
327   * user identities or is relying on simple authentication
328   * 
329   * @return true if UGI is working in a secure environment
330   */
331  public static boolean isSecurityEnabled() {
332    return !isAuthenticationMethodEnabled(AuthenticationMethod.SIMPLE);
333  }
334  
335  @InterfaceAudience.Private
336  @InterfaceStability.Evolving
337  private static boolean isAuthenticationMethodEnabled(AuthenticationMethod method) {
338    ensureInitialized();
339    return (authenticationMethod == method);
340  }
341  
342  /**
343   * Information about the logged in user.
344   */
345  private static UserGroupInformation loginUser = null;
346  private static String keytabPrincipal = null;
347  private static String keytabFile = null;
348
349  private final Subject subject;
350  // All non-static fields must be read-only caches that come from the subject.
351  private final User user;
352  private final boolean isKeytab;
353  private final boolean isKrbTkt;
354  
355  private static String OS_LOGIN_MODULE_NAME;
356  private static Class<? extends Principal> OS_PRINCIPAL_CLASS;
357  
358  private static final boolean windows =
359      System.getProperty("os.name").startsWith("Windows");
360  private static final boolean is64Bit =
361      System.getProperty("os.arch").contains("64");
362  private static final boolean aix = System.getProperty("os.name").equals("AIX");
363
364  /* Return the OS login module class name */
365  private static String getOSLoginModuleName() {
366    if (IBM_JAVA) {
367      if (windows) {
368        return is64Bit ? "com.ibm.security.auth.module.Win64LoginModule"
369            : "com.ibm.security.auth.module.NTLoginModule";
370      } else if (aix) {
371        return is64Bit ? "com.ibm.security.auth.module.AIX64LoginModule"
372            : "com.ibm.security.auth.module.AIXLoginModule";
373      } else {
374        return "com.ibm.security.auth.module.LinuxLoginModule";
375      }
376    } else {
377      return windows ? "com.sun.security.auth.module.NTLoginModule"
378        : "com.sun.security.auth.module.UnixLoginModule";
379    }
380  }
381
382  /* Return the OS principal class */
383  @SuppressWarnings("unchecked")
384  private static Class<? extends Principal> getOsPrincipalClass() {
385    ClassLoader cl = ClassLoader.getSystemClassLoader();
386    try {
387      String principalClass = null;
388      if (IBM_JAVA) {
389        if (is64Bit) {
390          principalClass = "com.ibm.security.auth.UsernamePrincipal";
391        } else {
392          if (windows) {
393            principalClass = "com.ibm.security.auth.NTUserPrincipal";
394          } else if (aix) {
395            principalClass = "com.ibm.security.auth.AIXPrincipal";
396          } else {
397            principalClass = "com.ibm.security.auth.LinuxPrincipal";
398          }
399        }
400      } else {
401        principalClass = windows ? "com.sun.security.auth.NTUserPrincipal"
402            : "com.sun.security.auth.UnixPrincipal";
403      }
404      return (Class<? extends Principal>) cl.loadClass(principalClass);
405    } catch (ClassNotFoundException e) {
406      LOG.error("Unable to find JAAS classes:" + e.getMessage());
407    }
408    return null;
409  }
410  static {
411    OS_LOGIN_MODULE_NAME = getOSLoginModuleName();
412    OS_PRINCIPAL_CLASS = getOsPrincipalClass();
413  }
414
415  private static class RealUser implements Principal {
416    private final UserGroupInformation realUser;
417    
418    RealUser(UserGroupInformation realUser) {
419      this.realUser = realUser;
420    }
421    
422    @Override
423    public String getName() {
424      return realUser.getUserName();
425    }
426    
427    public UserGroupInformation getRealUser() {
428      return realUser;
429    }
430    
431    @Override
432    public boolean equals(Object o) {
433      if (this == o) {
434        return true;
435      } else if (o == null || getClass() != o.getClass()) {
436        return false;
437      } else {
438        return realUser.equals(((RealUser) o).realUser);
439      }
440    }
441    
442    @Override
443    public int hashCode() {
444      return realUser.hashCode();
445    }
446    
447    @Override
448    public String toString() {
449      return realUser.toString();
450    }
451  }
452  
453  /**
454   * A JAAS configuration that defines the login modules that we want
455   * to use for login.
456   */
457  private static class HadoopConfiguration 
458      extends javax.security.auth.login.Configuration {
459    private static final String SIMPLE_CONFIG_NAME = "hadoop-simple";
460    private static final String USER_KERBEROS_CONFIG_NAME = 
461      "hadoop-user-kerberos";
462    private static final String KEYTAB_KERBEROS_CONFIG_NAME = 
463      "hadoop-keytab-kerberos";
464
465    private static final Map<String, String> BASIC_JAAS_OPTIONS =
466      new HashMap<String,String>();
467    static {
468      String jaasEnvVar = System.getenv("HADOOP_JAAS_DEBUG");
469      if (jaasEnvVar != null && "true".equalsIgnoreCase(jaasEnvVar)) {
470        BASIC_JAAS_OPTIONS.put("debug", "true");
471      }
472    }
473    
474    private static final AppConfigurationEntry OS_SPECIFIC_LOGIN =
475      new AppConfigurationEntry(OS_LOGIN_MODULE_NAME,
476                                LoginModuleControlFlag.REQUIRED,
477                                BASIC_JAAS_OPTIONS);
478    private static final AppConfigurationEntry HADOOP_LOGIN =
479      new AppConfigurationEntry(HadoopLoginModule.class.getName(),
480                                LoginModuleControlFlag.REQUIRED,
481                                BASIC_JAAS_OPTIONS);
482    private static final Map<String,String> USER_KERBEROS_OPTIONS = 
483      new HashMap<String,String>();
484    static {
485      if (IBM_JAVA) {
486        USER_KERBEROS_OPTIONS.put("useDefaultCcache", "true");
487      } else {
488        USER_KERBEROS_OPTIONS.put("doNotPrompt", "true");
489        USER_KERBEROS_OPTIONS.put("useTicketCache", "true");
490      }
491      String ticketCache = System.getenv("KRB5CCNAME");
492      if (ticketCache != null) {
493        if (IBM_JAVA) {
494          // The first value searched when "useDefaultCcache" is used.
495          System.setProperty("KRB5CCNAME", ticketCache);
496        } else {
497          USER_KERBEROS_OPTIONS.put("ticketCache", ticketCache);
498        }
499      }
500      USER_KERBEROS_OPTIONS.put("renewTGT", "true");
501      USER_KERBEROS_OPTIONS.putAll(BASIC_JAAS_OPTIONS);
502    }
503    private static final AppConfigurationEntry USER_KERBEROS_LOGIN =
504      new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(),
505                                LoginModuleControlFlag.OPTIONAL,
506                                USER_KERBEROS_OPTIONS);
507    private static final Map<String,String> KEYTAB_KERBEROS_OPTIONS = 
508      new HashMap<String,String>();
509    static {
510      if (IBM_JAVA) {
511        KEYTAB_KERBEROS_OPTIONS.put("credsType", "both");
512      } else {
513        KEYTAB_KERBEROS_OPTIONS.put("doNotPrompt", "true");
514        KEYTAB_KERBEROS_OPTIONS.put("useKeyTab", "true");
515        KEYTAB_KERBEROS_OPTIONS.put("storeKey", "true");
516      }
517      KEYTAB_KERBEROS_OPTIONS.put("refreshKrb5Config", "true");
518      KEYTAB_KERBEROS_OPTIONS.putAll(BASIC_JAAS_OPTIONS);      
519    }
520    private static final AppConfigurationEntry KEYTAB_KERBEROS_LOGIN =
521      new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(),
522                                LoginModuleControlFlag.REQUIRED,
523                                KEYTAB_KERBEROS_OPTIONS);
524    
525    private static final AppConfigurationEntry[] SIMPLE_CONF = 
526      new AppConfigurationEntry[]{OS_SPECIFIC_LOGIN, HADOOP_LOGIN};
527    
528    private static final AppConfigurationEntry[] USER_KERBEROS_CONF =
529      new AppConfigurationEntry[]{OS_SPECIFIC_LOGIN, USER_KERBEROS_LOGIN,
530                                  HADOOP_LOGIN};
531
532    private static final AppConfigurationEntry[] KEYTAB_KERBEROS_CONF =
533      new AppConfigurationEntry[]{KEYTAB_KERBEROS_LOGIN, HADOOP_LOGIN};
534
535    @Override
536    public AppConfigurationEntry[] getAppConfigurationEntry(String appName) {
537      if (SIMPLE_CONFIG_NAME.equals(appName)) {
538        return SIMPLE_CONF;
539      } else if (USER_KERBEROS_CONFIG_NAME.equals(appName)) {
540        return USER_KERBEROS_CONF;
541      } else if (KEYTAB_KERBEROS_CONFIG_NAME.equals(appName)) {
542        if (IBM_JAVA) {
543          KEYTAB_KERBEROS_OPTIONS.put("useKeytab",
544              prependFileAuthority(keytabFile));
545        } else {
546          KEYTAB_KERBEROS_OPTIONS.put("keyTab", keytabFile);
547        }
548        KEYTAB_KERBEROS_OPTIONS.put("principal", keytabPrincipal);
549        return KEYTAB_KERBEROS_CONF;
550      }
551      return null;
552    }
553  }
554
555  private static String prependFileAuthority(String keytabPath) {
556    return keytabPath.startsWith("file://") ? keytabPath
557        : "file://" + keytabPath;
558  }
559
560  /**
561   * Represents a javax.security configuration that is created at runtime.
562   */
563  private static class DynamicConfiguration
564      extends javax.security.auth.login.Configuration {
565    private AppConfigurationEntry[] ace;
566    
567    DynamicConfiguration(AppConfigurationEntry[] ace) {
568      this.ace = ace;
569    }
570    
571    @Override
572    public AppConfigurationEntry[] getAppConfigurationEntry(String appName) {
573      return ace;
574    }
575  }
576
577  private static LoginContext
578  newLoginContext(String appName, Subject subject,
579    javax.security.auth.login.Configuration loginConf)
580      throws LoginException {
581    // Temporarily switch the thread's ContextClassLoader to match this
582    // class's classloader, so that we can properly load HadoopLoginModule
583    // from the JAAS libraries.
584    Thread t = Thread.currentThread();
585    ClassLoader oldCCL = t.getContextClassLoader();
586    t.setContextClassLoader(HadoopLoginModule.class.getClassLoader());
587    try {
588      return new LoginContext(appName, subject, null, loginConf);
589    } finally {
590      t.setContextClassLoader(oldCCL);
591    }
592  }
593
594  private LoginContext getLogin() {
595    return user.getLogin();
596  }
597  
598  private void setLogin(LoginContext login) {
599    user.setLogin(login);
600  }
601
602  /**
603   * Create a UserGroupInformation for the given subject.
604   * This does not change the subject or acquire new credentials.
605   * @param subject the user's subject
606   */
607  UserGroupInformation(Subject subject) {
608    this(subject, false);
609  }
610
611  /**
612   * Create a UGI from the given subject.
613   * @param subject the subject
614   * @param externalKeyTab if the subject's keytab is managed by the user.
615   *                       Setting this to true will prevent UGI from attempting
616   *                       to login the keytab, or to renew it.
617   */
618  private UserGroupInformation(Subject subject, final boolean externalKeyTab) {
619    this.subject = subject;
620    this.user = subject.getPrincipals(User.class).iterator().next();
621    if (externalKeyTab) {
622      this.isKeytab = false;
623    } else {
624      this.isKeytab = !subject.getPrivateCredentials(KeyTab.class).isEmpty();
625    }
626    this.isKrbTkt = !subject.getPrivateCredentials(KerberosTicket.class).isEmpty();
627  }
628  
629  /**
630   * checks if logged in using kerberos
631   * @return true if the subject logged via keytab or has a Kerberos TGT
632   */
633  public boolean hasKerberosCredentials() {
634    return isKeytab || isKrbTkt;
635  }
636
637  /**
638   * Return the current user, including any doAs in the current stack.
639   * @return the current user
640   * @throws IOException if login fails
641   */
642  @InterfaceAudience.Public
643  @InterfaceStability.Evolving
644  public synchronized
645  static UserGroupInformation getCurrentUser() throws IOException {
646    AccessControlContext context = AccessController.getContext();
647    Subject subject = Subject.getSubject(context);
648    if (subject == null || subject.getPrincipals(User.class).isEmpty()) {
649      return getLoginUser();
650    } else {
651      return new UserGroupInformation(subject);
652    }
653  }
654
655  /**
656   * Find the most appropriate UserGroupInformation to use
657   *
658   * @param ticketCachePath    The Kerberos ticket cache path, or NULL
659   *                           if none is specfied
660   * @param user               The user name, or NULL if none is specified.
661   *
662   * @return                   The most appropriate UserGroupInformation
663   */ 
664  public static UserGroupInformation getBestUGI(
665      String ticketCachePath, String user) throws IOException {
666    if (ticketCachePath != null) {
667      return getUGIFromTicketCache(ticketCachePath, user);
668    } else if (user == null) {
669      return getCurrentUser();
670    } else {
671      return createRemoteUser(user);
672    }    
673  }
674
675  /**
676   * Create a UserGroupInformation from a Kerberos ticket cache.
677   * 
678   * @param user                The principal name to load from the ticket
679   *                            cache
680   * @param ticketCachePath     the path to the ticket cache file
681   *
682   * @throws IOException        if the kerberos login fails
683   */
684  @InterfaceAudience.Public
685  @InterfaceStability.Evolving
686  public static UserGroupInformation getUGIFromTicketCache(
687            String ticketCache, String user) throws IOException {
688    if (!isAuthenticationMethodEnabled(AuthenticationMethod.KERBEROS)) {
689      return getBestUGI(null, user);
690    }
691    try {
692      Map<String,String> krbOptions = new HashMap<String,String>();
693      if (IBM_JAVA) {
694        krbOptions.put("useDefaultCcache", "true");
695        // The first value searched when "useDefaultCcache" is used.
696        System.setProperty("KRB5CCNAME", ticketCache);
697      } else {
698        krbOptions.put("doNotPrompt", "true");
699        krbOptions.put("useTicketCache", "true");
700        krbOptions.put("useKeyTab", "false");
701        krbOptions.put("ticketCache", ticketCache);
702      }
703      krbOptions.put("renewTGT", "false");
704      krbOptions.putAll(HadoopConfiguration.BASIC_JAAS_OPTIONS);
705      AppConfigurationEntry ace = new AppConfigurationEntry(
706          KerberosUtil.getKrb5LoginModuleName(),
707          LoginModuleControlFlag.REQUIRED,
708          krbOptions);
709      DynamicConfiguration dynConf =
710          new DynamicConfiguration(new AppConfigurationEntry[]{ ace });
711      LoginContext login = newLoginContext(
712          HadoopConfiguration.USER_KERBEROS_CONFIG_NAME, null, dynConf);
713      login.login();
714
715      Subject loginSubject = login.getSubject();
716      Set<Principal> loginPrincipals = loginSubject.getPrincipals();
717      if (loginPrincipals.isEmpty()) {
718        throw new RuntimeException("No login principals found!");
719      }
720      if (loginPrincipals.size() != 1) {
721        LOG.warn("found more than one principal in the ticket cache file " +
722          ticketCache);
723      }
724      User ugiUser = new User(loginPrincipals.iterator().next().getName(),
725          AuthenticationMethod.KERBEROS, login);
726      loginSubject.getPrincipals().add(ugiUser);
727      UserGroupInformation ugi = new UserGroupInformation(loginSubject);
728      ugi.setLogin(login);
729      ugi.setAuthenticationMethod(AuthenticationMethod.KERBEROS);
730      return ugi;
731    } catch (LoginException le) {
732      throw new IOException("failure to login using ticket cache file " +
733          ticketCache, le);
734    }
735  }
736
737   /**
738   * Create a UserGroupInformation from a Subject with Kerberos principal.
739   *
740   * @param user                The KerberosPrincipal to use in UGI
741   *
742   * @throws IOException        if the kerberos login fails
743   */
744  public static UserGroupInformation getUGIFromSubject(Subject subject)
745      throws IOException {
746    if (subject == null) {
747      throw new IOException("Subject must not be null");
748    }
749
750    if (subject.getPrincipals(KerberosPrincipal.class).isEmpty()) {
751      throw new IOException("Provided Subject must contain a KerberosPrincipal");
752    }
753
754    KerberosPrincipal principal =
755        subject.getPrincipals(KerberosPrincipal.class).iterator().next();
756
757    User ugiUser = new User(principal.getName(),
758        AuthenticationMethod.KERBEROS, null);
759    subject.getPrincipals().add(ugiUser);
760    UserGroupInformation ugi = new UserGroupInformation(subject);
761    ugi.setLogin(null);
762    ugi.setAuthenticationMethod(AuthenticationMethod.KERBEROS);
763    return ugi;
764  }
765
766  /**
767   * Get the currently logged in user.
768   * @return the logged in user
769   * @throws IOException if login fails
770   */
771  @InterfaceAudience.Public
772  @InterfaceStability.Evolving
773  public synchronized 
774  static UserGroupInformation getLoginUser() throws IOException {
775    if (loginUser == null) {
776      loginUserFromSubject(null);
777    }
778    return loginUser;
779  }
780
781  /**
782   * remove the login method that is followed by a space from the username
783   * e.g. "jack (auth:SIMPLE)" -> "jack"
784   *
785   * @param userName
786   * @return userName without login method
787   */
788  public static String trimLoginMethod(String userName) {
789    int spaceIndex = userName.indexOf(' ');
790    if (spaceIndex >= 0) {
791      userName = userName.substring(0, spaceIndex);
792    }
793    return userName;
794  }
795
796  /**
797   * Log in a user using the given subject
798   * @parma subject the subject to use when logging in a user, or null to 
799   * create a new subject.
800   * @throws IOException if login fails
801   */
802  @InterfaceAudience.Public
803  @InterfaceStability.Evolving
804  public synchronized 
805  static void loginUserFromSubject(Subject subject) throws IOException {
806    ensureInitialized();
807    try {
808      if (subject == null) {
809        subject = new Subject();
810      }
811      LoginContext login =
812          newLoginContext(authenticationMethod.getLoginAppName(), 
813                          subject, new HadoopConfiguration());
814      login.login();
815      LOG.debug("Assuming keytab is managed externally since logged in from"
816          + " subject.");
817      UserGroupInformation realUser = new UserGroupInformation(subject, true);
818      realUser.setLogin(login);
819      realUser.setAuthenticationMethod(authenticationMethod);
820      // If the HADOOP_PROXY_USER environment variable or property
821      // is specified, create a proxy user as the logged in user.
822      String proxyUser = System.getenv(HADOOP_PROXY_USER);
823      if (proxyUser == null) {
824        proxyUser = System.getProperty(HADOOP_PROXY_USER);
825      }
826      loginUser = proxyUser == null ? realUser : createProxyUser(proxyUser, realUser);
827
828      String fileLocation = System.getenv(HADOOP_TOKEN_FILE_LOCATION);
829      if (fileLocation != null) {
830        // Load the token storage file and put all of the tokens into the
831        // user. Don't use the FileSystem API for reading since it has a lock
832        // cycle (HADOOP-9212).
833        Credentials cred = Credentials.readTokenStorageFile(
834            new File(fileLocation), conf);
835        loginUser.addCredentials(cred);
836      }
837      loginUser.spawnAutoRenewalThreadForUserCreds();
838    } catch (LoginException le) {
839      LOG.debug("failure to login", le);
840      throw new IOException("failure to login", le);
841    }
842    if (LOG.isDebugEnabled()) {
843      LOG.debug("UGI loginUser:"+loginUser);
844    } 
845  }
846
847  @InterfaceAudience.Private
848  @InterfaceStability.Unstable
849  @VisibleForTesting
850  public synchronized static void setLoginUser(UserGroupInformation ugi) {
851    // if this is to become stable, should probably logout the currently
852    // logged in ugi if it's different
853    loginUser = ugi;
854  }
855  
856  /**
857   * Is this user logged in from a keytab file?
858   * @return true if the credentials are from a keytab file.
859   */
860  public boolean isFromKeytab() {
861    return isKeytab;
862  }
863  
864  /**
865   * Get the Kerberos TGT
866   * @return the user's TGT or null if none was found
867   */
868  private synchronized KerberosTicket getTGT() {
869    Set<KerberosTicket> tickets = subject
870        .getPrivateCredentials(KerberosTicket.class);
871    for (KerberosTicket ticket : tickets) {
872      if (SecurityUtil.isOriginalTGT(ticket)) {
873        if (LOG.isDebugEnabled()) {
874          LOG.debug("Found tgt " + ticket);
875        }
876        return ticket;
877      }
878    }
879    return null;
880  }
881  
882  private long getRefreshTime(KerberosTicket tgt) {
883    long start = tgt.getStartTime().getTime();
884    long end = tgt.getEndTime().getTime();
885    return start + (long) ((end - start) * TICKET_RENEW_WINDOW);
886  }
887
888  /**Spawn a thread to do periodic renewals of kerberos credentials*/
889  private void spawnAutoRenewalThreadForUserCreds() {
890    if (isSecurityEnabled()) {
891      //spawn thread only if we have kerb credentials
892      if (user.getAuthenticationMethod() == AuthenticationMethod.KERBEROS &&
893          !isKeytab) {
894        Thread t = new Thread(new Runnable() {
895          
896          @Override
897          public void run() {
898            String cmd = conf.get("hadoop.kerberos.kinit.command",
899                                  "kinit");
900            KerberosTicket tgt = getTGT();
901            if (tgt == null) {
902              return;
903            }
904            long nextRefresh = getRefreshTime(tgt);
905            while (true) {
906              try {
907                long now = Time.now();
908                if(LOG.isDebugEnabled()) {
909                  LOG.debug("Current time is " + now);
910                  LOG.debug("Next refresh is " + nextRefresh);
911                }
912                if (now < nextRefresh) {
913                  Thread.sleep(nextRefresh - now);
914                }
915                Shell.execCommand(cmd, "-R");
916                if(LOG.isDebugEnabled()) {
917                  LOG.debug("renewed ticket");
918                }
919                reloginFromTicketCache();
920                tgt = getTGT();
921                if (tgt == null) {
922                  LOG.warn("No TGT after renewal. Aborting renew thread for " +
923                           getUserName());
924                  return;
925                }
926                nextRefresh = Math.max(getRefreshTime(tgt),
927                                       now + MIN_TIME_BEFORE_RELOGIN);
928              } catch (InterruptedException ie) {
929                LOG.warn("Terminating renewal thread");
930                return;
931              } catch (IOException ie) {
932                LOG.warn("Exception encountered while running the" +
933                    " renewal command. Aborting renew thread. " + ie);
934                return;
935              }
936            }
937          }
938        });
939        t.setDaemon(true);
940        t.setName("TGT Renewer for " + getUserName());
941        t.start();
942      }
943    }
944  }
945  /**
946   * Log a user in from a keytab file. Loads a user identity from a keytab
947   * file and logs them in. They become the currently logged-in user.
948   * @param user the principal name to load from the keytab
949   * @param path the path to the keytab file
950   * @throws IOException if the keytab file can't be read
951   */
952  @InterfaceAudience.Public
953  @InterfaceStability.Evolving
954  public synchronized
955  static void loginUserFromKeytab(String user,
956                                  String path
957                                  ) throws IOException {
958    if (!isSecurityEnabled())
959      return;
960
961    keytabFile = path;
962    keytabPrincipal = user;
963    Subject subject = new Subject();
964    LoginContext login; 
965    long start = 0;
966    try {
967      login = newLoginContext(HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME,
968            subject, new HadoopConfiguration());
969      start = Time.now();
970      login.login();
971      metrics.loginSuccess.add(Time.now() - start);
972      loginUser = new UserGroupInformation(subject);
973      loginUser.setLogin(login);
974      loginUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS);
975    } catch (LoginException le) {
976      if (start > 0) {
977        metrics.loginFailure.add(Time.now() - start);
978      }
979      throw new IOException("Login failure for " + user + " from keytab " + 
980                            path+ ": " + le, le);
981    }
982    LOG.info("Login successful for user " + keytabPrincipal
983        + " using keytab file " + keytabFile);
984  }
985
986  /**
987   * Log the current user out who previously logged in using keytab.
988   * This method assumes that the user logged in by calling
989   * {@link #loginUserFromKeytab(String, String)}.
990   *
991   * @throws IOException if a failure occurred in logout, or if the user did
992   * not log in by invoking loginUserFromKeyTab() before.
993   */
994  @InterfaceAudience.Public
995  @InterfaceStability.Evolving
996  public void logoutUserFromKeytab() throws IOException {
997    if (!isSecurityEnabled() ||
998        user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS) {
999      return;
1000    }
1001    LoginContext login = getLogin();
1002    if (login == null || keytabFile == null) {
1003      throw new IOException("loginUserFromKeytab must be done first");
1004    }
1005
1006    try {
1007      if (LOG.isDebugEnabled()) {
1008        LOG.debug("Initiating logout for " + getUserName());
1009      }
1010      synchronized (UserGroupInformation.class) {
1011        login.logout();
1012      }
1013    } catch (LoginException le) {
1014      throw new IOException("Logout failure for " + user + " from keytab " +
1015          keytabFile, le);
1016    }
1017
1018    LOG.info("Logout successful for user " + keytabPrincipal
1019        + " using keytab file " + keytabFile);
1020  }
1021  
1022  /**
1023   * Re-login a user from keytab if TGT is expired or is close to expiry.
1024   * 
1025   * @throws IOException
1026   */
1027  public synchronized void checkTGTAndReloginFromKeytab() throws IOException {
1028    if (!isSecurityEnabled()
1029        || user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS
1030        || !isKeytab)
1031      return;
1032    KerberosTicket tgt = getTGT();
1033    if (tgt != null && !shouldRenewImmediatelyForTests &&
1034        Time.now() < getRefreshTime(tgt)) {
1035      return;
1036    }
1037    reloginFromKeytab();
1038  }
1039
1040  // if the first kerberos ticket is not TGT, then remove and destroy it since
1041  // the kerberos library of jdk always use the first kerberos ticket as TGT.
1042  // See HADOOP-13433 for more details.
1043  private void fixKerberosTicketOrder() {
1044    Set<Object> creds = getSubject().getPrivateCredentials();
1045    synchronized (creds) {
1046      for (Iterator<Object> iter = creds.iterator(); iter.hasNext();) {
1047        Object cred = iter.next();
1048        if (cred instanceof KerberosTicket) {
1049          KerberosTicket ticket = (KerberosTicket) cred;
1050          if (ticket.isDestroyed() || ticket.getServer() == null) {
1051            LOG.warn("Ticket is already destroyed, remove it.");
1052            iter.remove();
1053          } else if (!ticket.getServer().getName().startsWith("krbtgt")) {
1054            LOG.warn(
1055                "The first kerberos ticket is not TGT"
1056                    + "(the server principal is " + ticket.getServer() +
1057                    ")), remove and destroy it.");
1058            iter.remove();
1059            try {
1060              ticket.destroy();
1061            } catch (DestroyFailedException e) {
1062              LOG.warn("destroy ticket failed", e);
1063            }
1064          } else {
1065            return;
1066          }
1067        }
1068      }
1069    }
1070    LOG.warn("Warning, no kerberos ticket found while attempting to renew" +
1071        " ticket");
1072  }
1073
1074  /**
1075   * Re-Login a user in from a keytab file. Loads a user identity from a keytab
1076   * file and logs them in. They become the currently logged-in user. This
1077   * method assumes that {@link #loginUserFromKeytab(String, String)} had
1078   * happened already.
1079   * The Subject field of this UserGroupInformation object is updated to have
1080   * the new credentials.
1081   * @throws IOException on a failure
1082   */
1083  @InterfaceAudience.Public
1084  @InterfaceStability.Evolving
1085  public synchronized void reloginFromKeytab() throws IOException {
1086    if (!isSecurityEnabled()
1087        || user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS
1088        || !isKeytab) {
1089      return;
1090    }
1091
1092    long now = Time.now();
1093    if (!shouldRenewImmediatelyForTests && !hasSufficientTimeElapsed(now)) {
1094      return;
1095    }
1096
1097    KerberosTicket tgt = getTGT();
1098    //Return if TGT is valid and is not going to expire soon.
1099    if (tgt != null && !shouldRenewImmediatelyForTests &&
1100        now < getRefreshTime(tgt)) {
1101      return;
1102    }
1103
1104    LoginContext login = getLogin();
1105    if (login == null || keytabFile == null) {
1106      throw new IOException("loginUserFromKeyTab must be done first");
1107    }
1108
1109    long start = 0;
1110    // register most recent relogin attempt
1111    user.setLastLogin(now);
1112    try {
1113      if (LOG.isDebugEnabled()) {
1114        LOG.debug("Initiating logout for " + getUserName());
1115      }
1116      synchronized (UserGroupInformation.class) {
1117        // clear up the kerberos state. But the tokens are not cleared! As per
1118        // the Java kerberos login module code, only the kerberos credentials
1119        // are cleared
1120        login.logout();
1121        // login and also update the subject field of this instance to
1122        // have the new credentials (pass it to the LoginContext constructor)
1123        login = newLoginContext(
1124            HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, getSubject(),
1125            new HadoopConfiguration());
1126        if (LOG.isDebugEnabled()) {
1127          LOG.debug("Initiating re-login for " + keytabPrincipal);
1128        }
1129        start = Time.now();
1130        login.login();
1131        fixKerberosTicketOrder();
1132        metrics.loginSuccess.add(Time.now() - start);
1133        setLogin(login);
1134      }
1135    } catch (LoginException le) {
1136      if (start > 0) {
1137        metrics.loginFailure.add(Time.now() - start);
1138      }
1139      throw new IOException("Login failure for " + keytabPrincipal + 
1140          " from keytab " + keytabFile, le);
1141    } 
1142  }
1143
1144  /**
1145   * Re-Login a user in from the ticket cache.  This
1146   * method assumes that login had happened already.
1147   * The Subject field of this UserGroupInformation object is updated to have
1148   * the new credentials.
1149   * @throws IOException on a failure
1150   */
1151  @InterfaceAudience.Public
1152  @InterfaceStability.Evolving
1153  public synchronized void reloginFromTicketCache() throws IOException {
1154    if (!isSecurityEnabled()
1155        || user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS
1156        || !isKrbTkt) {
1157      return;
1158    }
1159    LoginContext login = getLogin();
1160    if (login == null) {
1161      throw new IOException("login must be done first");
1162    }
1163    long now = Time.now();
1164    if (!hasSufficientTimeElapsed(now)) {
1165      return;
1166    }
1167    // register most recent relogin attempt
1168    user.setLastLogin(now);
1169    try {
1170      if (LOG.isDebugEnabled()) {
1171        LOG.debug("Initiating logout for " + getUserName());
1172      }
1173      //clear up the kerberos state. But the tokens are not cleared! As per 
1174      //the Java kerberos login module code, only the kerberos credentials
1175      //are cleared
1176      login.logout();
1177      //login and also update the subject field of this instance to 
1178      //have the new credentials (pass it to the LoginContext constructor)
1179      login = 
1180        newLoginContext(HadoopConfiguration.USER_KERBEROS_CONFIG_NAME, 
1181            getSubject(), new HadoopConfiguration());
1182      if (LOG.isDebugEnabled()) {
1183        LOG.debug("Initiating re-login for " + getUserName());
1184      }
1185      login.login();
1186      fixKerberosTicketOrder();
1187      setLogin(login);
1188    } catch (LoginException le) {
1189      throw new IOException("Login failure for " + getUserName(), le);
1190    } 
1191  }
1192
1193  /**
1194   * Log a user in from a keytab file. Loads a user identity from a keytab
1195   * file and login them in. This new user does not affect the currently
1196   * logged-in user.
1197   * @param user the principal name to load from the keytab
1198   * @param path the path to the keytab file
1199   * @throws IOException if the keytab file can't be read
1200   */
1201  public synchronized
1202  static UserGroupInformation loginUserFromKeytabAndReturnUGI(String user,
1203                                  String path
1204                                  ) throws IOException {
1205    if (!isSecurityEnabled())
1206      return UserGroupInformation.getCurrentUser();
1207    String oldKeytabFile = null;
1208    String oldKeytabPrincipal = null;
1209
1210    long start = 0;
1211    try {
1212      oldKeytabFile = keytabFile;
1213      oldKeytabPrincipal = keytabPrincipal;
1214      keytabFile = path;
1215      keytabPrincipal = user;
1216      Subject subject = new Subject();
1217      
1218      LoginContext login = newLoginContext(
1219          HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, subject,
1220          new HadoopConfiguration());
1221       
1222      start = Time.now();
1223      login.login();
1224      metrics.loginSuccess.add(Time.now() - start);
1225      UserGroupInformation newLoginUser = new UserGroupInformation(subject);
1226      newLoginUser.setLogin(login);
1227      newLoginUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS);
1228      
1229      return newLoginUser;
1230    } catch (LoginException le) {
1231      if (start > 0) {
1232        metrics.loginFailure.add(Time.now() - start);
1233      }
1234      throw new IOException("Login failure for " + user + " from keytab " + 
1235                            path, le);
1236    } finally {
1237      if(oldKeytabFile != null) keytabFile = oldKeytabFile;
1238      if(oldKeytabPrincipal != null) keytabPrincipal = oldKeytabPrincipal;
1239    }
1240  }
1241
1242  private boolean hasSufficientTimeElapsed(long now) {
1243    if (now - user.getLastLogin() < MIN_TIME_BEFORE_RELOGIN ) {
1244      LOG.warn("Not attempting to re-login since the last re-login was " +
1245          "attempted less than " + (MIN_TIME_BEFORE_RELOGIN/1000) + " seconds"+
1246          " before. Last Login=" + user.getLastLogin());
1247      return false;
1248    }
1249    return true;
1250  }
1251  
1252  /**
1253   * Did the login happen via keytab
1254   * @return true or false
1255   */
1256  @InterfaceAudience.Public
1257  @InterfaceStability.Evolving
1258  public synchronized static boolean isLoginKeytabBased() throws IOException {
1259    return getLoginUser().isKeytab;
1260  }
1261
1262  /**
1263   * Did the login happen via ticket cache
1264   * @return true or false
1265   */
1266  public static boolean isLoginTicketBased()  throws IOException {
1267    return getLoginUser().isKrbTkt;
1268  }
1269
1270  /**
1271   * Create a user from a login name. It is intended to be used for remote
1272   * users in RPC, since it won't have any credentials.
1273   * @param user the full user principal name, must not be empty or null
1274   * @return the UserGroupInformation for the remote user.
1275   */
1276  @InterfaceAudience.Public
1277  @InterfaceStability.Evolving
1278  public static UserGroupInformation createRemoteUser(String user) {
1279    return createRemoteUser(user, AuthMethod.SIMPLE);
1280  }
1281  
1282  /**
1283   * Create a user from a login name. It is intended to be used for remote
1284   * users in RPC, since it won't have any credentials.
1285   * @param user the full user principal name, must not be empty or null
1286   * @return the UserGroupInformation for the remote user.
1287   */
1288  @InterfaceAudience.Public
1289  @InterfaceStability.Evolving
1290  public static UserGroupInformation createRemoteUser(String user, AuthMethod authMethod) {
1291    if (user == null || user.isEmpty()) {
1292      throw new IllegalArgumentException("Null user");
1293    }
1294    Subject subject = new Subject();
1295    subject.getPrincipals().add(new User(user));
1296    UserGroupInformation result = new UserGroupInformation(subject);
1297    result.setAuthenticationMethod(authMethod);
1298    return result;
1299  }
1300
1301  /**
1302   * existing types of authentications' methods
1303   */
1304  @InterfaceAudience.Public
1305  @InterfaceStability.Evolving
1306  public static enum AuthenticationMethod {
1307    // currently we support only one auth per method, but eventually a 
1308    // subtype is needed to differentiate, ex. if digest is token or ldap
1309    SIMPLE(AuthMethod.SIMPLE,
1310        HadoopConfiguration.SIMPLE_CONFIG_NAME),
1311    KERBEROS(AuthMethod.KERBEROS,
1312        HadoopConfiguration.USER_KERBEROS_CONFIG_NAME),
1313    TOKEN(AuthMethod.TOKEN),
1314    CERTIFICATE(null),
1315    KERBEROS_SSL(null),
1316    PROXY(null);
1317    
1318    private final AuthMethod authMethod;
1319    private final String loginAppName;
1320    
1321    private AuthenticationMethod(AuthMethod authMethod) {
1322      this(authMethod, null);
1323    }
1324    private AuthenticationMethod(AuthMethod authMethod, String loginAppName) {
1325      this.authMethod = authMethod;
1326      this.loginAppName = loginAppName;
1327    }
1328    
1329    public AuthMethod getAuthMethod() {
1330      return authMethod;
1331    }
1332    
1333    String getLoginAppName() {
1334      if (loginAppName == null) {
1335        throw new UnsupportedOperationException(
1336            this + " login authentication is not supported");
1337      }
1338      return loginAppName;
1339    }
1340    
1341    public static AuthenticationMethod valueOf(AuthMethod authMethod) {
1342      for (AuthenticationMethod value : values()) {
1343        if (value.getAuthMethod() == authMethod) {
1344          return value;
1345        }
1346      }
1347      throw new IllegalArgumentException(
1348          "no authentication method for " + authMethod);
1349    }
1350  };
1351
1352  /**
1353   * Create a proxy user using username of the effective user and the ugi of the
1354   * real user.
1355   * @param user
1356   * @param realUser
1357   * @return proxyUser ugi
1358   */
1359  @InterfaceAudience.Public
1360  @InterfaceStability.Evolving
1361  public static UserGroupInformation createProxyUser(String user,
1362      UserGroupInformation realUser) {
1363    if (user == null || user.isEmpty()) {
1364      throw new IllegalArgumentException("Null user");
1365    }
1366    if (realUser == null) {
1367      throw new IllegalArgumentException("Null real user");
1368    }
1369    Subject subject = new Subject();
1370    Set<Principal> principals = subject.getPrincipals();
1371    principals.add(new User(user));
1372    principals.add(new RealUser(realUser));
1373    UserGroupInformation result =new UserGroupInformation(subject);
1374    result.setAuthenticationMethod(AuthenticationMethod.PROXY);
1375    return result;
1376  }
1377
1378  /**
1379   * get RealUser (vs. EffectiveUser)
1380   * @return realUser running over proxy user
1381   */
1382  @InterfaceAudience.Public
1383  @InterfaceStability.Evolving
1384  public UserGroupInformation getRealUser() {
1385    for (RealUser p: subject.getPrincipals(RealUser.class)) {
1386      return p.getRealUser();
1387    }
1388    return null;
1389  }
1390
1391
1392  
1393  /**
1394   * This class is used for storing the groups for testing. It stores a local
1395   * map that has the translation of usernames to groups.
1396   */
1397  private static class TestingGroups extends Groups {
1398    private final Map<String, List<String>> userToGroupsMapping = 
1399      new HashMap<String,List<String>>();
1400    private Groups underlyingImplementation;
1401    
1402    private TestingGroups(Groups underlyingImplementation) {
1403      super(new org.apache.hadoop.conf.Configuration());
1404      this.underlyingImplementation = underlyingImplementation;
1405    }
1406    
1407    @Override
1408    public List<String> getGroups(String user) throws IOException {
1409      List<String> result = userToGroupsMapping.get(user);
1410      
1411      if (result == null) {
1412        result = underlyingImplementation.getGroups(user);
1413      }
1414
1415      return result;
1416    }
1417
1418    private void setUserGroups(String user, String[] groups) {
1419      userToGroupsMapping.put(user, Arrays.asList(groups));
1420    }
1421  }
1422
1423  /**
1424   * Create a UGI for testing HDFS and MapReduce
1425   * @param user the full user principal name
1426   * @param userGroups the names of the groups that the user belongs to
1427   * @return a fake user for running unit tests
1428   */
1429  @InterfaceAudience.Public
1430  @InterfaceStability.Evolving
1431  public static UserGroupInformation createUserForTesting(String user, 
1432                                                          String[] userGroups) {
1433    ensureInitialized();
1434    UserGroupInformation ugi = createRemoteUser(user);
1435    // make sure that the testing object is setup
1436    if (!(groups instanceof TestingGroups)) {
1437      groups = new TestingGroups(groups);
1438    }
1439    // add the user groups
1440    ((TestingGroups) groups).setUserGroups(ugi.getShortUserName(), userGroups);
1441    return ugi;
1442  }
1443
1444
1445  /**
1446   * Create a proxy user UGI for testing HDFS and MapReduce
1447   * 
1448   * @param user
1449   *          the full user principal name for effective user
1450   * @param realUser
1451   *          UGI of the real user
1452   * @param userGroups
1453   *          the names of the groups that the user belongs to
1454   * @return a fake user for running unit tests
1455   */
1456  public static UserGroupInformation createProxyUserForTesting(String user,
1457      UserGroupInformation realUser, String[] userGroups) {
1458    ensureInitialized();
1459    UserGroupInformation ugi = createProxyUser(user, realUser);
1460    // make sure that the testing object is setup
1461    if (!(groups instanceof TestingGroups)) {
1462      groups = new TestingGroups(groups);
1463    }
1464    // add the user groups
1465    ((TestingGroups) groups).setUserGroups(ugi.getShortUserName(), userGroups);
1466    return ugi;
1467  }
1468  
1469  /**
1470   * Get the user's login name.
1471   * @return the user's name up to the first '/' or '@'.
1472   */
1473  public String getShortUserName() {
1474    for (User p: subject.getPrincipals(User.class)) {
1475      return p.getShortName();
1476    }
1477    return null;
1478  }
1479
1480  public String getPrimaryGroupName() throws IOException {
1481    List<String> groups = getGroups();
1482    if (groups.isEmpty()) {
1483      throw new IOException("There is no primary group for UGI " + this);
1484    }
1485    return groups.get(0);
1486  }
1487
1488  /**
1489   * Get the user's full principal name.
1490   * @return the user's full principal name.
1491   */
1492  @InterfaceAudience.Public
1493  @InterfaceStability.Evolving
1494  public String getUserName() {
1495    return user.getName();
1496  }
1497
1498  /**
1499   * Add a TokenIdentifier to this UGI. The TokenIdentifier has typically been
1500   * authenticated by the RPC layer as belonging to the user represented by this
1501   * UGI.
1502   * 
1503   * @param tokenId
1504   *          tokenIdentifier to be added
1505   * @return true on successful add of new tokenIdentifier
1506   */
1507  public synchronized boolean addTokenIdentifier(TokenIdentifier tokenId) {
1508    return subject.getPublicCredentials().add(tokenId);
1509  }
1510
1511  /**
1512   * Get the set of TokenIdentifiers belonging to this UGI
1513   * 
1514   * @return the set of TokenIdentifiers belonging to this UGI
1515   */
1516  public synchronized Set<TokenIdentifier> getTokenIdentifiers() {
1517    return subject.getPublicCredentials(TokenIdentifier.class);
1518  }
1519  
1520  /**
1521   * Add a token to this UGI
1522   * 
1523   * @param token Token to be added
1524   * @return true on successful add of new token
1525   */
1526  public boolean addToken(Token<? extends TokenIdentifier> token) {
1527    return (token != null) ? addToken(token.getService(), token) : false;
1528  }
1529
1530  /**
1531   * Add a named token to this UGI
1532   * 
1533   * @param alias Name of the token
1534   * @param token Token to be added
1535   * @return true on successful add of new token
1536   */
1537  public boolean addToken(Text alias, Token<? extends TokenIdentifier> token) {
1538    synchronized (subject) {
1539      getCredentialsInternal().addToken(alias, token);
1540      return true;
1541    }
1542  }
1543  
1544  /**
1545   * Obtain the collection of tokens associated with this user.
1546   * 
1547   * @return an unmodifiable collection of tokens associated with user
1548   */
1549  public Collection<Token<? extends TokenIdentifier>> getTokens() {
1550    synchronized (subject) {
1551      return Collections.unmodifiableCollection(
1552          new ArrayList<Token<?>>(getCredentialsInternal().getAllTokens()));
1553    }
1554  }
1555
1556  /**
1557   * Obtain the tokens in credentials form associated with this user.
1558   * 
1559   * @return Credentials of tokens associated with this user
1560   */
1561  public Credentials getCredentials() {
1562    synchronized (subject) {
1563      Credentials creds = new Credentials(getCredentialsInternal());
1564      Iterator<Token<?>> iter = creds.getAllTokens().iterator();
1565      while (iter.hasNext()) {
1566        if (iter.next() instanceof Token.PrivateToken) {
1567          iter.remove();
1568        }
1569      }
1570      return creds;
1571    }
1572  }
1573  
1574  /**
1575   * Add the given Credentials to this user.
1576   * @param credentials of tokens and secrets
1577   */
1578  public void addCredentials(Credentials credentials) {
1579    synchronized (subject) {
1580      getCredentialsInternal().addAll(credentials);
1581    }
1582  }
1583
1584  private synchronized Credentials getCredentialsInternal() {
1585    final Credentials credentials;
1586    final Set<Credentials> credentialsSet =
1587      subject.getPrivateCredentials(Credentials.class);
1588    if (!credentialsSet.isEmpty()){
1589      credentials = credentialsSet.iterator().next();
1590    } else {
1591      credentials = new Credentials();
1592      subject.getPrivateCredentials().add(credentials);
1593    }
1594    return credentials;
1595  }
1596
1597  /**
1598   * Get the group names for this user. {@ #getGroups(String)} is less
1599   * expensive alternative when checking for a contained element.
1600   * @return the list of users with the primary group first. If the command
1601   *    fails, it returns an empty list.
1602   */
1603  public String[] getGroupNames() {
1604    List<String> groups = getGroups();
1605    return groups.toArray(new String[groups.size()]);
1606  }
1607
1608  /**
1609   * Get the group names for this user.
1610   * @return the list of users with the primary group first. If the command
1611   *    fails, it returns an empty list.
1612   */
1613  public List<String> getGroups() {
1614    ensureInitialized();
1615    try {
1616      return groups.getGroups(getShortUserName());
1617    } catch (IOException ie) {
1618      if (LOG.isDebugEnabled()) {
1619        LOG.debug("Failed to get groups for user " + getShortUserName()
1620            + " by " + ie);
1621        LOG.trace("TRACE", ie);
1622      }
1623      return Collections.emptyList();
1624    }
1625  }
1626
1627  /**
1628   * Return the username.
1629   */
1630  @Override
1631  public String toString() {
1632    StringBuilder sb = new StringBuilder(getUserName());
1633    sb.append(" (auth:"+getAuthenticationMethod()+")");
1634    if (getRealUser() != null) {
1635      sb.append(" via ").append(getRealUser().toString());
1636    }
1637    return sb.toString();
1638  }
1639
1640  /**
1641   * Sets the authentication method in the subject
1642   * 
1643   * @param authMethod
1644   */
1645  public synchronized 
1646  void setAuthenticationMethod(AuthenticationMethod authMethod) {
1647    user.setAuthenticationMethod(authMethod);
1648  }
1649
1650  /**
1651   * Sets the authentication method in the subject
1652   * 
1653   * @param authMethod
1654   */
1655  public void setAuthenticationMethod(AuthMethod authMethod) {
1656    user.setAuthenticationMethod(AuthenticationMethod.valueOf(authMethod));
1657  }
1658
1659  /**
1660   * Get the authentication method from the subject
1661   * 
1662   * @return AuthenticationMethod in the subject, null if not present.
1663   */
1664  public synchronized AuthenticationMethod getAuthenticationMethod() {
1665    return user.getAuthenticationMethod();
1666  }
1667
1668  /**
1669   * Get the authentication method from the real user's subject.  If there
1670   * is no real user, return the given user's authentication method.
1671   * 
1672   * @return AuthenticationMethod in the subject, null if not present.
1673   */
1674  public synchronized AuthenticationMethod getRealAuthenticationMethod() {
1675    UserGroupInformation ugi = getRealUser();
1676    if (ugi == null) {
1677      ugi = this;
1678    }
1679    return ugi.getAuthenticationMethod();
1680  }
1681
1682  /**
1683   * Returns the authentication method of a ugi. If the authentication method is
1684   * PROXY, returns the authentication method of the real user.
1685   * 
1686   * @param ugi
1687   * @return AuthenticationMethod
1688   */
1689  public static AuthenticationMethod getRealAuthenticationMethod(
1690      UserGroupInformation ugi) {
1691    AuthenticationMethod authMethod = ugi.getAuthenticationMethod();
1692    if (authMethod == AuthenticationMethod.PROXY) {
1693      authMethod = ugi.getRealUser().getAuthenticationMethod();
1694    }
1695    return authMethod;
1696  }
1697
1698  /**
1699   * Compare the subjects to see if they are equal to each other.
1700   */
1701  @Override
1702  public boolean equals(Object o) {
1703    if (o == this) {
1704      return true;
1705    } else if (o == null || getClass() != o.getClass()) {
1706      return false;
1707    } else {
1708      return subject == ((UserGroupInformation) o).subject;
1709    }
1710  }
1711
1712  /**
1713   * Return the hash of the subject.
1714   */
1715  @Override
1716  public int hashCode() {
1717    return System.identityHashCode(subject);
1718  }
1719
1720  /**
1721   * Get the underlying subject from this ugi.
1722   * @return the subject that represents this user.
1723   */
1724  protected Subject getSubject() {
1725    return subject;
1726  }
1727
1728  /**
1729   * Run the given action as the user.
1730   * @param <T> the return type of the run method
1731   * @param action the method to execute
1732   * @return the value from the run method
1733   */
1734  @InterfaceAudience.Public
1735  @InterfaceStability.Evolving
1736  public <T> T doAs(PrivilegedAction<T> action) {
1737    logPrivilegedAction(subject, action);
1738    return Subject.doAs(subject, action);
1739  }
1740  
1741  /**
1742   * Run the given action as the user, potentially throwing an exception.
1743   * @param <T> the return type of the run method
1744   * @param action the method to execute
1745   * @return the value from the run method
1746   * @throws IOException if the action throws an IOException
1747   * @throws Error if the action throws an Error
1748   * @throws RuntimeException if the action throws a RuntimeException
1749   * @throws InterruptedException if the action throws an InterruptedException
1750   * @throws UndeclaredThrowableException if the action throws something else
1751   */
1752  @InterfaceAudience.Public
1753  @InterfaceStability.Evolving
1754  public <T> T doAs(PrivilegedExceptionAction<T> action
1755                    ) throws IOException, InterruptedException {
1756    try {
1757      logPrivilegedAction(subject, action);
1758      return Subject.doAs(subject, action);
1759    } catch (PrivilegedActionException pae) {
1760      Throwable cause = pae.getCause();
1761      if (LOG.isDebugEnabled()) {
1762        LOG.debug("PrivilegedActionException as:" + this + " cause:" + cause);
1763      }
1764      if (cause instanceof IOException) {
1765        throw (IOException) cause;
1766      } else if (cause instanceof Error) {
1767        throw (Error) cause;
1768      } else if (cause instanceof RuntimeException) {
1769        throw (RuntimeException) cause;
1770      } else if (cause instanceof InterruptedException) {
1771        throw (InterruptedException) cause;
1772      } else {
1773        throw new UndeclaredThrowableException(cause);
1774      }
1775    }
1776  }
1777
1778  private void logPrivilegedAction(Subject subject, Object action) {
1779    if (LOG.isDebugEnabled()) {
1780      // would be nice if action included a descriptive toString()
1781      String where = new Throwable().getStackTrace()[2].toString();
1782      LOG.debug("PrivilegedAction as:"+this+" from:"+where);
1783    }
1784  }
1785
1786  private void print() throws IOException {
1787    System.out.println("User: " + getUserName());
1788    System.out.print("Group Ids: ");
1789    System.out.println();
1790    String[] groups = getGroupNames();
1791    System.out.print("Groups: ");
1792    for(int i=0; i < groups.length; i++) {
1793      System.out.print(groups[i] + " ");
1794    }
1795    System.out.println();    
1796  }
1797
1798  /**
1799   * A test method to print out the current user's UGI.
1800   * @param args if there are two arguments, read the user from the keytab
1801   * and print it out.
1802   * @throws Exception
1803   */
1804  public static void main(String [] args) throws Exception {
1805  System.out.println("Getting UGI for current user");
1806    UserGroupInformation ugi = getCurrentUser();
1807    ugi.print();
1808    System.out.println("UGI: " + ugi);
1809    System.out.println("Auth method " + ugi.user.getAuthenticationMethod());
1810    System.out.println("Keytab " + ugi.isKeytab);
1811    System.out.println("============================================================");
1812    
1813    if (args.length == 2) {
1814      System.out.println("Getting UGI from keytab....");
1815      loginUserFromKeytab(args[0], args[1]);
1816      getCurrentUser().print();
1817      System.out.println("Keytab: " + ugi);
1818      System.out.println("Auth method " + loginUser.user.getAuthenticationMethod());
1819      System.out.println("Keytab " + loginUser.isKeytab);
1820    }
1821  }
1822
1823}