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