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   * remove the login method that is followed by a space from the username
781   * e.g. "jack (auth:SIMPLE)" -> "jack"
782   *
783   * @param userName
784   * @return userName without login method
785   */
786  public static String trimLoginMethod(String userName) {
787    int spaceIndex = userName.indexOf(' ');
788    if (spaceIndex >= 0) {
789      userName = userName.substring(0, spaceIndex);
790    }
791    return userName;
792  }
793
794  /**
795   * Log in a user using the given subject
796   * @parma subject the subject to use when logging in a user, or null to 
797   * create a new subject.
798   * @throws IOException if login fails
799   */
800  @InterfaceAudience.Public
801  @InterfaceStability.Evolving
802  public synchronized 
803  static void loginUserFromSubject(Subject subject) throws IOException {
804    ensureInitialized();
805    try {
806      if (subject == null) {
807        subject = new Subject();
808      }
809      LoginContext login =
810          newLoginContext(authenticationMethod.getLoginAppName(), 
811                          subject, new HadoopConfiguration());
812      login.login();
813      UserGroupInformation realUser = new UserGroupInformation(subject);
814      realUser.setLogin(login);
815      realUser.setAuthenticationMethod(authenticationMethod);
816      realUser = new UserGroupInformation(login.getSubject());
817      // If the HADOOP_PROXY_USER environment variable or property
818      // is specified, create a proxy user as the logged in user.
819      String proxyUser = System.getenv(HADOOP_PROXY_USER);
820      if (proxyUser == null) {
821        proxyUser = System.getProperty(HADOOP_PROXY_USER);
822      }
823      loginUser = proxyUser == null ? realUser : createProxyUser(proxyUser, realUser);
824
825      String fileLocation = System.getenv(HADOOP_TOKEN_FILE_LOCATION);
826      if (fileLocation != null) {
827        // Load the token storage file and put all of the tokens into the
828        // user. Don't use the FileSystem API for reading since it has a lock
829        // cycle (HADOOP-9212).
830        Credentials cred = Credentials.readTokenStorageFile(
831            new File(fileLocation), conf);
832        loginUser.addCredentials(cred);
833      }
834      loginUser.spawnAutoRenewalThreadForUserCreds();
835    } catch (LoginException le) {
836      LOG.debug("failure to login", le);
837      throw new IOException("failure to login", le);
838    }
839    if (LOG.isDebugEnabled()) {
840      LOG.debug("UGI loginUser:"+loginUser);
841    } 
842  }
843
844  @InterfaceAudience.Private
845  @InterfaceStability.Unstable
846  @VisibleForTesting
847  public synchronized static void setLoginUser(UserGroupInformation ugi) {
848    // if this is to become stable, should probably logout the currently
849    // logged in ugi if it's different
850    loginUser = ugi;
851  }
852  
853  /**
854   * Is this user logged in from a keytab file?
855   * @return true if the credentials are from a keytab file.
856   */
857  public boolean isFromKeytab() {
858    return isKeytab;
859  }
860  
861  /**
862   * Get the Kerberos TGT
863   * @return the user's TGT or null if none was found
864   */
865  private synchronized KerberosTicket getTGT() {
866    Set<KerberosTicket> tickets = subject
867        .getPrivateCredentials(KerberosTicket.class);
868    for (KerberosTicket ticket : tickets) {
869      if (SecurityUtil.isOriginalTGT(ticket)) {
870        if (LOG.isDebugEnabled()) {
871          LOG.debug("Found tgt " + ticket);
872        }
873        return ticket;
874      }
875    }
876    return null;
877  }
878  
879  private long getRefreshTime(KerberosTicket tgt) {
880    long start = tgt.getStartTime().getTime();
881    long end = tgt.getEndTime().getTime();
882    return start + (long) ((end - start) * TICKET_RENEW_WINDOW);
883  }
884
885  /**Spawn a thread to do periodic renewals of kerberos credentials*/
886  private void spawnAutoRenewalThreadForUserCreds() {
887    if (isSecurityEnabled()) {
888      //spawn thread only if we have kerb credentials
889      if (user.getAuthenticationMethod() == AuthenticationMethod.KERBEROS &&
890          !isKeytab) {
891        Thread t = new Thread(new Runnable() {
892          
893          @Override
894          public void run() {
895            String cmd = conf.get("hadoop.kerberos.kinit.command",
896                                  "kinit");
897            KerberosTicket tgt = getTGT();
898            if (tgt == null) {
899              return;
900            }
901            long nextRefresh = getRefreshTime(tgt);
902            while (true) {
903              try {
904                long now = Time.now();
905                if(LOG.isDebugEnabled()) {
906                  LOG.debug("Current time is " + now);
907                  LOG.debug("Next refresh is " + nextRefresh);
908                }
909                if (now < nextRefresh) {
910                  Thread.sleep(nextRefresh - now);
911                }
912                Shell.execCommand(cmd, "-R");
913                if(LOG.isDebugEnabled()) {
914                  LOG.debug("renewed ticket");
915                }
916                reloginFromTicketCache();
917                tgt = getTGT();
918                if (tgt == null) {
919                  LOG.warn("No TGT after renewal. Aborting renew thread for " +
920                           getUserName());
921                  return;
922                }
923                nextRefresh = Math.max(getRefreshTime(tgt),
924                                       now + MIN_TIME_BEFORE_RELOGIN);
925              } catch (InterruptedException ie) {
926                LOG.warn("Terminating renewal thread");
927                return;
928              } catch (IOException ie) {
929                LOG.warn("Exception encountered while running the" +
930                    " renewal command. Aborting renew thread. " + ie);
931                return;
932              }
933            }
934          }
935        });
936        t.setDaemon(true);
937        t.setName("TGT Renewer for " + getUserName());
938        t.start();
939      }
940    }
941  }
942  /**
943   * Log a user in from a keytab file. Loads a user identity from a keytab
944   * file and logs them in. They become the currently logged-in user.
945   * @param user the principal name to load from the keytab
946   * @param path the path to the keytab file
947   * @throws IOException if the keytab file can't be read
948   */
949  @InterfaceAudience.Public
950  @InterfaceStability.Evolving
951  public synchronized
952  static void loginUserFromKeytab(String user,
953                                  String path
954                                  ) throws IOException {
955    if (!isSecurityEnabled())
956      return;
957
958    keytabFile = path;
959    keytabPrincipal = user;
960    Subject subject = new Subject();
961    LoginContext login; 
962    long start = 0;
963    try {
964      login = newLoginContext(HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME,
965            subject, new HadoopConfiguration());
966      start = Time.now();
967      login.login();
968      metrics.loginSuccess.add(Time.now() - start);
969      loginUser = new UserGroupInformation(subject);
970      loginUser.setLogin(login);
971      loginUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS);
972    } catch (LoginException le) {
973      if (start > 0) {
974        metrics.loginFailure.add(Time.now() - start);
975      }
976      throw new IOException("Login failure for " + user + " from keytab " + 
977                            path+ ": " + le, le);
978    }
979    LOG.info("Login successful for user " + keytabPrincipal
980        + " using keytab file " + keytabFile);
981  }
982  
983  /**
984   * Re-login a user from keytab if TGT is expired or is close to expiry.
985   * 
986   * @throws IOException
987   */
988  public synchronized void checkTGTAndReloginFromKeytab() throws IOException {
989    if (!isSecurityEnabled()
990        || user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS
991        || !isKeytab)
992      return;
993    KerberosTicket tgt = getTGT();
994    if (tgt != null && !shouldRenewImmediatelyForTests &&
995        Time.now() < getRefreshTime(tgt)) {
996      return;
997    }
998    reloginFromKeytab();
999  }
1000
1001  /**
1002   * Re-Login a user in from a keytab file. Loads a user identity from a keytab
1003   * file and logs them in. They become the currently logged-in user. This
1004   * method assumes that {@link #loginUserFromKeytab(String, String)} had 
1005   * happened already.
1006   * The Subject field of this UserGroupInformation object is updated to have
1007   * the new credentials.
1008   * @throws IOException on a failure
1009   */
1010  @InterfaceAudience.Public
1011  @InterfaceStability.Evolving
1012  public synchronized void reloginFromKeytab()
1013  throws IOException {
1014    if (!isSecurityEnabled() ||
1015         user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS ||
1016         !isKeytab)
1017      return;
1018    
1019    long now = Time.now();
1020    if (!shouldRenewImmediatelyForTests && !hasSufficientTimeElapsed(now)) {
1021      return;
1022    }
1023
1024    KerberosTicket tgt = getTGT();
1025    //Return if TGT is valid and is not going to expire soon.
1026    if (tgt != null && !shouldRenewImmediatelyForTests &&
1027        now < getRefreshTime(tgt)) {
1028      return;
1029    }
1030    
1031    LoginContext login = getLogin();
1032    if (login == null || keytabFile == null) {
1033      throw new IOException("loginUserFromKeyTab must be done first");
1034    }
1035    
1036    long start = 0;
1037    // register most recent relogin attempt
1038    user.setLastLogin(now);
1039    try {
1040      if (LOG.isDebugEnabled()) {
1041        LOG.debug("Initiating logout for " + getUserName());
1042      }
1043      synchronized (UserGroupInformation.class) {
1044        // clear up the kerberos state. But the tokens are not cleared! As per
1045        // the Java kerberos login module code, only the kerberos credentials
1046        // are cleared
1047        login.logout();
1048        // login and also update the subject field of this instance to
1049        // have the new credentials (pass it to the LoginContext constructor)
1050        login = newLoginContext(
1051            HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, getSubject(),
1052            new HadoopConfiguration());
1053        if (LOG.isDebugEnabled()) {
1054          LOG.debug("Initiating re-login for " + keytabPrincipal);
1055        }
1056        start = Time.now();
1057        login.login();
1058        metrics.loginSuccess.add(Time.now() - start);
1059        setLogin(login);
1060      }
1061    } catch (LoginException le) {
1062      if (start > 0) {
1063        metrics.loginFailure.add(Time.now() - start);
1064      }
1065      throw new IOException("Login failure for " + keytabPrincipal + 
1066          " from keytab " + keytabFile, le);
1067    } 
1068  }
1069
1070  /**
1071   * Re-Login a user in from the ticket cache.  This
1072   * method assumes that login had happened already.
1073   * The Subject field of this UserGroupInformation object is updated to have
1074   * the new credentials.
1075   * @throws IOException on a failure
1076   */
1077  @InterfaceAudience.Public
1078  @InterfaceStability.Evolving
1079  public synchronized void reloginFromTicketCache()
1080  throws IOException {
1081    if (!isSecurityEnabled() || 
1082        user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS ||
1083        !isKrbTkt)
1084      return;
1085    LoginContext login = getLogin();
1086    if (login == null) {
1087      throw new IOException("login must be done first");
1088    }
1089    long now = Time.now();
1090    if (!hasSufficientTimeElapsed(now)) {
1091      return;
1092    }
1093    // register most recent relogin attempt
1094    user.setLastLogin(now);
1095    try {
1096      if (LOG.isDebugEnabled()) {
1097        LOG.debug("Initiating logout for " + getUserName());
1098      }
1099      //clear up the kerberos state. But the tokens are not cleared! As per 
1100      //the Java kerberos login module code, only the kerberos credentials
1101      //are cleared
1102      login.logout();
1103      //login and also update the subject field of this instance to 
1104      //have the new credentials (pass it to the LoginContext constructor)
1105      login = 
1106        newLoginContext(HadoopConfiguration.USER_KERBEROS_CONFIG_NAME, 
1107            getSubject(), new HadoopConfiguration());
1108      if (LOG.isDebugEnabled()) {
1109        LOG.debug("Initiating re-login for " + getUserName());
1110      }
1111      login.login();
1112      setLogin(login);
1113    } catch (LoginException le) {
1114      throw new IOException("Login failure for " + getUserName(), le);
1115    } 
1116  }
1117
1118
1119  /**
1120   * Log a user in from a keytab file. Loads a user identity from a keytab
1121   * file and login them in. This new user does not affect the currently
1122   * logged-in user.
1123   * @param user the principal name to load from the keytab
1124   * @param path the path to the keytab file
1125   * @throws IOException if the keytab file can't be read
1126   */
1127  public synchronized
1128  static UserGroupInformation loginUserFromKeytabAndReturnUGI(String user,
1129                                  String path
1130                                  ) throws IOException {
1131    if (!isSecurityEnabled())
1132      return UserGroupInformation.getCurrentUser();
1133    String oldKeytabFile = null;
1134    String oldKeytabPrincipal = null;
1135
1136    long start = 0;
1137    try {
1138      oldKeytabFile = keytabFile;
1139      oldKeytabPrincipal = keytabPrincipal;
1140      keytabFile = path;
1141      keytabPrincipal = user;
1142      Subject subject = new Subject();
1143      
1144      LoginContext login = newLoginContext(
1145          HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, subject,
1146          new HadoopConfiguration());
1147       
1148      start = Time.now();
1149      login.login();
1150      metrics.loginSuccess.add(Time.now() - start);
1151      UserGroupInformation newLoginUser = new UserGroupInformation(subject);
1152      newLoginUser.setLogin(login);
1153      newLoginUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS);
1154      
1155      return newLoginUser;
1156    } catch (LoginException le) {
1157      if (start > 0) {
1158        metrics.loginFailure.add(Time.now() - start);
1159      }
1160      throw new IOException("Login failure for " + user + " from keytab " + 
1161                            path, le);
1162    } finally {
1163      if(oldKeytabFile != null) keytabFile = oldKeytabFile;
1164      if(oldKeytabPrincipal != null) keytabPrincipal = oldKeytabPrincipal;
1165    }
1166  }
1167
1168  private boolean hasSufficientTimeElapsed(long now) {
1169    if (now - user.getLastLogin() < MIN_TIME_BEFORE_RELOGIN ) {
1170      LOG.warn("Not attempting to re-login since the last re-login was " +
1171          "attempted less than " + (MIN_TIME_BEFORE_RELOGIN/1000) + " seconds"+
1172          " before.");
1173      return false;
1174    }
1175    return true;
1176  }
1177  
1178  /**
1179   * Did the login happen via keytab
1180   * @return true or false
1181   */
1182  @InterfaceAudience.Public
1183  @InterfaceStability.Evolving
1184  public synchronized static boolean isLoginKeytabBased() throws IOException {
1185    return getLoginUser().isKeytab;
1186  }
1187
1188  /**
1189   * Did the login happen via ticket cache
1190   * @return true or false
1191   */
1192  public static boolean isLoginTicketBased()  throws IOException {
1193    return getLoginUser().isKrbTkt;
1194  }
1195
1196  /**
1197   * Create a user from a login name. It is intended to be used for remote
1198   * users in RPC, since it won't have any credentials.
1199   * @param user the full user principal name, must not be empty or null
1200   * @return the UserGroupInformation for the remote user.
1201   */
1202  @InterfaceAudience.Public
1203  @InterfaceStability.Evolving
1204  public static UserGroupInformation createRemoteUser(String user) {
1205    return createRemoteUser(user, AuthMethod.SIMPLE);
1206  }
1207  
1208  /**
1209   * Create a user from a login name. It is intended to be used for remote
1210   * users in RPC, since it won't have any credentials.
1211   * @param user the full user principal name, must not be empty or null
1212   * @return the UserGroupInformation for the remote user.
1213   */
1214  @InterfaceAudience.Public
1215  @InterfaceStability.Evolving
1216  public static UserGroupInformation createRemoteUser(String user, AuthMethod authMethod) {
1217    if (user == null || user.isEmpty()) {
1218      throw new IllegalArgumentException("Null user");
1219    }
1220    Subject subject = new Subject();
1221    subject.getPrincipals().add(new User(user));
1222    UserGroupInformation result = new UserGroupInformation(subject);
1223    result.setAuthenticationMethod(authMethod);
1224    return result;
1225  }
1226
1227  /**
1228   * existing types of authentications' methods
1229   */
1230  @InterfaceAudience.Public
1231  @InterfaceStability.Evolving
1232  public static enum AuthenticationMethod {
1233    // currently we support only one auth per method, but eventually a 
1234    // subtype is needed to differentiate, ex. if digest is token or ldap
1235    SIMPLE(AuthMethod.SIMPLE,
1236        HadoopConfiguration.SIMPLE_CONFIG_NAME),
1237    KERBEROS(AuthMethod.KERBEROS,
1238        HadoopConfiguration.USER_KERBEROS_CONFIG_NAME),
1239    TOKEN(AuthMethod.TOKEN),
1240    CERTIFICATE(null),
1241    KERBEROS_SSL(null),
1242    PROXY(null);
1243    
1244    private final AuthMethod authMethod;
1245    private final String loginAppName;
1246    
1247    private AuthenticationMethod(AuthMethod authMethod) {
1248      this(authMethod, null);
1249    }
1250    private AuthenticationMethod(AuthMethod authMethod, String loginAppName) {
1251      this.authMethod = authMethod;
1252      this.loginAppName = loginAppName;
1253    }
1254    
1255    public AuthMethod getAuthMethod() {
1256      return authMethod;
1257    }
1258    
1259    String getLoginAppName() {
1260      if (loginAppName == null) {
1261        throw new UnsupportedOperationException(
1262            this + " login authentication is not supported");
1263      }
1264      return loginAppName;
1265    }
1266    
1267    public static AuthenticationMethod valueOf(AuthMethod authMethod) {
1268      for (AuthenticationMethod value : values()) {
1269        if (value.getAuthMethod() == authMethod) {
1270          return value;
1271        }
1272      }
1273      throw new IllegalArgumentException(
1274          "no authentication method for " + authMethod);
1275    }
1276  };
1277
1278  /**
1279   * Create a proxy user using username of the effective user and the ugi of the
1280   * real user.
1281   * @param user
1282   * @param realUser
1283   * @return proxyUser ugi
1284   */
1285  @InterfaceAudience.Public
1286  @InterfaceStability.Evolving
1287  public static UserGroupInformation createProxyUser(String user,
1288      UserGroupInformation realUser) {
1289    if (user == null || user.isEmpty()) {
1290      throw new IllegalArgumentException("Null user");
1291    }
1292    if (realUser == null) {
1293      throw new IllegalArgumentException("Null real user");
1294    }
1295    Subject subject = new Subject();
1296    Set<Principal> principals = subject.getPrincipals();
1297    principals.add(new User(user));
1298    principals.add(new RealUser(realUser));
1299    UserGroupInformation result =new UserGroupInformation(subject);
1300    result.setAuthenticationMethod(AuthenticationMethod.PROXY);
1301    return result;
1302  }
1303
1304  /**
1305   * get RealUser (vs. EffectiveUser)
1306   * @return realUser running over proxy user
1307   */
1308  @InterfaceAudience.Public
1309  @InterfaceStability.Evolving
1310  public UserGroupInformation getRealUser() {
1311    for (RealUser p: subject.getPrincipals(RealUser.class)) {
1312      return p.getRealUser();
1313    }
1314    return null;
1315  }
1316
1317
1318  
1319  /**
1320   * This class is used for storing the groups for testing. It stores a local
1321   * map that has the translation of usernames to groups.
1322   */
1323  private static class TestingGroups extends Groups {
1324    private final Map<String, List<String>> userToGroupsMapping = 
1325      new HashMap<String,List<String>>();
1326    private Groups underlyingImplementation;
1327    
1328    private TestingGroups(Groups underlyingImplementation) {
1329      super(new org.apache.hadoop.conf.Configuration());
1330      this.underlyingImplementation = underlyingImplementation;
1331    }
1332    
1333    @Override
1334    public List<String> getGroups(String user) throws IOException {
1335      List<String> result = userToGroupsMapping.get(user);
1336      
1337      if (result == null) {
1338        result = underlyingImplementation.getGroups(user);
1339      }
1340
1341      return result;
1342    }
1343
1344    private void setUserGroups(String user, String[] groups) {
1345      userToGroupsMapping.put(user, Arrays.asList(groups));
1346    }
1347  }
1348
1349  /**
1350   * Create a UGI for testing HDFS and MapReduce
1351   * @param user the full user principal name
1352   * @param userGroups the names of the groups that the user belongs to
1353   * @return a fake user for running unit tests
1354   */
1355  @InterfaceAudience.Public
1356  @InterfaceStability.Evolving
1357  public static UserGroupInformation createUserForTesting(String user, 
1358                                                          String[] userGroups) {
1359    ensureInitialized();
1360    UserGroupInformation ugi = createRemoteUser(user);
1361    // make sure that the testing object is setup
1362    if (!(groups instanceof TestingGroups)) {
1363      groups = new TestingGroups(groups);
1364    }
1365    // add the user groups
1366    ((TestingGroups) groups).setUserGroups(ugi.getShortUserName(), userGroups);
1367    return ugi;
1368  }
1369
1370
1371  /**
1372   * Create a proxy user UGI for testing HDFS and MapReduce
1373   * 
1374   * @param user
1375   *          the full user principal name for effective user
1376   * @param realUser
1377   *          UGI of the real user
1378   * @param userGroups
1379   *          the names of the groups that the user belongs to
1380   * @return a fake user for running unit tests
1381   */
1382  public static UserGroupInformation createProxyUserForTesting(String user,
1383      UserGroupInformation realUser, String[] userGroups) {
1384    ensureInitialized();
1385    UserGroupInformation ugi = createProxyUser(user, realUser);
1386    // make sure that the testing object is setup
1387    if (!(groups instanceof TestingGroups)) {
1388      groups = new TestingGroups(groups);
1389    }
1390    // add the user groups
1391    ((TestingGroups) groups).setUserGroups(ugi.getShortUserName(), userGroups);
1392    return ugi;
1393  }
1394  
1395  /**
1396   * Get the user's login name.
1397   * @return the user's name up to the first '/' or '@'.
1398   */
1399  public String getShortUserName() {
1400    for (User p: subject.getPrincipals(User.class)) {
1401      return p.getShortName();
1402    }
1403    return null;
1404  }
1405
1406  public String getPrimaryGroupName() throws IOException {
1407    String[] groups = getGroupNames();
1408    if (groups.length == 0) {
1409      throw new IOException("There is no primary group for UGI " + this);
1410    }
1411    return groups[0];
1412  }
1413
1414  /**
1415   * Get the user's full principal name.
1416   * @return the user's full principal name.
1417   */
1418  @InterfaceAudience.Public
1419  @InterfaceStability.Evolving
1420  public String getUserName() {
1421    return user.getName();
1422  }
1423
1424  /**
1425   * Add a TokenIdentifier to this UGI. The TokenIdentifier has typically been
1426   * authenticated by the RPC layer as belonging to the user represented by this
1427   * UGI.
1428   * 
1429   * @param tokenId
1430   *          tokenIdentifier to be added
1431   * @return true on successful add of new tokenIdentifier
1432   */
1433  public synchronized boolean addTokenIdentifier(TokenIdentifier tokenId) {
1434    return subject.getPublicCredentials().add(tokenId);
1435  }
1436
1437  /**
1438   * Get the set of TokenIdentifiers belonging to this UGI
1439   * 
1440   * @return the set of TokenIdentifiers belonging to this UGI
1441   */
1442  public synchronized Set<TokenIdentifier> getTokenIdentifiers() {
1443    return subject.getPublicCredentials(TokenIdentifier.class);
1444  }
1445  
1446  /**
1447   * Add a token to this UGI
1448   * 
1449   * @param token Token to be added
1450   * @return true on successful add of new token
1451   */
1452  public boolean addToken(Token<? extends TokenIdentifier> token) {
1453    return (token != null) ? addToken(token.getService(), token) : false;
1454  }
1455
1456  /**
1457   * Add a named token to this UGI
1458   * 
1459   * @param alias Name of the token
1460   * @param token Token to be added
1461   * @return true on successful add of new token
1462   */
1463  public boolean addToken(Text alias, Token<? extends TokenIdentifier> token) {
1464    synchronized (subject) {
1465      getCredentialsInternal().addToken(alias, token);
1466      return true;
1467    }
1468  }
1469  
1470  /**
1471   * Obtain the collection of tokens associated with this user.
1472   * 
1473   * @return an unmodifiable collection of tokens associated with user
1474   */
1475  public Collection<Token<? extends TokenIdentifier>> getTokens() {
1476    synchronized (subject) {
1477      return Collections.unmodifiableCollection(
1478          new ArrayList<Token<?>>(getCredentialsInternal().getAllTokens()));
1479    }
1480  }
1481
1482  /**
1483   * Obtain the tokens in credentials form associated with this user.
1484   * 
1485   * @return Credentials of tokens associated with this user
1486   */
1487  public Credentials getCredentials() {
1488    synchronized (subject) {
1489      Credentials creds = new Credentials(getCredentialsInternal());
1490      Iterator<Token<?>> iter = creds.getAllTokens().iterator();
1491      while (iter.hasNext()) {
1492        if (iter.next() instanceof Token.PrivateToken) {
1493          iter.remove();
1494        }
1495      }
1496      return creds;
1497    }
1498  }
1499  
1500  /**
1501   * Add the given Credentials to this user.
1502   * @param credentials of tokens and secrets
1503   */
1504  public void addCredentials(Credentials credentials) {
1505    synchronized (subject) {
1506      getCredentialsInternal().addAll(credentials);
1507    }
1508  }
1509
1510  private synchronized Credentials getCredentialsInternal() {
1511    final Credentials credentials;
1512    final Set<Credentials> credentialsSet =
1513      subject.getPrivateCredentials(Credentials.class);
1514    if (!credentialsSet.isEmpty()){
1515      credentials = credentialsSet.iterator().next();
1516    } else {
1517      credentials = new Credentials();
1518      subject.getPrivateCredentials().add(credentials);
1519    }
1520    return credentials;
1521  }
1522
1523  /**
1524   * Get the group names for this user.
1525   * @return the list of users with the primary group first. If the command
1526   *    fails, it returns an empty list.
1527   */
1528  public synchronized String[] getGroupNames() {
1529    ensureInitialized();
1530    try {
1531      Set<String> result = new LinkedHashSet<String>
1532        (groups.getGroups(getShortUserName()));
1533      return result.toArray(new String[result.size()]);
1534    } catch (IOException ie) {
1535      LOG.warn("No groups available for user " + getShortUserName());
1536      return new String[0];
1537    }
1538  }
1539  
1540  /**
1541   * Return the username.
1542   */
1543  @Override
1544  public String toString() {
1545    StringBuilder sb = new StringBuilder(getUserName());
1546    sb.append(" (auth:"+getAuthenticationMethod()+")");
1547    if (getRealUser() != null) {
1548      sb.append(" via ").append(getRealUser().toString());
1549    }
1550    return sb.toString();
1551  }
1552
1553  /**
1554   * Sets the authentication method in the subject
1555   * 
1556   * @param authMethod
1557   */
1558  public synchronized 
1559  void setAuthenticationMethod(AuthenticationMethod authMethod) {
1560    user.setAuthenticationMethod(authMethod);
1561  }
1562
1563  /**
1564   * Sets the authentication method in the subject
1565   * 
1566   * @param authMethod
1567   */
1568  public void setAuthenticationMethod(AuthMethod authMethod) {
1569    user.setAuthenticationMethod(AuthenticationMethod.valueOf(authMethod));
1570  }
1571
1572  /**
1573   * Get the authentication method from the subject
1574   * 
1575   * @return AuthenticationMethod in the subject, null if not present.
1576   */
1577  public synchronized AuthenticationMethod getAuthenticationMethod() {
1578    return user.getAuthenticationMethod();
1579  }
1580
1581  /**
1582   * Get the authentication method from the real user's subject.  If there
1583   * is no real user, return the given user's authentication method.
1584   * 
1585   * @return AuthenticationMethod in the subject, null if not present.
1586   */
1587  public synchronized AuthenticationMethod getRealAuthenticationMethod() {
1588    UserGroupInformation ugi = getRealUser();
1589    if (ugi == null) {
1590      ugi = this;
1591    }
1592    return ugi.getAuthenticationMethod();
1593  }
1594
1595  /**
1596   * Returns the authentication method of a ugi. If the authentication method is
1597   * PROXY, returns the authentication method of the real user.
1598   * 
1599   * @param ugi
1600   * @return AuthenticationMethod
1601   */
1602  public static AuthenticationMethod getRealAuthenticationMethod(
1603      UserGroupInformation ugi) {
1604    AuthenticationMethod authMethod = ugi.getAuthenticationMethod();
1605    if (authMethod == AuthenticationMethod.PROXY) {
1606      authMethod = ugi.getRealUser().getAuthenticationMethod();
1607    }
1608    return authMethod;
1609  }
1610
1611  /**
1612   * Compare the subjects to see if they are equal to each other.
1613   */
1614  @Override
1615  public boolean equals(Object o) {
1616    if (o == this) {
1617      return true;
1618    } else if (o == null || getClass() != o.getClass()) {
1619      return false;
1620    } else {
1621      return subject == ((UserGroupInformation) o).subject;
1622    }
1623  }
1624
1625  /**
1626   * Return the hash of the subject.
1627   */
1628  @Override
1629  public int hashCode() {
1630    return System.identityHashCode(subject);
1631  }
1632
1633  /**
1634   * Get the underlying subject from this ugi.
1635   * @return the subject that represents this user.
1636   */
1637  protected Subject getSubject() {
1638    return subject;
1639  }
1640
1641  /**
1642   * Run the given action as the user.
1643   * @param <T> the return type of the run method
1644   * @param action the method to execute
1645   * @return the value from the run method
1646   */
1647  @InterfaceAudience.Public
1648  @InterfaceStability.Evolving
1649  public <T> T doAs(PrivilegedAction<T> action) {
1650    logPrivilegedAction(subject, action);
1651    return Subject.doAs(subject, action);
1652  }
1653  
1654  /**
1655   * Run the given action as the user, potentially throwing an exception.
1656   * @param <T> the return type of the run method
1657   * @param action the method to execute
1658   * @return the value from the run method
1659   * @throws IOException if the action throws an IOException
1660   * @throws Error if the action throws an Error
1661   * @throws RuntimeException if the action throws a RuntimeException
1662   * @throws InterruptedException if the action throws an InterruptedException
1663   * @throws UndeclaredThrowableException if the action throws something else
1664   */
1665  @InterfaceAudience.Public
1666  @InterfaceStability.Evolving
1667  public <T> T doAs(PrivilegedExceptionAction<T> action
1668                    ) throws IOException, InterruptedException {
1669    try {
1670      logPrivilegedAction(subject, action);
1671      return Subject.doAs(subject, action);
1672    } catch (PrivilegedActionException pae) {
1673      Throwable cause = pae.getCause();
1674      LOG.warn("PriviledgedActionException as:"+this+" cause:"+cause);
1675      if (cause instanceof IOException) {
1676        throw (IOException) cause;
1677      } else if (cause instanceof Error) {
1678        throw (Error) cause;
1679      } else if (cause instanceof RuntimeException) {
1680        throw (RuntimeException) cause;
1681      } else if (cause instanceof InterruptedException) {
1682        throw (InterruptedException) cause;
1683      } else {
1684        throw new UndeclaredThrowableException(cause);
1685      }
1686    }
1687  }
1688
1689  private void logPrivilegedAction(Subject subject, Object action) {
1690    if (LOG.isDebugEnabled()) {
1691      // would be nice if action included a descriptive toString()
1692      String where = new Throwable().getStackTrace()[2].toString();
1693      LOG.debug("PrivilegedAction as:"+this+" from:"+where);
1694    }
1695  }
1696
1697  private void print() throws IOException {
1698    System.out.println("User: " + getUserName());
1699    System.out.print("Group Ids: ");
1700    System.out.println();
1701    String[] groups = getGroupNames();
1702    System.out.print("Groups: ");
1703    for(int i=0; i < groups.length; i++) {
1704      System.out.print(groups[i] + " ");
1705    }
1706    System.out.println();    
1707  }
1708
1709  /**
1710   * A test method to print out the current user's UGI.
1711   * @param args if there are two arguments, read the user from the keytab
1712   * and print it out.
1713   * @throws Exception
1714   */
1715  public static void main(String [] args) throws Exception {
1716  System.out.println("Getting UGI for current user");
1717    UserGroupInformation ugi = getCurrentUser();
1718    ugi.print();
1719    System.out.println("UGI: " + ugi);
1720    System.out.println("Auth method " + ugi.user.getAuthenticationMethod());
1721    System.out.println("Keytab " + ugi.isKeytab);
1722    System.out.println("============================================================");
1723    
1724    if (args.length == 2) {
1725      System.out.println("Getting UGI from keytab....");
1726      loginUserFromKeytab(args[0], args[1]);
1727      getCurrentUser().print();
1728      System.out.println("Keytab: " + ugi);
1729      System.out.println("Auth method " + loginUser.user.getAuthenticationMethod());
1730      System.out.println("Keytab " + loginUser.isKeytab);
1731    }
1732  }
1733
1734}