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

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

Introduction

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

Prototype

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

Source Link

Document

Return the current user, including any doAs in the current stack.

Usage

From source file:org.apache.ambari.view.filebrowser.HdfsApi.java

License:Apache License

private UserGroupInformation getProxyUser() throws IOException {
    UserGroupInformation proxyuser;/*from  ww w .j a  v a2 s . c o m*/
    if (params.containsKey("proxyuser")) {
        proxyuser = UserGroupInformation.createRemoteUser(params.get("proxyuser"));
    } else {
        proxyuser = UserGroupInformation.getCurrentUser();
    }

    proxyuser.setAuthenticationMethod(getAuthenticationMethod());
    return proxyuser;
}

From source file:org.apache.ambari.view.filebrowser.HdfsService.java

License:Apache License

/**
 * Get proxyuser username to use in HDFS
 * @param context View Context instance/*from ww w . ja  v a2s.  com*/
 * @return user name
 */
public String getRealUsername(ViewContext context) {
    String username = context.getProperties().get("webhdfs.proxyuser");
    if (username == null || username.isEmpty())
        try {
            username = UserGroupInformation.getCurrentUser().getShortUserName();
        } catch (IOException e) {
            throw new ServiceFormattedException("HdfsApi connection failed. Can't get current user", e);
        }
    return username;
}

From source file:org.apache.ambari.view.utils.hdfs.HdfsApi.java

License:Apache License

private UserGroupInformation getProxyUser() throws IOException {
    UserGroupInformation proxyuser;/*from ww w  .j av  a 2 s  .  com*/
    if (authParams.containsKey("proxyuser")) {
        proxyuser = UserGroupInformation.createRemoteUser(authParams.get("proxyuser"));
    } else {
        proxyuser = UserGroupInformation.getCurrentUser();
    }

    proxyuser.setAuthenticationMethod(getAuthenticationMethod());
    return proxyuser;
}

From source file:org.apache.apex.engine.security.TokenRenewer.java

License:Apache License

public TokenRenewer(Context context, boolean renewRMToken, Configuration conf, String destinationFile)
        throws IOException {
    this.renewRMToken = renewRMToken;
    this.destinationFile = destinationFile;
    this.conf = conf;

    if (renewRMToken) {
        tokenLifeTime = (long) (context.getValue(LogicalPlan.TOKEN_REFRESH_ANTICIPATORY_FACTOR)
                * Math.min(context.getValue(LogicalPlan.HDFS_TOKEN_LIFE_TIME),
                        context.getValue(LogicalPlan.RM_TOKEN_LIFE_TIME)));
        tokenRenewalInterval = (long) (context.getValue(LogicalPlan.TOKEN_REFRESH_ANTICIPATORY_FACTOR)
                * Math.min(context.getValue(LogicalPlan.HDFS_TOKEN_RENEWAL_INTERVAL),
                        context.getValue(LogicalPlan.RM_TOKEN_RENEWAL_INTERVAL)));
        rmAddress = conf.getSocketAddr(YarnConfiguration.RM_ADDRESS, YarnConfiguration.DEFAULT_RM_ADDRESS,
                YarnConfiguration.DEFAULT_RM_PORT);
    } else {//www .  j av a 2  s  .  c o m
        tokenLifeTime = (long) (context.getValue(LogicalPlan.TOKEN_REFRESH_ANTICIPATORY_FACTOR)
                * context.getValue(LogicalPlan.HDFS_TOKEN_LIFE_TIME));
        tokenRenewalInterval = (long) (context.getValue(LogicalPlan.TOKEN_REFRESH_ANTICIPATORY_FACTOR)
                * context.getValue(LogicalPlan.HDFS_TOKEN_RENEWAL_INTERVAL));
    }

    principal = context.getValue(LogicalPlan.PRINCIPAL);
    hdfsKeyTabFile = context.getValue(LogicalPlan.KEY_TAB_FILE);

    expiryTime = System.currentTimeMillis() + tokenLifeTime;
    renewTime = expiryTime;

    logger.debug("token life time {} renewal interval {}", tokenLifeTime, tokenRenewalInterval);
    logger.debug("Token expiry time {} renew time {}", expiryTime, renewTime);

    credentials = UserGroupInformation.getCurrentUser().getCredentials();
    // Check credentials are proper at RM
    if (renewRMToken) {
        renewTokens(false, true);
    }
}

From source file:org.apache.apex.engine.security.TokenRenewer.java

License:Apache License

