Example usage for org.apache.hadoop.security UserGroupInformation getLoginUser

List of usage examples for org.apache.hadoop.security UserGroupInformation getLoginUser

Introduction

In this page you can find the example usage for org.apache.hadoop.security UserGroupInformation getLoginUser.

Prototype

@InterfaceAudience.Public
@InterfaceStability.Evolving
public static UserGroupInformation getLoginUser() throws IOException 

Source Link

Document

Get the currently logged in user.

Usage

From source file:org.apache.hoya.tools.HoyaUtils.java

License:Apache License

/**
 * Turn on security. This is setup to only run once.
 * @param conf configuration to build up security
 * @return true if security was initialized in this call
 * @throws IOException IO/Net problems//from  www  .  j  ava  2s. com
 * @throws BadConfigException the configuration and system state are inconsistent
 */
public static boolean initProcessSecurity(Configuration conf) throws IOException, BadConfigException {

    if (processSecurityAlreadyInitialized.compareAndSet(true, true)) {
        //security is already inited
        return false;
    }

    log.info("JVM initialized into secure mode with kerberos realm {}", HoyaUtils.getKerberosRealm());
    //this gets UGI to reset its previous world view (i.e simple auth)
    //security
    log.debug("java.security.krb5.realm={}", System.getProperty("java.security.krb5.realm", ""));
    log.debug("java.security.krb5.kdc={}", System.getProperty("java.security.krb5.kdc", ""));
    SecurityUtil.setAuthenticationMethod(UserGroupInformation.AuthenticationMethod.KERBEROS, conf);
    UserGroupInformation.setConfiguration(conf);
    UserGroupInformation authUser = UserGroupInformation.getCurrentUser();
    log.debug("Authenticating as " + authUser.toString());
    log.debug("Login user is {}", UserGroupInformation.getLoginUser());
    if (!UserGroupInformation.isSecurityEnabled()) {
        throw new BadConfigException("Although secure mode is enabled,"
                + "the application has already set up its user as an insecure entity %s", authUser);
    }
    if (authUser.getAuthenticationMethod() == UserGroupInformation.AuthenticationMethod.SIMPLE) {
        throw new BadConfigException("Auth User is not Kerberized %s"
                + " -security has already been set up with the wrong authentication method", authUser);

    }

    HoyaUtils.verifyPrincipalSet(conf, YarnConfiguration.RM_PRINCIPAL);
    HoyaUtils.verifyPrincipalSet(conf, DFSConfigKeys.DFS_NAMENODE_USER_NAME_KEY);
    return true;
}

From source file:org.apache.hoya.tools.HoyaUtils.java

License:Apache License

/**
 * Force an early login: This catches any auth problems early rather than
 * in RPC operatins/*from  w w  w  . j av a 2 s . c o  m*/
 * @throws IOException if the login fails
 */
public static void forceLogin() throws IOException {
    if (UserGroupInformation.isSecurityEnabled()) {
        if (UserGroupInformation.isLoginKeytabBased()) {
            UserGroupInformation.getLoginUser().reloginFromKeytab();
        } else {
            UserGroupInformation.getLoginUser().reloginFromTicketCache();
        }
    }
}

From source file:org.apache.hoya.yarn.appmaster.HoyaAppMaster.java

License:Apache License

@Override //AbstractService
public synchronized void serviceInit(Configuration conf) throws Exception {

    // Load in the server configuration - if it is actually on the Classpath
    Configuration serverConf = ConfigHelper.loadFromResource(SERVER_RESOURCE);
    ConfigHelper.mergeConfigurations(conf, serverConf, SERVER_RESOURCE);

    AbstractActionArgs action = serviceArgs.getCoreAction();
    HoyaAMCreateAction createAction = (HoyaAMCreateAction) action;
    //sort out the location of the AM
    serviceArgs.applyDefinitions(conf);// w  w w  . j av a2s .com
    serviceArgs.applyFileSystemURL(conf);

    String rmAddress = createAction.getRmAddress();
    if (rmAddress != null) {
        log.debug("Setting rm address from the command line: {}", rmAddress);
        HoyaUtils.setRmSchedulerAddress(conf, rmAddress);
    }
    serviceArgs.applyDefinitions(conf);
    serviceArgs.applyFileSystemURL(conf);
    //init security with our conf
    if (HoyaUtils.isClusterSecure(conf)) {
        log.info("Secure mode with kerberos realm {}", HoyaUtils.getKerberosRealm());
        UserGroupInformation.setConfiguration(conf);
        UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
        log.debug("Authenticating as " + ugi.toString());
        HoyaUtils.verifyPrincipalSet(conf, DFSConfigKeys.DFS_NAMENODE_USER_NAME_KEY);
        // always enforce protocol to be token-based.
        conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION,
                SaslRpcServer.AuthMethod.TOKEN.toString());
    }
    log.info("Login user is {}", UserGroupInformation.getLoginUser());

    //look at settings of Hadoop Auth, to pick up a problem seen once
    checkAndWarnForAuthTokenProblems();

    super.serviceInit(conf);
}

From source file:org.apache.ignite.internal.processors.hadoop.impl.delegate.HadoopKerberosFileSystemFactoryDelegate.java

License:Apache License

/** {@inheritDoc} */
@Override//w w w  .  j  a va 2  s. c o  m
protected FileSystem create(String usrName) throws IOException, InterruptedException {
    UserGroupInformation proxyUgi = UserGroupInformation.createProxyUser(usrName,
            UserGroupInformation.getLoginUser());

    return proxyUgi.doAs(new PrivilegedExceptionAction<FileSystem>() {
        @Override
        public FileSystem run() throws Exception {
            FileSystem fs = FileSystem.get(fullUri, cfg);

            if (workDir != null)
                fs.setWorkingDirectory(workDir);

            return fs;
        }
    });
}

