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

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

Introduction

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

Prototype

@InterfaceAudience.Public
@InterfaceStability.Evolving
public static void loginUserFromKeytab(String user, String path) throws IOException 

Source Link

Document

Log a user in from a keytab file.

Usage

From source file:org.apache.apex.malhar.contrib.hbase.HBaseStore.java

License:Apache License

@Override
public void connect() throws IOException {
    if ((principal != null) && (keytabPath != null)) {
        String lprincipal = evaluateProperty(principal);
        String lkeytabPath = evaluateProperty(keytabPath);
        UserGroupInformation.loginUserFromKeytab(lprincipal, lkeytabPath);
        doRelogin = true;/*from   ww  w  .j  a va2s. c o m*/
        loginRenewer = new Thread(new Runnable() {
            @Override
            public void run() {
                logger.debug("Renewer starting");
                try {
                    while (doRelogin) {
                        Thread.sleep(reloginCheckInterval);
                        try {
                            UserGroupInformation.getLoginUser().checkTGTAndReloginFromKeytab();
                        } catch (IOException e) {
                            logger.error("Error trying to relogin from keytab", e);
                        }
                    }
                } catch (InterruptedException e) {
                    if (doRelogin) {
                        logger.warn("Renewer interrupted... stopping");
                    }
                }
                logger.debug("Renewer ending");
            }
        });
        loginRenewer.start();
    }
    configuration = HBaseConfiguration.create();
    // The default configuration is loaded from resources in classpath, the following parameters can be optionally set
    // to override defaults
    if (zookeeperQuorum != null) {
        configuration.set("hbase.zookeeper.quorum", zookeeperQuorum);
    }
    if (zookeeperClientPort != 0) {
        configuration.set("hbase.zookeeper.property.clientPort", "" + zookeeperClientPort);
    }

    // Connect to default table if specified
    if (tableName != null) {
        table = connectTable(tableName);
    }

    CacheLoader<String, HTable> cacheLoader = new CacheLoader<String, HTable>() {
        @Override
        public HTable load(String key) throws Exception {
            return loadTable(key);
        }
    };

    RemovalListener<String, HTable> removalListener = new RemovalListener<String, HTable>() {
        @Override
        public void onRemoval(RemovalNotification<String, HTable> notification) {
            unloadTable(notification.getValue());
        }
    };

    int maxCacheSize = (tableName == null) ? maxOpenTables : (maxOpenTables - 1);

    tableCache = CacheBuilder.<String, HTable>newBuilder().maximumSize(maxCacheSize)
            .removalListener(removalListener).build(cacheLoader);
}

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

License:Apache License

@VisibleForTesting
protected boolean handleSecurity(Configuration atlasProperties) {
    if (AuthenticationUtil.isKerberosAuthenticationEnabled(atlasProperties)) {
        String kafkaPrincipal = atlasProperties.getString("atlas.notification.kafka.service.principal");
        String kafkaKeyTab = atlasProperties.getString("atlas.notification.kafka.keytab.location");
        org.apache.hadoop.conf.Configuration hadoopConf = new org.apache.hadoop.conf.Configuration();
        SecurityUtil.setAuthenticationMethod(UserGroupInformation.AuthenticationMethod.KERBEROS, hadoopConf);
        try {//from  ww  w .  ja  v a 2 s  .  co m
            String serverPrincipal = SecurityUtil.getServerPrincipal(kafkaPrincipal, (String) null);
            UserGroupInformation.setConfiguration(hadoopConf);
            UserGroupInformation.loginUserFromKeytab(serverPrincipal, kafkaKeyTab);
        } catch (IOException e) {
            LOG.warn("Could not login as {} from keytab file {}", kafkaPrincipal, kafkaKeyTab, e);
            return false;
        }
    }
    return true;
}

From source file:org.apache.atlas.web.listeners.LoginProcessor.java

License:Apache License

protected void doServiceLogin(Configuration hadoopConfig,
        org.apache.commons.configuration.Configuration configuration) {
    UserGroupInformation.setConfiguration(hadoopConfig);

    UserGroupInformation ugi = null;/*w  w  w .  java  2s  .com*/
    UserGroupInformation.AuthenticationMethod authenticationMethod = SecurityUtil
            .getAuthenticationMethod(hadoopConfig);
    try {
        if (authenticationMethod == UserGroupInformation.AuthenticationMethod.SIMPLE) {
            UserGroupInformation.loginUserFromSubject(null);
        } else if (authenticationMethod == UserGroupInformation.AuthenticationMethod.KERBEROS) {
            String bindAddress = getHostname(configuration);
            UserGroupInformation.loginUserFromKeytab(
                    getServerPrincipal(configuration.getString(AUTHENTICATION_PRINCIPAL), bindAddress),
                    configuration.getString(AUTHENTICATION_KEYTAB));
        }
        LOG.info("Logged in user {}", UserGroupInformation.getLoginUser());
    } catch (IOException e) {
        throw new IllegalStateException(String.format("Unable to perform %s login.", authenticationMethod), e);
    }
}

