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