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.pig.backend.hadoop.HKerberos.java

License:Apache License

public static void tryKerberosKeytabLogin(Configuration conf) {
    // Before we can actually connect we may need to login using the provided credentials.
    if (UserGroupInformation.isSecurityEnabled()) {
        UserGroupInformation loginUser;/* ww  w  .  j av  a2  s .  c  o  m*/
        try {
            loginUser = UserGroupInformation.getLoginUser();
        } catch (IOException e) {
            LOG.error("Unable to start attempt to login using Kerberos keytab: " + e.getMessage());
            return;
        }

        // If we are logged in into Kerberos with a keytab we can skip this to avoid needless logins
        if (!loginUser.hasKerberosCredentials() && !loginUser.isFromKeytab()) {
            String krb5Conf = conf.get("java.security.krb5.conf");
            String krb5Principal = conf.get("hadoop.security.krb5.principal");
            String krb5Keytab = conf.get("hadoop.security.krb5.keytab");

            // Only attempt login if we have all the required settings.
            if (krb5Conf != null && krb5Principal != null && krb5Keytab != null) {
                LOG.info("Trying login using Kerberos Keytab");
                LOG.info("krb5: Conf      = " + krb5Conf);
                LOG.info("krb5: Principal = " + krb5Principal);
                LOG.info("krb5: Keytab    = " + krb5Keytab);
                System.setProperty("java.security.krb5.conf", krb5Conf);
                try {
                    UserGroupInformation.loginUserFromKeytab(krb5Principal, krb5Keytab);
                } catch (IOException e) {
                    LOG.error("Unable to perform keytab based kerberos authentication: " + e.getMessage());
                }
            }
        }
    }
}

From source file:org.apache.ranger.audit.provider.LocalFileLogBuffer.java

License:Apache License

@Override
public void run() {
    UserGroupInformation loginUser = null;

    try {//from  w w w .j  a v  a2s.  co  m
        loginUser = UserGroupInformation.getLoginUser();
    } catch (IOException excp) {
        mLogger.error(
                "DestinationDispatcherThread.run(): failed to get login user details. Audit files will not be sent to HDFS destination",
                excp);
    }

    if (loginUser == null) {
        mLogger.error(
                "DestinationDispatcherThread.run(): failed to get login user. Audit files will not be sent to HDFS destination");

        return;
    }

    loginUser.doAs(new PrivilegedAction<Integer>() {
        @Override
        public Integer run() {
            doRun();

            return 0;
        }
    });
}

From source file:org.apache.ranger.audit.provider.MiscUtil.java

License:Apache License

public static UserGroupInformation createUGIFromSubject(Subject subject) throws IOException {
    logger.info("SUBJECT " + (subject == null ? "not found" : "found"));
    UserGroupInformation ugi = null;/*from   w  w  w  .j  av a 2s . co m*/
    if (subject != null) {
        logger.info("SUBJECT.PRINCIPALS.size()=" + subject.getPrincipals().size());
        Set<Principal> principals = subject.getPrincipals();
        for (Principal principal : principals) {
            logger.info("SUBJECT.PRINCIPAL.NAME=" + principal.getName());
        }
        try {
            // Do not remove the below statement. The default
            // getLoginUser does some initialization which is needed
            // for getUGIFromSubject() to work.
            UserGroupInformation.getLoginUser();
            logger.info("Default UGI before using new Subject:" + UserGroupInformation.getLoginUser());
        } catch (Throwable t) {
            logger.error(t);
        }
        ugi = UserGroupInformation.getUGIFromSubject(subject);
        logger.info("SUBJECT.UGI.NAME=" + ugi.getUserName() + ", ugi=" + ugi);
    } else {
        logger.info("Server username is not available");
    }
    return ugi;
}

From source file:org.apache.ranger.audit.provider.MiscUtil.java

License:Apache License