From source file:org.apache.drill.exec.server.BootStrapContext.java

License:Apache License

private void login(final DrillConfig config) throws DrillbitStartupException {
    try {//from  ww  w .  j a  va 2s. c  om
        if (config.hasPath(SERVICE_PRINCIPAL)) {
            // providing a service principal => Kerberos mechanism
            final Configuration loginConf = new Configuration();
            loginConf.set(CommonConfigurationKeys.HADOOP_SECURITY_AUTHENTICATION,
                    UserGroupInformation.AuthenticationMethod.KERBEROS.toString());

            // set optional user name mapping
            if (config.hasPath(KERBEROS_NAME_MAPPING)) {
                loginConf.set(CommonConfigurationKeys.HADOOP_SECURITY_AUTH_TO_LOCAL,
                        config.getString(KERBEROS_NAME_MAPPING));
            }

            UserGroupInformation.setConfiguration(loginConf);

            // service principal canonicalization
            final String principal = config.getString(SERVICE_PRINCIPAL);
            final String parts[] = KerberosUtil.splitPrincipalIntoParts(principal);
            if (parts.length != 3) {
                throw new DrillbitStartupException(String.format(
                        "Invalid %s, Drill service principal must be of format: primary/instance@REALM",
                        SERVICE_PRINCIPAL));
            }
            parts[1] = KerberosUtil.canonicalizeInstanceName(parts[1], hostName);

            final String canonicalizedPrincipal = KerberosUtil.getPrincipalFromParts(parts[0], parts[1],
                    parts[2]);
            final String keytab = config.getString(SERVICE_KEYTAB_LOCATION);

            // login to KDC (AS)
            // Note that this call must happen before any call to UserGroupInformation#getLoginUser,
            // but there is no way to enforce the order (this static init. call and parameters from
            // DrillConfig are both required).
            UserGroupInformation.loginUserFromKeytab(canonicalizedPrincipal, keytab);

            logger.info("Process user name: '{}' and logged in successfully as '{}'", processUserName,
                    canonicalizedPrincipal);
        } else {
            UserGroupInformation.getLoginUser(); // init
        }

        // ugi does not support logout
    } catch (final IOException e) {
        throw new DrillbitStartupException("Failed to login.", e);
    }

}

From source file:org.apache.druid.indexer.JobHelper.java

License:Apache License

/**
 * Dose authenticate against a secured hadoop cluster
 * In case of any bug fix make sure to fix the code at HdfsStorageAuthentication#authenticate as well.
 *
 * @param config containing the principal name and keytab path.
 *///from  w w  w  . j ava  2s  . c  o m
public static void authenticate(HadoopDruidIndexerConfig config) {
    String principal = config.HADOOP_KERBEROS_CONFIG.getPrincipal();
    String keytab = config.HADOOP_KERBEROS_CONFIG.getKeytab();
    if (!Strings.isNullOrEmpty(principal) && !Strings.isNullOrEmpty(keytab)) {
        Configuration conf = new Configuration();
        UserGroupInformation.setConfiguration(conf);
        if (UserGroupInformation.isSecurityEnabled()) {
            try {
                if (UserGroupInformation.getCurrentUser().hasKerberosCredentials() == false
                        || !UserGroupInformation.getCurrentUser().getUserName().equals(principal)) {
                    log.info("trying to authenticate user [%s] with keytab [%s]", principal, keytab);
                    UserGroupInformation.loginUserFromKeytab(principal, keytab);
                }
            } catch (IOException e) {
                throw new ISE(e, "Failed to authenticate user principal [%s] with keytab [%s]", principal,
                        keytab);
            }
        }
    }
}

From source file:org.apache.druid.security.kerberos.DruidKerberosUtil.java

License:Apache License

