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.KerberosPrincipal;
046import javax.security.auth.kerberos.KerberosTicket;
047import javax.security.auth.kerberos.KeyTab;
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      System.getProperty("os.arch").contains("s390x");
362  private static final boolean aix = System.getProperty("os.name").equals("AIX");
363
364  /* Return the OS login module class name */
365  private static String getOSLoginModuleName() {
366    if (IBM_JAVA) {
367      if (windows) {
368        return is64Bit ? "com.ibm.security.auth.module.Win64LoginModule"
369            : "com.ibm.security.auth.module.NTLoginModule";
370      } else if (aix) {
371        return is64Bit ? "com.ibm.security.auth.module.AIX64LoginModule"
372            : "com.ibm.security.auth.module.AIXLoginModule";
373      } else {
374        return "com.ibm.security.auth.module.LinuxLoginModule";
375      }
376    } else {
377      return windows ? "com.sun.security.auth.module.NTLoginModule"
378        : "com.sun.security.auth.module.UnixLoginModule";
379    }
380  }
381
382  /* Return the OS principal class */
383  @SuppressWarnings("unchecked")
384  private static Class<? extends Principal> getOsPrincipalClass() {
385    ClassLoader cl = ClassLoader.getSystemClassLoader();
386    try {
387      String principalClass = null;
388      if (IBM_JAVA) {
389        if (is64Bit) {
390          principalClass = "com.ibm.security.auth.UsernamePrincipal";
391        } else {
392          if (windows) {
393            principalClass = "com.ibm.security.auth.NTUserPrincipal";
394          } else if (aix) {
395            principalClass = "com.ibm.security.auth.AIXPrincipal";
396          } else {
397            principalClass = "com.ibm.security.auth.LinuxPrincipal";
398          }
399        }
400      } else {
401        principalClass = windows ? "com.sun.security.auth.NTUserPrincipal"
402            : "com.sun.security.auth.UnixPrincipal";
403      }
404      return (Class<? extends Principal>) cl.loadClass(principalClass);
405    } catch (ClassNotFoundException e) {
406      LOG.error("Unable to find JAAS classes:" + e.getMessage());
407    }
408    return null;
409  }
410  static {
411    OS_LOGIN_MODULE_NAME = getOSLoginModuleName();
412    OS_PRINCIPAL_CLASS = getOsPrincipalClass();
413  }
414
415  private static class RealUser implements Principal {
416    private final UserGroupInformation realUser;
417    
418    RealUser(UserGroupInformation realUser) {
419      this.realUser = realUser;
420    }
421    
422    @Override
423    public String getName() {
424      return realUser.getUserName();
425    }
426    
427    public UserGroupInformation getRealUser() {
428      return realUser;
429    }
430    
431    @Override
432    public boolean equals(Object o) {
433      if (this == o) {
434        return true;
435      } else if (o == null || getClass() != o.getClass()) {
436        return false;
437      } else {
438        return realUser.equals(((RealUser) o).realUser);
439      }
440    }
441    
442    @Override
443    public int hashCode() {
444      return realUser.hashCode();
445    }
446    
447    @Override
448    public String toString() {
449      return realUser.toString();
450    }
451  }
452  
453  /**
454   * A JAAS configuration that defines the login modules that we want
455   * to use for login.
456   */
457  private static class HadoopConfiguration 
458      extends javax.security.auth.login.Configuration {
459    private static final String SIMPLE_CONFIG_NAME = "hadoop-simple";
460    private static final String USER_KERBEROS_CONFIG_NAME = 
461      "hadoop-user-kerberos";
462    private static final String KEYTAB_KERBEROS_CONFIG_NAME = 
463      "hadoop-keytab-kerberos";
464
465    private static final Map<String, String> BASIC_JAAS_OPTIONS =
466      new HashMap<String,String>();
467    static {
468      String jaasEnvVar = System.getenv("HADOOP_JAAS_DEBUG");
469      if (jaasEnvVar != null && "true".equalsIgnoreCase(jaasEnvVar)) {
470        BASIC_JAAS_OPTIONS.put("debug", "true");
471      }
472    }
473    
474    private static final AppConfigurationEntry OS_SPECIFIC_LOGIN =
475      new AppConfigurationEntry(OS_LOGIN_MODULE_NAME,
476                                LoginModuleControlFlag.REQUIRED,
477                                BASIC_JAAS_OPTIONS);
478    private static final AppConfigurationEntry HADOOP_LOGIN =
479      new AppConfigurationEntry(HadoopLoginModule.class.getName(),
480                                LoginModuleControlFlag.REQUIRED,
481                                BASIC_JAAS_OPTIONS);
482    private static final Map<String,String> USER_KERBEROS_OPTIONS = 
483      new HashMap<String,String>();
484    static {
485      if (IBM_JAVA) {
486        USER_KERBEROS_OPTIONS.put("useDefaultCcache", "true");
487      } else {
488        USER_KERBEROS_OPTIONS.put("doNotPrompt", "true");
489        USER_KERBEROS_OPTIONS.put("useTicketCache", "true");
490      }
491      String ticketCache = System.getenv("KRB5CCNAME");
492      if (ticketCache != null) {
493        if (IBM_JAVA) {
494          // The first value searched when "useDefaultCcache" is used.
495          System.setProperty("KRB5CCNAME", ticketCache);
496        } else {
497          USER_KERBEROS_OPTIONS.put("ticketCache", ticketCache);
498        }
499      }
500      USER_KERBEROS_OPTIONS.put("renewTGT", "true");
501      USER_KERBEROS_OPTIONS.putAll(BASIC_JAAS_OPTIONS);
502    }
503    private static final AppConfigurationEntry USER_KERBEROS_LOGIN =
504      new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(),
505                                LoginModuleControlFlag.OPTIONAL,
506                                USER_KERBEROS_OPTIONS);
507    private static final Map<String,String> KEYTAB_KERBEROS_OPTIONS = 
508      new HashMap<String,String>();
509    static {
510      if (IBM_JAVA) {
511        KEYTAB_KERBEROS_OPTIONS.put("credsType", "both");
512      } else {
513        KEYTAB_KERBEROS_OPTIONS.put("doNotPrompt", "true");
514        KEYTAB_KERBEROS_OPTIONS.put("useKeyTab", "true");
515        KEYTAB_KERBEROS_OPTIONS.put("storeKey", "true");
516      }
517      KEYTAB_KERBEROS_OPTIONS.put("refreshKrb5Config", "true");
518      KEYTAB_KERBEROS_OPTIONS.putAll(BASIC_JAAS_OPTIONS);      
519    }
520    private static final AppConfigurationEntry KEYTAB_KERBEROS_LOGIN =
521      new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(),
522                                LoginModuleControlFlag.REQUIRED,
523                                KEYTAB_KERBEROS_OPTIONS);
524    
525    private static final AppConfigurationEntry[] SIMPLE_CONF = 
526      new AppConfigurationEntry[]{OS_SPECIFIC_LOGIN, HADOOP_LOGIN};
527    
528    private static final AppConfigurationEntry[] USER_KERBEROS_CONF =
529      new AppConfigurationEntry[]{OS_SPECIFIC_LOGIN, USER_KERBEROS_LOGIN,
530                                  HADOOP_LOGIN};
531
532    private static final AppConfigurationEntry[] KEYTAB_KERBEROS_CONF =
533      new AppConfigurationEntry[]{KEYTAB_KERBEROS_LOGIN, HADOOP_LOGIN};
534
535    @Override
536    public AppConfigurationEntry[] getAppConfigurationEntry(String appName) {
537      if (SIMPLE_CONFIG_NAME.equals(appName)) {
538        return SIMPLE_CONF;
539      } else if (USER_KERBEROS_CONFIG_NAME.equals(appName)) {
540        return USER_KERBEROS_CONF;
541      } else if (KEYTAB_KERBEROS_CONFIG_NAME.equals(appName)) {
542        if (IBM_JAVA) {
543          KEYTAB_KERBEROS_OPTIONS.put("useKeytab",
544              prependFileAuthority(keytabFile));
545        } else {
546          KEYTAB_KERBEROS_OPTIONS.put("keyTab", keytabFile);
547        }
548        KEYTAB_KERBEROS_OPTIONS.put("principal", keytabPrincipal);
549        return KEYTAB_KERBEROS_CONF;
550      }
551      return null;
552    }
553  }
554
555  private static String prependFileAuthority(String keytabPath) {
556    return keytabPath.startsWith("file://") ? keytabPath
557        : "file://" + keytabPath;
558  }
559
560  /**
561   * Represents a javax.security configuration that is created at runtime.
562   */
563  private static class DynamicConfiguration
564      extends javax.security.auth.login.Configuration {
565    private AppConfigurationEntry[] ace;
566    
567    DynamicConfiguration(AppConfigurationEntry[] ace) {
568      this.ace = ace;
569    }
570    
571    @Override
572    public AppConfigurationEntry[] getAppConfigurationEntry(String appName) {
573      return ace;
574    }
575  }
576
577  private static LoginContext
578  newLoginContext(String appName, Subject subject,
579    javax.security.auth.login.Configuration loginConf)
580      throws LoginException {
581    // Temporarily switch the thread's ContextClassLoader to match this
582    // class's classloader, so that we can properly load HadoopLoginModule
583    // from the JAAS libraries.
584    Thread t = Thread.currentThread();
585    ClassLoader oldCCL = t.getContextClassLoader();
586    t.setContextClassLoader(HadoopLoginModule.class.getClassLoader());
587    try {
588      return new LoginContext(appName, subject, null, loginConf);
589    } finally {
590      t.setContextClassLoader(oldCCL);
591    }
592  }
593
594  private LoginContext getLogin() {
595    return user.getLogin();
596  }
597  
598  private void setLogin(LoginContext login) {
599    user.setLogin(login);
600  }
601
602  /**
603   * Create a UserGroupInformation for the given subject.
604   * This does not change the subject or acquire new credentials.
605   * @param subject the user's subject
606   */
607  UserGroupInformation(Subject subject) {
608    this.subject = subject;
609    this.user = subject.getPrincipals(User.class).iterator().next();
610    this.isKeytab = !subject.getPrivateCredentials(KeyTab.class).isEmpty();
611    this.isKrbTkt = !subject.getPrivateCredentials(KerberosTicket.class).isEmpty();
612  }
613  
614  /**
615   * checks if logged in using kerberos
616   * @return true if the subject logged via keytab or has a Kerberos TGT
617   */
618  public boolean hasKerberosCredentials() {
619    return isKeytab || isKrbTkt;
620  }
621
622  /**
623   * Return the current user, including any doAs in the current stack.
624   * @return the current user
625   * @throws IOException if login fails
626   */
627  @InterfaceAudience.Public
628  @InterfaceStability.Evolving
629  public synchronized
630  static UserGroupInformation getCurrentUser() throws IOException {
631    AccessControlContext context = AccessController.getContext();
632    Subject subject = Subject.getSubject(context);
633    if (subject == null || subject.getPrincipals(User.class).isEmpty()) {
634      return getLoginUser();
635    } else {
636      return new UserGroupInformation(subject);
637    }
638  }
639
640  /**
641   * Find the most appropriate UserGroupInformation to use
642   *
643   * @param ticketCachePath    The Kerberos ticket cache path, or NULL
644   *                           if none is specfied
645   * @param user               The user name, or NULL if none is specified.
646   *
647   * @return                   The most appropriate UserGroupInformation
648   */ 
649  public static UserGroupInformation getBestUGI(
650      String ticketCachePath, String user) throws IOException {
651    if (ticketCachePath != null) {
652      return getUGIFromTicketCache(ticketCachePath, user);
653    } else if (user == null) {
654      return getCurrentUser();
655    } else {
656      return createRemoteUser(user);
657    }    
658  }
659
660  /**
661   * Create a UserGroupInformation from a Kerberos ticket cache.
662   * 
663   * @param user                The principal name to load from the ticket
664   *                            cache
665   * @param ticketCachePath     the path to the ticket cache file
666   *
667   * @throws IOException        if the kerberos login fails
668   */
669  @InterfaceAudience.Public
670  @InterfaceStability.Evolving
671  public static UserGroupInformation getUGIFromTicketCache(
672            String ticketCache, String user) throws IOException {
673    if (!isAuthenticationMethodEnabled(AuthenticationMethod.KERBEROS)) {
674      return getBestUGI(null, user);
675    }
676    try {
677      Map<String,String> krbOptions = new HashMap<String,String>();
678      if (IBM_JAVA) {
679        krbOptions.put("useDefaultCcache", "true");
680        // The first value searched when "useDefaultCcache" is used.
681        System.setProperty("KRB5CCNAME", ticketCache);
682      } else {
683        krbOptions.put("doNotPrompt", "true");
684        krbOptions.put("useTicketCache", "true");
685        krbOptions.put("useKeyTab", "false");
686        krbOptions.put("ticketCache", ticketCache);
687      }
688      krbOptions.put("renewTGT", "false");
689      krbOptions.putAll(HadoopConfiguration.BASIC_JAAS_OPTIONS);
690      AppConfigurationEntry ace = new AppConfigurationEntry(
691          KerberosUtil.getKrb5LoginModuleName(),
692          LoginModuleControlFlag.REQUIRED,
693          krbOptions);
694      DynamicConfiguration dynConf =
695          new DynamicConfiguration(new AppConfigurationEntry[]{ ace });
696      LoginContext login = newLoginContext(
697          HadoopConfiguration.USER_KERBEROS_CONFIG_NAME, null, dynConf);
698      login.login();
699
700      Subject loginSubject = login.getSubject();
701      Set<Principal> loginPrincipals = loginSubject.getPrincipals();
702      if (loginPrincipals.isEmpty()) {
703        throw new RuntimeException("No login principals found!");
704      }
705      if (loginPrincipals.size() != 1) {
706        LOG.warn("found more than one principal in the ticket cache file " +
707          ticketCache);
708      }
709      User ugiUser = new User(loginPrincipals.iterator().next().getName(),
710          AuthenticationMethod.KERBEROS, login);
711      loginSubject.getPrincipals().add(ugiUser);
712      UserGroupInformation ugi = new UserGroupInformation(loginSubject);
713      ugi.setLogin(login);
714      ugi.setAuthenticationMethod(AuthenticationMethod.KERBEROS);
715      return ugi;
716    } catch (LoginException le) {
717      throw new IOException("failure to login using ticket cache file " +
718          ticketCache, le);
719    }
720  }
721
722   /**
723   * Create a UserGroupInformation from a Subject with Kerberos principal.
724   *
725   * @param user                The KerberosPrincipal to use in UGI
726   *
727   * @throws IOException        if the kerberos login fails
728   */
729  public static UserGroupInformation getUGIFromSubject(Subject subject)
730      throws IOException {
731    if (subject == null) {
732      throw new IOException("Subject must not be null");
733    }
734
735    if (subject.getPrincipals(KerberosPrincipal.class).isEmpty()) {
736      throw new IOException("Provided Subject must contain a KerberosPrincipal");
737    }
738
739    KerberosPrincipal principal =
740        subject.getPrincipals(KerberosPrincipal.class).iterator().next();
741
742    User ugiUser = new User(principal.getName(),
743        AuthenticationMethod.KERBEROS, null);
744    subject.getPrincipals().add(ugiUser);
745    UserGroupInformation ugi = new UserGroupInformation(subject);
746    ugi.setLogin(null);
747    ugi.setAuthenticationMethod(AuthenticationMethod.KERBEROS);
748    return ugi;
749  }
750
751  /**
752   * Get the currently logged in user.
753   * @return the logged in user
754   * @throws IOException if login fails
755   */
756  @InterfaceAudience.Public
757  @InterfaceStability.Evolving
758  public synchronized 
759  static UserGroupInformation getLoginUser() throws IOException {
760    if (loginUser == null) {
761      loginUserFromSubject(null);
762    }
763    return loginUser;
764  }
765
766  /**
767   * remove the login method that is followed by a space from the username
768   * e.g. "jack (auth:SIMPLE)" -> "jack"
769   *
770   * @param userName
771   * @return userName without login method
772   */
773  public static String trimLoginMethod(String userName) {
774    int spaceIndex = userName.indexOf(' ');
775    if (spaceIndex >= 0) {
776      userName = userName.substring(0, spaceIndex);
777    }
778    return userName;
779  }
780
781  /**
782   * Log in a user using the given subject
783   * @parma subject the subject to use when logging in a user, or null to 
784   * create a new subject.
785   * @throws IOException if login fails
786   */
787  @InterfaceAudience.Public
788  @InterfaceStability.Evolving
789  public synchronized 
790  static void loginUserFromSubject(Subject subject) throws IOException {
791    ensureInitialized();
792    try {
793      if (subject == null) {
794        subject = new Subject();
795      }
796      LoginContext login =
797          newLoginContext(authenticationMethod.getLoginAppName(), 
798                          subject, new HadoopConfiguration());
799      login.login();
800      UserGroupInformation realUser = new UserGroupInformation(subject);
801      realUser.setLogin(login);
802      realUser.setAuthenticationMethod(authenticationMethod);
803      realUser = new UserGroupInformation(login.getSubject());
804      // If the HADOOP_PROXY_USER environment variable or property
805      // is specified, create a proxy user as the logged in user.
806      String proxyUser = System.getenv(HADOOP_PROXY_USER);
807      if (proxyUser == null) {
808        proxyUser = System.getProperty(HADOOP_PROXY_USER);
809      }
810      loginUser = proxyUser == null ? realUser : createProxyUser(proxyUser, realUser);
811
812      String fileLocation = System.getenv(HADOOP_TOKEN_FILE_LOCATION);
813      if (fileLocation != null) {
814        // Load the token storage file and put all of the tokens into the
815        // user. Don't use the FileSystem API for reading since it has a lock
816        // cycle (HADOOP-9212).
817        Credentials cred = Credentials.readTokenStorageFile(
818            new File(fileLocation), conf);
819        loginUser.addCredentials(cred);
820      }
821      loginUser.spawnAutoRenewalThreadForUserCreds();
822    } catch (LoginException le) {
823      LOG.debug("failure to login", le);
824      throw new IOException("failure to login", le);
825    }
826    if (LOG.isDebugEnabled()) {
827      LOG.debug("UGI loginUser:"+loginUser);
828    } 
829  }
830
831  @InterfaceAudience.Private
832  @InterfaceStability.Unstable
833  @VisibleForTesting
834  public synchronized static void setLoginUser(UserGroupInformation ugi) {
835    // if this is to become stable, should probably logout the currently
836    // logged in ugi if it's different
837    loginUser = ugi;
838  }
839  
840  /**
841   * Is this user logged in from a keytab file?
842   * @return true if the credentials are from a keytab file.
843   */
844  public boolean isFromKeytab() {
845    return isKeytab;
846  }
847  
848  /**
849   * Get the Kerberos TGT
850   * @return the user's TGT or null if none was found
851   */
852  private synchronized KerberosTicket getTGT() {
853    Set<KerberosTicket> tickets = subject
854        .getPrivateCredentials(KerberosTicket.class);
855    for (KerberosTicket ticket : tickets) {
856      if (SecurityUtil.isOriginalTGT(ticket)) {
857        return ticket;
858      }
859    }
860    return null;
861  }
862  
863  private long getRefreshTime(KerberosTicket tgt) {
864    long start = tgt.getStartTime().getTime();
865    long end = tgt.getEndTime().getTime();
866    return start + (long) ((end - start) * TICKET_RENEW_WINDOW);
867  }
868
869  /**Spawn a thread to do periodic renewals of kerberos credentials*/
870  private void spawnAutoRenewalThreadForUserCreds() {
871    if (isSecurityEnabled()) {
872      //spawn thread only if we have kerb credentials
873      if (user.getAuthenticationMethod() == AuthenticationMethod.KERBEROS &&
874          !isKeytab) {
875        Thread t = new Thread(new Runnable() {
876          
877          @Override
878          public void run() {
879            String cmd = conf.get("hadoop.kerberos.kinit.command",
880                                  "kinit");
881            KerberosTicket tgt = getTGT();
882            if (tgt == null) {
883              return;
884            }
885            long nextRefresh = getRefreshTime(tgt);
886            while (true) {
887              try {
888                long now = Time.now();
889                if(LOG.isDebugEnabled()) {
890                  LOG.debug("Current time is " + now);
891                  LOG.debug("Next refresh is " + nextRefresh);
892                }
893                if (now < nextRefresh) {
894                  Thread.sleep(nextRefresh - now);
895                }
896                Shell.execCommand(cmd, "-R");
897                if(LOG.isDebugEnabled()) {
898                  LOG.debug("renewed ticket");
899                }
900                reloginFromTicketCache();
901                tgt = getTGT();
902                if (tgt == null) {
903                  LOG.warn("No TGT after renewal. Aborting renew thread for " +
904                           getUserName());
905                  return;
906                }
907                nextRefresh = Math.max(getRefreshTime(tgt),
908                                       now + MIN_TIME_BEFORE_RELOGIN);
909              } catch (InterruptedException ie) {
910                LOG.warn("Terminating renewal thread");
911                return;
912              } catch (IOException ie) {
913                LOG.warn("Exception encountered while running the" +
914                    " renewal command. Aborting renew thread. " + ie);
915                return;
916              }
917            }
918          }
919        });
920        t.setDaemon(true);
921        t.setName("TGT Renewer for " + getUserName());
922        t.start();
923      }
924    }
925  }
926  /**
927   * Log a user in from a keytab file. Loads a user identity from a keytab
928   * file and logs them in. They become the currently logged-in user.
929   * @param user the principal name to load from the keytab
930   * @param path the path to the keytab file
931   * @throws IOException if the keytab file can't be read
932   */
933  @InterfaceAudience.Public
934  @InterfaceStability.Evolving
935  public synchronized
936  static void loginUserFromKeytab(String user,
937                                  String path
938                                  ) throws IOException {
939    if (!isSecurityEnabled())
940      return;
941
942    keytabFile = path;
943    keytabPrincipal = user;
944    Subject subject = new Subject();
945    LoginContext login; 
946    long start = 0;
947    try {
948      login = newLoginContext(HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME,
949            subject, new HadoopConfiguration());
950      start = Time.now();
951      login.login();
952      metrics.loginSuccess.add(Time.now() - start);
953      loginUser = new UserGroupInformation(subject);
954      loginUser.setLogin(login);
955      loginUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS);
956    } catch (LoginException le) {
957      if (start > 0) {
958        metrics.loginFailure.add(Time.now() - start);
959      }
960      throw new IOException("Login failure for " + user + " from keytab " + 
961                            path+ ": " + le, le);
962    }
963    LOG.info("Login successful for user " + keytabPrincipal
964        + " using keytab file " + keytabFile);
965  }
966  
967  /**
968   * Re-login a user from keytab if TGT is expired or is close to expiry.
969   * 
970   * @throws IOException
971   */
972  public synchronized void checkTGTAndReloginFromKeytab() throws IOException {
973    if (!isSecurityEnabled()
974        || user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS
975        || !isKeytab)
976      return;
977    KerberosTicket tgt = getTGT();
978    if (tgt != null && !shouldRenewImmediatelyForTests &&
979        Time.now() < getRefreshTime(tgt)) {
980      return;
981    }
982    reloginFromKeytab();
983  }
984
985  /**
986   * Re-Login a user in from a keytab file. Loads a user identity from a keytab
987   * file and logs them in. They become the currently logged-in user. This
988   * method assumes that {@link #loginUserFromKeytab(String, String)} had 
989   * happened already.
990   * The Subject field of this UserGroupInformation object is updated to have
991   * the new credentials.
992   * @throws IOException on a failure
993   */
994  @InterfaceAudience.Public
995  @InterfaceStability.Evolving
996  public synchronized void reloginFromKeytab()
997  throws IOException {
998    if (!isSecurityEnabled() ||
999         user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS ||
1000         !isKeytab)
1001      return;
1002    
1003    long now = Time.now();
1004    if (!shouldRenewImmediatelyForTests && !hasSufficientTimeElapsed(now)) {
1005      return;
1006    }
1007
1008    KerberosTicket tgt = getTGT();
1009    //Return if TGT is valid and is not going to expire soon.
1010    if (tgt != null && !shouldRenewImmediatelyForTests &&
1011        now < getRefreshTime(tgt)) {
1012      return;
1013    }
1014    
1015    LoginContext login = getLogin();
1016    if (login == null || keytabFile == null) {
1017      throw new IOException("loginUserFromKeyTab must be done first");
1018    }
1019    
1020    long start = 0;
1021    // register most recent relogin attempt
1022    user.setLastLogin(now);
1023    try {
1024      if (LOG.isDebugEnabled()) {
1025        LOG.debug("Initiating logout for " + getUserName());
1026      }
1027      synchronized (UserGroupInformation.class) {
1028        // clear up the kerberos state. But the tokens are not cleared! As per
1029        // the Java kerberos login module code, only the kerberos credentials
1030        // are cleared
1031        login.logout();
1032        // login and also update the subject field of this instance to
1033        // have the new credentials (pass it to the LoginContext constructor)
1034        login = newLoginContext(
1035            HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, getSubject(),
1036            new HadoopConfiguration());
1037        if (LOG.isDebugEnabled()) {
1038          LOG.debug("Initiating re-login for " + keytabPrincipal);
1039        }
1040        start = Time.now();
1041        login.login();
1042        metrics.loginSuccess.add(Time.now() - start);
1043        setLogin(login);
1044      }
1045    } catch (LoginException le) {
1046      if (start > 0) {
1047        metrics.loginFailure.add(Time.now() - start);
1048      }
1049      throw new IOException("Login failure for " + keytabPrincipal + 
1050          " from keytab " + keytabFile, le);
1051    } 
1052  }
1053
1054  /**
1055   * Re-Login a user in from the ticket cache.  This
1056   * method assumes that login had happened already.
1057   * The Subject field of this UserGroupInformation object is updated to have
1058   * the new credentials.
1059   * @throws IOException on a failure
1060   */
1061  @InterfaceAudience.Public
1062  @InterfaceStability.Evolving
1063  public synchronized void reloginFromTicketCache()
1064  throws IOException {
1065    if (!isSecurityEnabled() || 
1066        user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS ||
1067        !isKrbTkt)
1068      return;
1069    LoginContext login = getLogin();
1070    if (login == null) {
1071      throw new IOException("login must be done first");
1072    }
1073    long now = Time.now();
1074    if (!hasSufficientTimeElapsed(now)) {
1075      return;
1076    }
1077    // register most recent relogin attempt
1078    user.setLastLogin(now);
1079    try {
1080      if (LOG.isDebugEnabled()) {
1081        LOG.debug("Initiating logout for " + getUserName());
1082      }
1083      //clear up the kerberos state. But the tokens are not cleared! As per 
1084      //the Java kerberos login module code, only the kerberos credentials
1085      //are cleared
1086      login.logout();
1087      //login and also update the subject field of this instance to 
1088      //have the new credentials (pass it to the LoginContext constructor)
1089      login = 
1090        newLoginContext(HadoopConfiguration.USER_KERBEROS_CONFIG_NAME, 
1091            getSubject(), new HadoopConfiguration());
1092      if (LOG.isDebugEnabled()) {
1093        LOG.debug("Initiating re-login for " + getUserName());
1094      }
1095      login.login();
1096      setLogin(login);
1097    } catch (LoginException le) {
1098      throw new IOException("Login failure for " + getUserName(), le);
1099    } 
1100  }
1101
1102
1103  /**
1104   * Log a user in from a keytab file. Loads a user identity from a keytab
1105   * file and login them in. This new user does not affect the currently
1106   * logged-in user.
1107   * @param user the principal name to load from the keytab
1108   * @param path the path to the keytab file
1109   * @throws IOException if the keytab file can't be read
1110   */
1111  public synchronized
1112  static UserGroupInformation loginUserFromKeytabAndReturnUGI(String user,
1113                                  String path
1114                                  ) throws IOException {
1115    if (!isSecurityEnabled())
1116      return UserGroupInformation.getCurrentUser();
1117    String oldKeytabFile = null;
1118    String oldKeytabPrincipal = null;
1119
1120    long start = 0;
1121    try {
1122      oldKeytabFile = keytabFile;
1123      oldKeytabPrincipal = keytabPrincipal;
1124      keytabFile = path;
1125      keytabPrincipal = user;
1126      Subject subject = new Subject();
1127      
1128      LoginContext login = newLoginContext(
1129          HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, subject,
1130          new HadoopConfiguration());
1131       
1132      start = Time.now();
1133      login.login();
1134      metrics.loginSuccess.add(Time.now() - start);
1135      UserGroupInformation newLoginUser = new UserGroupInformation(subject);
1136      newLoginUser.setLogin(login);
1137      newLoginUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS);
1138      
1139      return newLoginUser;
1140    } catch (LoginException le) {
1141      if (start > 0) {
1142        metrics.loginFailure.add(Time.now() - start);
1143      }
1144      throw new IOException("Login failure for " + user + " from keytab " + 
1145                            path, le);
1146    } finally {
1147      if(oldKeytabFile != null) keytabFile = oldKeytabFile;
1148      if(oldKeytabPrincipal != null) keytabPrincipal = oldKeytabPrincipal;
1149    }
1150  }
1151
1152  private boolean hasSufficientTimeElapsed(long now) {
1153    if (now - user.getLastLogin() < MIN_TIME_BEFORE_RELOGIN ) {
1154      LOG.warn("Not attempting to re-login since the last re-login was " +
1155          "attempted less than " + (MIN_TIME_BEFORE_RELOGIN/1000) + " seconds"+
1156          " before.");
1157      return false;
1158    }
1159    return true;
1160  }
1161  
1162  /**
1163   * Did the login happen via keytab
1164   * @return true or false
1165   */
1166  @InterfaceAudience.Public
1167  @InterfaceStability.Evolving
1168  public synchronized static boolean isLoginKeytabBased() throws IOException {
1169    return getLoginUser().isKeytab;
1170  }
1171
1172  /**
1173   * Did the login happen via ticket cache
1174   * @return true or false
1175   */
1176  public static boolean isLoginTicketBased()  throws IOException {
1177    return getLoginUser().isKrbTkt;
1178  }
1179
1180  /**
1181   * Create a user from a login name. It is intended to be used for remote
1182   * users in RPC, since it won't have any credentials.
1183   * @param user the full user principal name, must not be empty or null
1184   * @return the UserGroupInformation for the remote user.
1185   */
1186  @InterfaceAudience.Public
1187  @InterfaceStability.Evolving
1188  public static UserGroupInformation createRemoteUser(String user) {
1189    return createRemoteUser(user, AuthMethod.SIMPLE);
1190  }
1191  
1192  /**
1193   * Create a user from a login name. It is intended to be used for remote
1194   * users in RPC, since it won't have any credentials.
1195   * @param user the full user principal name, must not be empty or null
1196   * @return the UserGroupInformation for the remote user.
1197   */
1198  @InterfaceAudience.Public
1199  @InterfaceStability.Evolving
1200  public static UserGroupInformation createRemoteUser(String user, AuthMethod authMethod) {
1201    if (user == null || user.isEmpty()) {
1202      throw new IllegalArgumentException("Null user");
1203    }
1204    Subject subject = new Subject();
1205    subject.getPrincipals().add(new User(user));
1206    UserGroupInformation result = new UserGroupInformation(subject);
1207    result.setAuthenticationMethod(authMethod);
1208    return result;
1209  }
1210
1211  /**
1212   * existing types of authentications' methods
1213   */
1214  @InterfaceAudience.Public
1215  @InterfaceStability.Evolving
1216  public static enum AuthenticationMethod {
1217    // currently we support only one auth per method, but eventually a 
1218    // subtype is needed to differentiate, ex. if digest is token or ldap
1219    SIMPLE(AuthMethod.SIMPLE,
1220        HadoopConfiguration.SIMPLE_CONFIG_NAME),
1221    KERBEROS(AuthMethod.KERBEROS,
1222        HadoopConfiguration.USER_KERBEROS_CONFIG_NAME),
1223    TOKEN(AuthMethod.TOKEN),
1224    CERTIFICATE(null),
1225    KERBEROS_SSL(null),
1226    PROXY(null);
1227    
1228    private final AuthMethod authMethod;
1229    private final String loginAppName;
1230    
1231    private AuthenticationMethod(AuthMethod authMethod) {
1232      this(authMethod, null);
1233    }
1234    private AuthenticationMethod(AuthMethod authMethod, String loginAppName) {
1235      this.authMethod = authMethod;
1236      this.loginAppName = loginAppName;
1237    }
1238    
1239    public AuthMethod getAuthMethod() {
1240      return authMethod;
1241    }
1242    
1243    String getLoginAppName() {
1244      if (loginAppName == null) {
1245        throw new UnsupportedOperationException(
1246            this + " login authentication is not supported");
1247      }
1248      return loginAppName;
1249    }
1250    
1251    public static AuthenticationMethod valueOf(AuthMethod authMethod) {
1252      for (AuthenticationMethod value : values()) {
1253        if (value.getAuthMethod() == authMethod) {
1254          return value;
1255        }
1256      }
1257      throw new IllegalArgumentException(
1258          "no authentication method for " + authMethod);
1259    }
1260  };
1261
1262  /**
1263   * Create a proxy user using username of the effective user and the ugi of the
1264   * real user.
1265   * @param user
1266   * @param realUser
1267   * @return proxyUser ugi
1268   */
1269  @InterfaceAudience.Public
1270  @InterfaceStability.Evolving
1271  public static UserGroupInformation createProxyUser(String user,
1272      UserGroupInformation realUser) {
1273    if (user == null || user.isEmpty()) {
1274      throw new IllegalArgumentException("Null user");
1275    }
1276    if (realUser == null) {
1277      throw new IllegalArgumentException("Null real user");
1278    }
1279    Subject subject = new Subject();
1280    Set<Principal> principals = subject.getPrincipals();
1281    principals.add(new User(user));
1282    principals.add(new RealUser(realUser));
1283    UserGroupInformation result =new UserGroupInformation(subject);
1284    result.setAuthenticationMethod(AuthenticationMethod.PROXY);
1285    return result;
1286  }
1287
1288  /**
1289   * get RealUser (vs. EffectiveUser)
1290   * @return realUser running over proxy user
1291   */
1292  @InterfaceAudience.Public
1293  @InterfaceStability.Evolving
1294  public UserGroupInformation getRealUser() {
1295    for (RealUser p: subject.getPrincipals(RealUser.class)) {
1296      return p.getRealUser();
1297    }
1298    return null;
1299  }
1300
1301
1302  
1303  /**
1304   * This class is used for storing the groups for testing. It stores a local
1305   * map that has the translation of usernames to groups.
1306   */
1307  private static class TestingGroups extends Groups {
1308    private final Map<String, List<String>> userToGroupsMapping = 
1309      new HashMap<String,List<String>>();
1310    private Groups underlyingImplementation;
1311    
1312    private TestingGroups(Groups underlyingImplementation) {
1313      super(new org.apache.hadoop.conf.Configuration());
1314      this.underlyingImplementation = underlyingImplementation;
1315    }
1316    
1317    @Override
1318    public List<String> getGroups(String user) throws IOException {
1319      List<String> result = userToGroupsMapping.get(user);
1320      
1321      if (result == null) {
1322        result = underlyingImplementation.getGroups(user);
1323      }
1324
1325      return result;
1326    }
1327
1328    private void setUserGroups(String user, String[] groups) {
1329      userToGroupsMapping.put(user, Arrays.asList(groups));
1330    }
1331  }
1332
1333  /**
1334   * Create a UGI for testing HDFS and MapReduce
1335   * @param user the full user principal name
1336   * @param userGroups the names of the groups that the user belongs to
1337   * @return a fake user for running unit tests
1338   */
1339  @InterfaceAudience.Public
1340  @InterfaceStability.Evolving
1341  public static UserGroupInformation createUserForTesting(String user, 
1342                                                          String[] userGroups) {
1343    ensureInitialized();
1344    UserGroupInformation ugi = createRemoteUser(user);
1345    // make sure that the testing object is setup
1346    if (!(groups instanceof TestingGroups)) {
1347      groups = new TestingGroups(groups);
1348    }
1349    // add the user groups
1350    ((TestingGroups) groups).setUserGroups(ugi.getShortUserName(), userGroups);
1351    return ugi;
1352  }
1353
1354
1355  /**
1356   * Create a proxy user UGI for testing HDFS and MapReduce
1357   * 
1358   * @param user
1359   *          the full user principal name for effective user
1360   * @param realUser
1361   *          UGI of the real user
1362   * @param userGroups
1363   *          the names of the groups that the user belongs to
1364   * @return a fake user for running unit tests
1365   */
1366  public static UserGroupInformation createProxyUserForTesting(String user,
1367      UserGroupInformation realUser, String[] userGroups) {
1368    ensureInitialized();
1369    UserGroupInformation ugi = createProxyUser(user, realUser);
1370    // make sure that the testing object is setup
1371    if (!(groups instanceof TestingGroups)) {
1372      groups = new TestingGroups(groups);
1373    }
1374    // add the user groups
1375    ((TestingGroups) groups).setUserGroups(ugi.getShortUserName(), userGroups);
1376    return ugi;
1377  }
1378  
1379  /**
1380   * Get the user's login name.
1381   * @return the user's name up to the first '/' or '@'.
1382   */
1383  public String getShortUserName() {
1384    for (User p: subject.getPrincipals(User.class)) {
1385      return p.getShortName();
1386    }
1387    return null;
1388  }
1389
1390  public String getPrimaryGroupName() throws IOException {
1391    String[] groups = getGroupNames();
1392    if (groups.length == 0) {
1393      throw new IOException("There is no primary group for UGI " + this);
1394    }
1395    return groups[0];
1396  }
1397
1398  /**
1399   * Get the user's full principal name.
1400   * @return the user's full principal name.
1401   */
1402  @InterfaceAudience.Public
1403  @InterfaceStability.Evolving
1404  public String getUserName() {
1405    return user.getName();
1406  }
1407
1408  /**
1409   * Add a TokenIdentifier to this UGI. The TokenIdentifier has typically been
1410   * authenticated by the RPC layer as belonging to the user represented by this
1411   * UGI.
1412   * 
1413   * @param tokenId
1414   *          tokenIdentifier to be added
1415   * @return true on successful add of new tokenIdentifier
1416   */
1417  public synchronized boolean addTokenIdentifier(TokenIdentifier tokenId) {
1418    return subject.getPublicCredentials().add(tokenId);
1419  }
1420
1421  /**
1422   * Get the set of TokenIdentifiers belonging to this UGI
1423   * 
1424   * @return the set of TokenIdentifiers belonging to this UGI
1425   */
1426  public synchronized Set<TokenIdentifier> getTokenIdentifiers() {
1427    return subject.getPublicCredentials(TokenIdentifier.class);
1428  }
1429  
1430  /**
1431   * Add a token to this UGI
1432   * 
1433   * @param token Token to be added
1434   * @return true on successful add of new token
1435   */
1436  public boolean addToken(Token<? extends TokenIdentifier> token) {
1437    return (token != null) ? addToken(token.getService(), token) : false;
1438  }
1439
1440  /**
1441   * Add a named token to this UGI
1442   * 
1443   * @param alias Name of the token
1444   * @param token Token to be added
1445   * @return true on successful add of new token
1446   */
1447  public boolean addToken(Text alias, Token<? extends TokenIdentifier> token) {
1448    synchronized (subject) {
1449      getCredentialsInternal().addToken(alias, token);
1450      return true;
1451    }
1452  }
1453  
1454  /**
1455   * Obtain the collection of tokens associated with this user.
1456   * 
1457   * @return an unmodifiable collection of tokens associated with user
1458   */
1459  public Collection<Token<? extends TokenIdentifier>> getTokens() {
1460    synchronized (subject) {
1461      return Collections.unmodifiableCollection(
1462          new ArrayList<Token<?>>(getCredentialsInternal().getAllTokens()));
1463    }
1464  }
1465
1466  /**
1467   * Obtain the tokens in credentials form associated with this user.
1468   * 
1469   * @return Credentials of tokens associated with this user
1470   */
1471  public Credentials getCredentials() {
1472    synchronized (subject) {
1473      Credentials creds = new Credentials(getCredentialsInternal());
1474      Iterator<Token<?>> iter = creds.getAllTokens().iterator();
1475      while (iter.hasNext()) {
1476        if (iter.next() instanceof Token.PrivateToken) {
1477          iter.remove();
1478        }
1479      }
1480      return creds;
1481    }
1482  }
1483  
1484  /**
1485   * Add the given Credentials to this user.
1486   * @param credentials of tokens and secrets
1487   */
1488  public void addCredentials(Credentials credentials) {
1489    synchronized (subject) {
1490      getCredentialsInternal().addAll(credentials);
1491    }
1492  }
1493
1494  private synchronized Credentials getCredentialsInternal() {
1495    final Credentials credentials;
1496    final Set<Credentials> credentialsSet =
1497      subject.getPrivateCredentials(Credentials.class);
1498    if (!credentialsSet.isEmpty()){
1499      credentials = credentialsSet.iterator().next();
1500    } else {
1501      credentials = new Credentials();
1502      subject.getPrivateCredentials().add(credentials);
1503    }
1504    return credentials;
1505  }
1506
1507  /**
1508   * Get the group names for this user.
1509   * @return the list of users with the primary group first. If the command
1510   *    fails, it returns an empty list.
1511   */
1512  public synchronized String[] getGroupNames() {
1513    ensureInitialized();
1514    try {
1515      Set<String> result = new LinkedHashSet<String>
1516        (groups.getGroups(getShortUserName()));
1517      return result.toArray(new String[result.size()]);
1518    } catch (IOException ie) {
1519      LOG.warn("No groups available for user " + getShortUserName());
1520      return new String[0];
1521    }
1522  }
1523  
1524  /**
1525   * Return the username.
1526   */
1527  @Override
1528  public String toString() {
1529    StringBuilder sb = new StringBuilder(getUserName());
1530    sb.append(" (auth:"+getAuthenticationMethod()+")");
1531    if (getRealUser() != null) {
1532      sb.append(" via ").append(getRealUser().toString());
1533    }
1534    return sb.toString();
1535  }
1536
1537  /**
1538   * Sets the authentication method in the subject
1539   * 
1540   * @param authMethod
1541   */
1542  public synchronized 
1543  void setAuthenticationMethod(AuthenticationMethod authMethod) {
1544    user.setAuthenticationMethod(authMethod);
1545  }
1546
1547  /**
1548   * Sets the authentication method in the subject
1549   * 
1550   * @param authMethod
1551   */
1552  public void setAuthenticationMethod(AuthMethod authMethod) {
1553    user.setAuthenticationMethod(AuthenticationMethod.valueOf(authMethod));
1554  }
1555
1556  /**
1557   * Get the authentication method from the subject
1558   * 
1559   * @return AuthenticationMethod in the subject, null if not present.
1560   */
1561  public synchronized AuthenticationMethod getAuthenticationMethod() {
1562    return user.getAuthenticationMethod();
1563  }
1564
1565  /**
1566   * Get the authentication method from the real user's subject.  If there
1567   * is no real user, return the given user's authentication method.
1568   * 
1569   * @return AuthenticationMethod in the subject, null if not present.
1570   */
1571  public synchronized AuthenticationMethod getRealAuthenticationMethod() {
1572    UserGroupInformation ugi = getRealUser();
1573    if (ugi == null) {
1574      ugi = this;
1575    }
1576    return ugi.getAuthenticationMethod();
1577  }
1578
1579  /**
1580   * Returns the authentication method of a ugi. If the authentication method is
1581   * PROXY, returns the authentication method of the real user.
1582   * 
1583   * @param ugi
1584   * @return AuthenticationMethod
1585   */
1586  public static AuthenticationMethod getRealAuthenticationMethod(
1587      UserGroupInformation ugi) {
1588    AuthenticationMethod authMethod = ugi.getAuthenticationMethod();
1589    if (authMethod == AuthenticationMethod.PROXY) {
1590      authMethod = ugi.getRealUser().getAuthenticationMethod();
1591    }
1592    return authMethod;
1593  }
1594
1595  /**
1596   * Compare the subjects to see if they are equal to each other.
1597   */
1598  @Override
1599  public boolean equals(Object o) {
1600    if (o == this) {
1601      return true;
1602    } else if (o == null || getClass() != o.getClass()) {
1603      return false;
1604    } else {
1605      return subject == ((UserGroupInformation) o).subject;
1606    }
1607  }
1608
1609  /**
1610   * Return the hash of the subject.
1611   */
1612  @Override
1613  public int hashCode() {
1614    return System.identityHashCode(subject);
1615  }
1616
1617  /**
1618   * Get the underlying subject from this ugi.
1619   * @return the subject that represents this user.
1620   */
1621  protected Subject getSubject() {
1622    return subject;
1623  }
1624
1625  /**
1626   * Run the given action as the user.
1627   * @param <T> the return type of the run method
1628   * @param action the method to execute
1629   * @return the value from the run method
1630   */
1631  @InterfaceAudience.Public
1632  @InterfaceStability.Evolving
1633  public <T> T doAs(PrivilegedAction<T> action) {
1634    logPrivilegedAction(subject, action);
1635    return Subject.doAs(subject, action);
1636  }
1637  
1638  /**
1639   * Run the given action as the user, potentially throwing an exception.
1640   * @param <T> the return type of the run method
1641   * @param action the method to execute
1642   * @return the value from the run method
1643   * @throws IOException if the action throws an IOException
1644   * @throws Error if the action throws an Error
1645   * @throws RuntimeException if the action throws a RuntimeException
1646   * @throws InterruptedException if the action throws an InterruptedException
1647   * @throws UndeclaredThrowableException if the action throws something else
1648   */
1649  @InterfaceAudience.Public
1650  @InterfaceStability.Evolving
1651  public <T> T doAs(PrivilegedExceptionAction<T> action
1652                    ) throws IOException, InterruptedException {
1653    try {
1654      logPrivilegedAction(subject, action);
1655      return Subject.doAs(subject, action);
1656    } catch (PrivilegedActionException pae) {
1657      Throwable cause = pae.getCause();
1658      if (LOG.isDebugEnabled()) {
1659        LOG.debug("PrivilegedActionException as:" + this + " cause:" + cause);
1660      }
1661      if (cause instanceof IOException) {
1662        throw (IOException) cause;
1663      } else if (cause instanceof Error) {
1664        throw (Error) cause;
1665      } else if (cause instanceof RuntimeException) {
1666        throw (RuntimeException) cause;
1667      } else if (cause instanceof InterruptedException) {
1668        throw (InterruptedException) cause;
1669      } else {
1670        throw new UndeclaredThrowableException(cause);
1671      }
1672    }
1673  }
1674
1675  private void logPrivilegedAction(Subject subject, Object action) {
1676    if (LOG.isDebugEnabled()) {
1677      // would be nice if action included a descriptive toString()
1678      String where = new Throwable().getStackTrace()[2].toString();
1679      LOG.debug("PrivilegedAction as:"+this+" from:"+where);
1680    }
1681  }
1682
1683  private void print() throws IOException {
1684    System.out.println("User: " + getUserName());
1685    System.out.print("Group Ids: ");
1686    System.out.println();
1687    String[] groups = getGroupNames();
1688    System.out.print("Groups: ");
1689    for(int i=0; i < groups.length; i++) {
1690      System.out.print(groups[i] + " ");
1691    }
1692    System.out.println();    
1693  }
1694
1695  /**
1696   * A test method to print out the current user's UGI.
1697   * @param args if there are two arguments, read the user from the keytab
1698   * and print it out.
1699   * @throws Exception
1700   */
1701  public static void main(String [] args) throws Exception {
1702  System.out.println("Getting UGI for current user");
1703    UserGroupInformation ugi = getCurrentUser();
1704    ugi.print();
1705    System.out.println("UGI: " + ugi);
1706    System.out.println("Auth method " + ugi.user.getAuthenticationMethod());
1707    System.out.println("Keytab " + ugi.isKeytab);
1708    System.out.println("============================================================");
1709    
1710    if (args.length == 2) {
1711      System.out.println("Getting UGI from keytab....");
1712      loginUserFromKeytab(args[0], args[1]);
1713      getCurrentUser().print();
1714      System.out.println("Keytab: " + ugi);
1715      System.out.println("Auth method " + loginUser.user.getAuthenticationMethod());
1716      System.out.println("Keytab " + loginUser.isKeytab);
1717    }
1718  }
1719
1720}