public static void authWithConfig(String appName, Configuration config) {
    try {//from   ww w.  jav  a2  s .  c om
        if (config != null) {
            logger.info(
                    "Getting AppConfigrationEntry[] for appName=" + appName + ", config=" + config.toString());
            AppConfigurationEntry[] entries = config.getAppConfigurationEntry(appName);
            if (entries != null) {
                logger.info("Got " + entries.length + "  AppConfigrationEntry elements for appName=" + appName);
                for (AppConfigurationEntry appEntry : entries) {
                    logger.info("APP_ENTRY:getLoginModuleName()=" + appEntry.getLoginModuleName());
                    logger.info("APP_ENTRY:getControlFlag()=" + appEntry.getControlFlag());
                    logger.info("APP_ENTRY.getOptions()=" + appEntry.getOptions());
                }
            }

            LoginContext loginContext = new LoginContext(appName, new Subject(), null, config);
            logger.info("Login in for appName=" + appName);
            loginContext.login();
            logger.info("Principals after login=" + loginContext.getSubject().getPrincipals());
            logger.info("UserGroupInformation.loginUserFromSubject(): appName=" + appName + ", principals="
                    + loginContext.getSubject().getPrincipals());

            UserGroupInformation ugi = MiscUtil.createUGIFromSubject(loginContext.getSubject());
            if (ugi != null) {
                MiscUtil.setUGILoginUser(ugi, loginContext.getSubject());
            }

            // UserGroupInformation.loginUserFromSubject(loginContext
            // .getSubject());
            logger.info("POST UserGroupInformation.loginUserFromSubject UGI="
                    + UserGroupInformation.getLoginUser());
        }
    } catch (Throwable t) {
        logger.fatal("Error logging as appName=" + appName + ", config=" + config.toString() + ", error="
                + t.getMessage());
    }
}

From source file:org.apache.ranger.audit.provider.MiscUtil.java

License:Apache License

public static UserGroupInformation getLoginUser() throws IOException {
    return UserGroupInformation.getLoginUser();
}

From source file:org.apache.ranger.authorization.solr.authorizer.RangerSolrAuthorizer.java

License:Apache License

private void authToJAASFile() {
    try {//from  w  w  w . ja  va  2 s.c  o m
        // logger.info("DEFAULT UGI=" +
        // UserGroupInformation.getLoginUser());

        Configuration config = Configuration.getConfiguration();
        MiscUtil.authWithConfig(solrAppName, config);
        logger.info("POST AUTH UGI=" + UserGroupInformation.getLoginUser());
    } catch (Throwable t) {
        logger.error("Error authenticating for appName=" + solrAppName, t);
    }
}

From source file:org.apache.ranger.tagsync.process.TagSynchronizer.java

License:Apache License

private static boolean initializeKerberosIdentity(Properties props) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> TagSynchronizer.initializeKerberosIdentity()");
    }// w  w w  .  j  a va 2  s. c  o  m

    boolean ret = false;

    String authenticationType = TagSyncConfig.getAuthenticationType(props);
    String principal = TagSyncConfig.getKerberosPrincipal(props);
    String keytab = TagSyncConfig.getKerberosKeytab(props);
    String nameRules = TagSyncConfig.getNameRules(props);

    if (LOG.isDebugEnabled()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("authenticationType=" + authenticationType);
            LOG.debug("principal=" + principal);
            LOG.debug("keytab" + keytab);
            LOG.debug("nameRules=" + nameRules);
        }
    }
    final boolean isKerberized = !StringUtils.isEmpty(authenticationType)
            && authenticationType.trim().equalsIgnoreCase(AUTH_TYPE_KERBEROS)
            && SecureClientLogin.isKerberosCredentialExists(principal, keytab);

    if (isKerberized) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Trying to get kerberos identitiy");
        }
        Subject subject = null;
        try {
            subject = SecureClientLogin.loginUserFromKeytab(principal, keytab, nameRules);
        } catch (IOException exception) {
            LOG.error("Could not get Subject from principal:[" + principal + "], keytab:[" + keytab
                    + "], nameRules:[" + nameRules + "]", exception);
        }

        UserGroupInformation kerberosIdentity;

        if (subject != null) {
            try {
                UserGroupInformation.loginUserFromSubject(subject);
                kerberosIdentity = UserGroupInformation.getLoginUser();
                if (kerberosIdentity != null) {
                    props.put(TagSyncConfig.TAGSYNC_KERBEROS_IDENTITY, kerberosIdentity.getUserName());
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Got UGI, user:[" + kerberosIdentity.getUserName() + "]");
                    }
                    ret = true;
                } else {
                    LOG.error("KerberosIdentity is null!");
                }
            } catch (IOException exception) {
                LOG.error("Failed to get UGI from Subject:[" + subject + "]", exception);
            }
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Not configured for Kerberos Authentication");
        }
        props.remove(TagSyncConfig.TAGSYNC_KERBEROS_IDENTITY);

        ret = true;
    }

    if (!ret) {
        props.remove(TagSyncConfig.TAGSYNC_KERBEROS_IDENTITY);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== TagSynchronizer.initializeKerberosIdentity() : " + ret);
    }

    return ret;
}

From source file:org.apache.sentry.cli.tools.PermissionsMigrationToolCommon.java

License:Apache License

