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