public static void authenticateIfRequired(String internalClientPrincipal, String internalClientKeytab) {
    if (!Strings.isNullOrEmpty(internalClientPrincipal) && !Strings.isNullOrEmpty(internalClientKeytab)) {
        Configuration conf = new Configuration();
        conf.setClassLoader(DruidKerberosModule.class.getClassLoader());
        conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos");
        UserGroupInformation.setConfiguration(conf);
        try {/*  w ww.j  a  v a  2s  .c  o m*/
            //login for the first time.
            if (UserGroupInformation.getCurrentUser().hasKerberosCredentials() == false
                    || !UserGroupInformation.getCurrentUser().getUserName().equals(internalClientPrincipal)) {
                log.info("trying to authenticate user [%s] with keytab [%s]", internalClientPrincipal,
                        internalClientKeytab);
                UserGroupInformation.loginUserFromKeytab(internalClientPrincipal, internalClientKeytab);
                return;
            }
            //try to relogin in case the TGT expired
            if (UserGroupInformation.isLoginKeytabBased()) {
                log.info("Re-Login from key tab [%s] with principal [%s]", internalClientKeytab,
                        internalClientPrincipal);
                UserGroupInformation.getLoginUser().checkTGTAndReloginFromKeytab();
                return;
            } else if (UserGroupInformation.isLoginTicketBased()) {
                log.info("Re-Login from Ticket cache");
                UserGroupInformation.getLoginUser().reloginFromTicketCache();
                return;
            }
        } catch (IOException e) {
            throw new ISE(e, "Failed to authenticate user principal [%s] with keytab [%s]",
                    internalClientPrincipal, internalClientKeytab);
        }
    }
}

From source file:org.apache.eagle.app.utils.HadoopSecurityUtil.java

License:Apache License

public static void login(Configuration kConfig) throws IOException {
    String keytab = kConfig.get(EAGLE_KEYTAB_FILE_KEY);
    String principal = kConfig.get(EAGLE_PRINCIPAL_KEY);
    if (keytab == null || principal == null || keytab.isEmpty() || principal.isEmpty()) {
        return;//from  www.  j a v  a 2  s  . co m
    }

    kConfig.setBoolean("hadoop.security.authorization", true);
    kConfig.set("hadoop.security.authentication", "kerberos");
    UserGroupInformation.setConfiguration(kConfig);
    UserGroupInformation.loginUserFromKeytab(kConfig.get(EAGLE_PRINCIPAL_KEY),
            kConfig.get(EAGLE_KEYTAB_FILE_KEY));
}

From source file:org.apache.eagle.jpm.util.HDFSUtil.java

License:Apache License

public static void login(Configuration kConfig) throws IOException {
    if (kConfig.get("hdfs.kerberos.principal") == null || kConfig.get("hdfs.kerberos.principal").isEmpty()) {
        if (kConfig.get("hadoop.job.ugi") != null) {
            System.setProperty("HADOOP_USER_NAME", kConfig.get("hadoop.job.ugi"));
        }/*from ww w .j a va 2s . c o m*/
        return;
    }
    kConfig.setBoolean("hadoop.security.authorization", true);
    kConfig.set("hadoop.security.authentication", "kerberos");
    UserGroupInformation.setConfiguration(kConfig);
    UserGroupInformation.loginUserFromKeytab(kConfig.get("hdfs.kerberos.principal"),
            kConfig.get("hdfs.keytab.file"));
}

From source file:org.apache.eagle.security.util.HadoopSecurityUtil.java

License:Apache License

public static void login(Configuration kConfig) throws IOException {
    if (kConfig.get(EAGLE_KEYTAB_FILE_KEY) == null || kConfig.get(EAGLE_USER_NAME_KEY) == null)
        return;/*w w w .  j  a v a  2s. co  m*/

    kConfig.setBoolean("hadoop.security.authorization", true);
    kConfig.set("hadoop.security.authentication", "kerberos");
    UserGroupInformation.setConfiguration(kConfig);
    UserGroupInformation.loginUserFromKeytab(kConfig.get(EAGLE_USER_NAME_KEY),
            kConfig.get(EAGLE_KEYTAB_FILE_KEY));
}

From source file:org.apache.falcon.security.AuthenticationInitializationService.java

License:Apache License

protected static void initializeKerberos() throws FalconException {
    try {//from  w  ww. j  a va  2 s.co m
        Properties configuration = StartupProperties.get();
        String principal = configuration.getProperty(KERBEROS_PRINCIPAL);
        Validate.notEmpty(principal, "Missing required configuration property: " + KERBEROS_PRINCIPAL);
        principal = org.apache.hadoop.security.SecurityUtil.getServerPrincipal(principal,
                SecurityUtil.getLocalHostName());

        String keytabFilePath = configuration.getProperty(KERBEROS_KEYTAB);
        Validate.notEmpty(keytabFilePath, "Missing required configuration property: " + KERBEROS_KEYTAB);
        checkIsReadable(keytabFilePath);

        Configuration conf = new Configuration();
        conf.set("hadoop.security.authentication", "kerberos");

        UserGroupInformation.setConfiguration(conf);
        UserGroupInformation.loginUserFromKeytab(principal, keytabFilePath);

        LOG.info("Got Kerberos ticket, keytab: {}, Falcon principal: {}", keytabFilePath, principal);
    } catch (Exception ex) {
        throw new FalconException("Could not initialize " + SERVICE_NAME + ": " + ex.getMessage(), ex);
    }
}