private void migrateSentryServiceConfig() throws Exception {
    Configuration conf = getSentryConf();
    String component = getComponent(conf);
    String serviceName = getServiceName(conf);
    GenericPrivilegeConverter converter = new GenericPrivilegeConverter(component, serviceName, false);

    // instantiate a client for sentry service.  This sets the ugi, so must
    // be done before getting the ugi below.
    try (SentryGenericServiceClient client = SentryGenericServiceClientFactory.create(getSentryConf())) {
        UserGroupInformation ugi = UserGroupInformation.getLoginUser();
        String requestorName = ugi.getShortUserName();

        for (TSentryRole r : client.listAllRoles(requestorName, component)) {
            for (TSentryPrivilege p : client.listAllPrivilegesByRoleName(requestorName, r.getRoleName(),
                    component, serviceName)) {

                String privilegeStr = converter.toString(p);
                Collection<String> privileges = Collections.singleton(privilegeStr);
                Collection<String> migrated = transformPrivileges(privileges);
                if (!migrated.isEmpty()) {
                    LOGGER.info("{} For role {} migrating privileges from {} to {}", getDryRunMessage(),
                            r.getRoleName(), privileges, migrated);

                    /*//  w w w.j ava  2  s.  co m
                     * Note that it is not possible to provide transactional (all-or-nothing) behavior for these configuration
                     * changes since the Sentry client/server protocol does not support. e.g. under certain failure conditions
                     * like crash of Sentry server or network disconnect between client/server, it is possible that the migration
                     * can not complete but can also not be rolled back. Hence this migration tool relies on the fact that privilege
                     * grant/revoke operations are idempotent and hence re-execution of the migration tool will fix any inconsistency
                     * due to such failures.
                     **/
                    boolean originalPermPresent = false;
                    for (String perm : migrated) {
                        if (perm.equalsIgnoreCase(privilegeStr)) {
                            originalPermPresent = true;
                            continue;
                        }
                        TSentryPrivilege x = converter.fromString(perm);
                        LOGGER.info("{} GRANT permission {}", getDryRunMessage(), perm);
                        if (!dryRun) {
                            client.grantPrivilege(requestorName, r.getRoleName(), component, x);
                        }
                    }

                    // Revoke old permission (only if not part of migrated permissions)
                    if (!originalPermPresent) {
                        LOGGER.info("{} REVOKE permission {}", getDryRunMessage(), privilegeStr);
                        if (!dryRun) {
                            client.revokePrivilege(requestorName, r.getRoleName(), component, p);
                        }
                    }
                }
            }
        }
    }
}

From source file:org.apache.sentry.cli.tools.SentryConfigToolIndexer.java

License:Apache License

/**
 * Processes the necessary command based on the arguments parsed earlier.
 * @throws Exception/*www  .  ja v  a2s  .c  o  m*/
 */
public void run() throws Exception {
    String component = HBASE_INDEXER;
    Configuration conf = getSentryConf();

    String service = conf.get(ApiConstants.ClientConfig.SERVICE_NAME, getServiceName());

    if (service == null) {
        throw new IllegalArgumentException(
                "Service was not defined. Please, use -s command option, or sentry.provider.backend.generic.service-name configuration entry.");
    }

    LOGGER.info(String.format("Context: component=%s, service=%s", component, service));
    // instantiate a solr client for sentry service.  This sets the ugi, so must
    // be done before getting the ugi below.
    try (SentryGenericServiceClient client = SentryGenericServiceClientFactory.create(conf)) {
        UserGroupInformation ugi = UserGroupInformation.getLoginUser();
        String requestorName = ugi.getShortUserName();

        convertINIToSentryServiceCmds(component, service, requestorName, conf, client, getPolicyFile(),
                getValidate(), getImportPolicy(), getCheckCompat());
    }
}

From source file:org.apache.sentry.cli.tools.SentryConfigToolSolr.java

License:Apache License

@Override
public void run() throws Exception {
    String component = "SOLR";
    Configuration conf = getSentryConf();

    String service = conf.get(SOLR_SERVICE_NAME, "service1");
    // instantiate a solr client for sentry service.  This sets the ugi, so must
    // be done before getting the ugi below.
    try (SentryGenericServiceClient client = SentryGenericServiceClientFactory.create(conf)) {
        UserGroupInformation ugi = UserGroupInformation.getLoginUser();
        String requestorName = ugi.getShortUserName();

        convertINIToSentryServiceCmds(component, service, requestorName, conf, client, getPolicyFile(),
                getValidate(), getImportPolicy(), getCheckCompat());
    }//from   w ww  .  j  a  v a2  s.  co  m
}