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