private long renewTokens(final boolean refresh, boolean checkOnly) throws IOException {
    logger.info("{}", checkOnly ? "Checking renewal" : (refresh ? "Refreshing tokens" : "Renewing tokens"));
    long expiryTime = System.currentTimeMillis() + (refresh ? tokenLifeTime : tokenRenewalInterval);

    final String tokenRenewer = UserGroupInformation.getCurrentUser().getUserName();
    logger.debug("Token renewer {}", tokenRenewer);

    File keyTabFile = null;/*  w  w  w.  j a  va2s . com*/
    try (FileSystem fs = FileSystem.newInstance(conf)) {
        String destinationDir = FileUtils.getTempDirectoryPath();
        keyTabFile = FSUtil.copyToLocalFileSystem(fs, destinationDir, destinationFile, hdfsKeyTabFile, conf);

        if (principal == null) {
            //principal = UserGroupInformation.getCurrentUser().getUserName();
            principal = UserGroupInformation.getLoginUser().getUserName();
        }
        logger.debug("Principal {}", principal);
        UserGroupInformation ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(principal,
                keyTabFile.getAbsolutePath());
        if (!checkOnly) {
            try {
                UserGroupInformation currUGI = UserGroupInformation.createProxyUser(tokenRenewer, ugi);
                currUGI.doAs(new PrivilegedExceptionAction<Object>() {
                    @Override
                    public Object run() throws Exception {

                        if (refresh) {
                            Credentials creds = new Credentials();
                            try (FileSystem fs1 = FileSystem.newInstance(conf)) {
                                logger.info("Refreshing fs tokens");
                                fs1.addDelegationTokens(tokenRenewer, creds);
                                logger.info("Refreshed tokens");
                            }
                            if (renewRMToken) {
                                try (YarnClient yarnClient = StramClientUtils.createYarnClient(conf)) {
                                    logger.info("Refreshing rm tokens");
                                    new StramClientUtils.ClientRMHelper(yarnClient, conf)
                                            .addRMDelegationToken(tokenRenewer, creds);
                                    logger.info("Refreshed tokens");
                                }
                            }
                            credentials.addAll(creds);
                        } else {
                            Collection<Token<? extends TokenIdentifier>> tokens = credentials.getAllTokens();
                            for (Token<? extends TokenIdentifier> token : tokens) {
                                logger.debug("Token {}", token);
                                if (token.getKind().equals(HDFS_TOKEN_KIND) || (renewRMToken
                                        && token.getKind().equals(RMDelegationTokenIdentifier.KIND_NAME))) {
                                    logger.info("Renewing token {}", token.getKind());
                                    token.renew(conf);
                                    logger.info("Renewed token");
                                }
                            }
                        }

                        return null;
                    }
                });
                UserGroupInformation.getCurrentUser().addCredentials(credentials);
            } catch (InterruptedException e) {
                logger.error("Error while renewing tokens ", e);
                expiryTime = System.currentTimeMillis();
            } catch (IOException e) {
                logger.error("Error while renewing tokens ", e);
                expiryTime = System.currentTimeMillis();
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("number of tokens: {}", credentials.getAllTokens().size());
            Iterator<Token<?>> iter = credentials.getAllTokens().iterator();
            while (iter.hasNext()) {
                Token<?> token = iter.next();
                logger.debug("updated token: {}", token);
            }
        }
    } finally {
        if (keyTabFile != null) {
            keyTabFile.delete();
        }
    }
    return expiryTime;
}

From source file:org.apache.atlas.AtlasBaseClient.java

License:Apache License

protected static UserGroupInformation getCurrentUGI() throws AtlasException {
    try {/*from   w ww .j ava  2  s. c o  m*/
        return UserGroupInformation.getCurrentUser();
    } catch (IOException e) {
        throw new AtlasException(e);
    }
}

From source file:org.apache.atlas.AtlasClient.java

License:Apache License

private static UserGroupInformation getCurrentUGI() throws AtlasException {
    try {//from  ww w .  ja  v a 2 s  .  co  m
        return UserGroupInformation.getCurrentUser();
    } catch (IOException e) {
        throw new AtlasException(e);
    }
}

From source file:org.apache.atlas.hive.bridge.HiveMetaStoreBridge.java

License:Apache License

public static void main(String[] argv) throws Exception {

    Configuration atlasConf = ApplicationProperties.get();
    String atlasEndpoint = atlasConf.getString(ATLAS_ENDPOINT, DEFAULT_DGI_URL);
    AtlasClient atlasClient;// ww  w .j av a 2 s.  co  m

    if (!AuthenticationUtil.isKerberosAuthicationEnabled()) {
        String[] basicAuthUsernamePassword = AuthenticationUtil.getBasicAuthenticationInput();
        atlasClient = new AtlasClient(new String[] { atlasEndpoint }, basicAuthUsernamePassword);
    } else {
        UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
        atlasClient = new AtlasClient(ugi, ugi.getShortUserName(), atlasEndpoint);
    }

    HiveMetaStoreBridge hiveMetaStoreBridge = new HiveMetaStoreBridge(new HiveConf(), atlasClient);
    hiveMetaStoreBridge.registerHiveDataModel();
    hiveMetaStoreBridge.importHiveMetadata();
}

From source file:org.apache.atlas.hive.hook.HiveHookIT.java

License:Apache License

@Test
public void testCreateExternalTable() throws Exception {
    String tableName = tableName();
    String colName = columnName();

    String pFile = createTestDFSPath("parentPath");
    final String query = String.format("create TEMPORARY EXTERNAL table %s.%s( %s, %s) location '%s'",
            DEFAULT_DB, tableName, colName + " int", "name string", pFile);
    runCommand(query);//from  w  ww .  j  a v a 2 s  .c o  m
    assertTableIsRegistered(DEFAULT_DB, tableName, null, true);

    String processId = assertProcessIsRegistered(query);
    Referenceable processReference = atlasClient.getEntity(processId);
    assertEquals(processReference.get("userName"), UserGroupInformation.getCurrentUser().getShortUserName());

    verifyTimestamps(processReference, "startTime");
    verifyTimestamps(processReference, "endTime");

    validateHDFSPaths(processReference, pFile, INPUTS);
}

From source file:org.apache.atlas.hook.AtlasHook.java

License:Apache License

/**
 * Returns the user. Order of preference:
 * 1. Given userName/*from www .  ja  va2s.c  o m*/
 * 2. ugi.getShortUserName()
 * 3. UserGroupInformation.getCurrentUser().getShortUserName()
 * 4. System.getProperty("user.name")
 */

public static String getUser(String userName, UserGroupInformation ugi) {
    if (StringUtils.isNotEmpty(userName)) {
        return userName;
    }

    if (ugi != null && StringUtils.isNotEmpty(ugi.getShortUserName())) {
        return ugi.getShortUserName();
    }

    try {
        return UserGroupInformation.getCurrentUser().getShortUserName();
    } catch (IOException e) {
        LOG.warn("Failed for UserGroupInformation.getCurrentUser()");
        return System.getProperty("user.name");
    }
}