From source file:org.apache.ignite.internal.processors.hadoop.impl.delegate.HadoopKerberosFileSystemFactoryDelegate.java

License:Apache License

/**
 * Re-logins the user if needed./*from   w w w  . jav a  2  s.  c  om*/
 * First, the re-login interval defined in factory is checked. The re-login attempts will be not more
 * frequent than one attempt per {@code reloginInterval}.
 * Second, {@code UserGroupInformation.checkTGTAndReloginFromKeytab()} method invoked that gets existing
 * TGT and checks its validity. If the TGT is expired or is close to expiry, it performs re-login.
 *
 * <p>This operation expected to be called upon each operation with the file system created with the factory.
 * As long as {@link #get(String)} operation is invoked upon each file {@link IgniteHadoopFileSystem}, there
 * is no need to invoke it otherwise specially.
 *
 * @throws IOException If login fails.
 */
private void reloginIfNeeded() throws IOException {
    long now = System.currentTimeMillis();

    if (now >= lastReloginTime + reloginInterval) {
        UserGroupInformation.getLoginUser().checkTGTAndReloginFromKeytab();

        lastReloginTime = now;
    }
}

From source file:org.apache.lens.client.DelegationTokenClientFilter.java

License:Apache License

@Override
public void filter(ClientRequestContext requestContext) throws IOException {
    Optional<Token<? extends TokenIdentifier>> hdfsDelegationToken = UserGroupInformation.getLoginUser()
            .getTokens().stream().filter(tkn -> tkn.getKind().toString().equals(DELEGATION_TKN_KIND))
            .findFirst();//ww w  . j  a  va  2s  .  co  m

    if (hdfsDelegationToken.isPresent()) {
        requestContext.getHeaders().add(HDFS_DELEGATION_TKN_HEADER,
                hdfsDelegationToken.get().encodeToUrlString());
    }
}

From source file:org.apache.oozie.action.hadoop.CredentialsProvider.java

License:Apache License

/**
 * Relogs into Kerberos using the Keytab for the Oozie server user.  This should be called before attempting to get delegation
 * tokens via {@link Credentials} implementations to ensure that the Kerberos credentials are current and won't expire too soon.
 *
 * @throws IOException/*w  w  w .jav  a2s.co m*/
 */
public static void ensureKerberosLogin() throws IOException {
    LOG.debug("About to relogin from keytab");
    UserGroupInformation.getLoginUser().checkTGTAndReloginFromKeytab();
    LOG.debug("Relogin from keytab successful");
}

From source file:org.apache.oozie.action.hadoop.HbaseCredentials.java

License:Apache License

private void obtainToken(final JobConf jobConf, Context context) throws IOException, InterruptedException {
    String user = context.getWorkflow().getUser();
    UserGroupInformation ugi = UserGroupInformation.createProxyUser(user, UserGroupInformation.getLoginUser());
    User u = User.create(ugi);/*from w  w  w .jav  a  2s  . c o  m*/
    // A direct doAs is required here vs. User#obtainAuthTokenForJob(...)
    // See OOZIE-2419 for more
    Token<AuthenticationTokenIdentifier> token = u
            .runAs(new PrivilegedExceptionAction<Token<AuthenticationTokenIdentifier>>() {
                public Token<AuthenticationTokenIdentifier> run() throws Exception {
                    return TokenUtil.obtainToken(jobConf);
                }
            });
    jobConf.getCredentials().addToken(token.getService(), token);
}

From source file:org.apache.oozie.action.hadoop.HCatCredentialHelper.java

License:Apache License

/**
 * This Function will set the HCat token to jobconf
 * @param launcherJobConf - job conf/*from   www . j a v a 2s  .c o  m*/
 * @param principal - principal for HCat server
 * @param server - Serevr URI for HCat server
 * @throws Exception
 */
public void set(JobConf launcherJobConf, String principal, String server) throws Exception {
    try {
        HCatClient client = getHCatClient(launcherJobConf, principal, server);
        XLog.getLog(getClass())
                .debug("HCatCredentialHelper: set: User name for which token will be asked from HCat: "
                        + launcherJobConf.get(USER_NAME));
        String tokenStrForm = client.getDelegationToken(launcherJobConf.get(USER_NAME),
                UserGroupInformation.getLoginUser().getShortUserName());
        Token<DelegationTokenIdentifier> hcatToken = new Token<DelegationTokenIdentifier>();
        hcatToken.decodeFromUrlString(tokenStrForm);
        launcherJobConf.getCredentials().addToken(new Text("HCat Token"), hcatToken);
        XLog.getLog(getClass()).debug("Added the HCat token in job conf");
    } catch (Exception ex) {
        XLog.getLog(getClass()).debug("set Exception" + ex.getMessage());
        throw ex;
    }
}

From source file:org.apache.oozie.action.hadoop.KerberosDoAs.java

License:Open Source License

public Void call() throws Exception {
    final Callable<Void> callable = getCallable();
    UserGroupInformation ugi = UserGroupInformation.createProxyUser(getUser(),
            UserGroupInformation.getLoginUser());
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        public Void run() throws Exception {
            callable.call();/*  w w w. j  a  va  2  s.  c om*/
            return null;
        }
    });
    return null;
}