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.drill.exec.rpc.BitConnectionConfig.java

License:Apache License

public Map<String, ?> getSaslClientProperties(final DrillbitEndpoint remoteEndpoint) throws IOException {
    final DrillProperties properties = DrillProperties.createEmpty();

    final UserGroupInformation loginUser = UserGroupInformation.getLoginUser();
    if (loginUser.getAuthenticationMethod() == UserGroupInformation.AuthenticationMethod.KERBEROS) {
        final HadoopKerberosName loginPrincipal = new HadoopKerberosName(loginUser.getUserName());
        if (!useLoginPrincipal) {
            properties.setProperty(DrillProperties.SERVICE_PRINCIPAL, KerberosUtil.getPrincipalFromParts(
                    loginPrincipal.getShortName(), remoteEndpoint.getAddress(), loginPrincipal.getRealm()));
        } else {//from  ww  w.  jav  a  2s. c  o  m
            properties.setProperty(DrillProperties.SERVICE_PRINCIPAL, loginPrincipal.toString());
        }
    }
    return properties.stringPropertiesAsMap();
}

From source file:org.apache.drill.exec.rpc.BitRpcUtility.java

License:Apache License

/**
 * Creates various instances needed to start the SASL handshake. This is called from
 * {@link BasicClient#prepareSaslHandshake(RpcConnectionHandler, List)} only for
 * {@link org.apache.drill.exec.rpc.data.DataClient} and {@link org.apache.drill.exec.rpc.control.ControlClient}
 *
 * @param connectionHandler    - Connection handler used by client's to know about success/failure conditions.
 * @param serverAuthMechanisms - List of auth mechanisms configured on server side
 * @param connection - ClientConnection used for authentication
 * @param config - ClientConnection config
 * @param endpoint - Remote DrillbitEndpoint
 * @param client - Either of DataClient/ControlClient instance
 * @param saslRpcType - SASL_MESSAGE RpcType for Data and Control channel
 *//* www .  j a  va2 s.c o m*/
public static <T extends EnumLite, CC extends ClientConnection, HS extends MessageLite, HR extends MessageLite> void prepareSaslHandshake(
        final RpcConnectionHandler<CC> connectionHandler, List<String> serverAuthMechanisms, CC connection,
        BitConnectionConfig config, DrillbitEndpoint endpoint, final BasicClient<T, CC, HS, HR> client,
        T saslRpcType) {
    try {
        final Map<String, String> saslProperties = SaslProperties
                .getSaslProperties(connection.isEncryptionEnabled(), connection.getMaxWrappedSize());
        final UserGroupInformation ugi = UserGroupInformation.getLoginUser();
        final AuthenticatorFactory factory = config.getAuthFactory(serverAuthMechanisms);
        client.startSaslHandshake(connectionHandler, config.getSaslClientProperties(endpoint, saslProperties),
                ugi, factory, saslRpcType);
    } catch (final IOException e) {
        logger.error("Failed while doing setup for starting sasl handshake for connection",
                connection.getName());
        final Exception ex = new RpcException(
                String.format("Failed to initiate authentication to %s", endpoint.getAddress()), e);
        connectionHandler.connectionFailed(RpcConnectionHandler.FailureType.AUTHENTICATION, ex);
    }
}

From source file:org.apache.drill.exec.rpc.control.ControlClient.java

License:Apache License

@Override
protected void validateHandshake(BitControlHandshake handshake) throws RpcException {
    if (handshake.getRpcVersion() != ControlRpcConfig.RPC_VERSION) {
        throw new RpcException(String.format("Invalid rpc version.  Expected %d, actual %d.",
                handshake.getRpcVersion(), ControlRpcConfig.RPC_VERSION));
    }/*from  w w w .j  a  v a 2 s . co  m*/

    if (handshake.getAuthenticationMechanismsCount() != 0) { // remote requires authentication
        final SaslClient saslClient;
        try {
            saslClient = config.getAuthFactory(handshake.getAuthenticationMechanismsList()).createSaslClient(
                    UserGroupInformation.getLoginUser(), config.getSaslClientProperties(remoteEndpoint));
        } catch (final IOException e) {
            throw new RpcException(
                    String.format("Failed to initiate authenticate to %s", remoteEndpoint.getAddress()), e);
        }
        if (saslClient == null) {
            throw new RpcException("Unexpected failure. Could not initiate SASL exchange.");
        }
        connection.setSaslClient(saslClient);
    } else {
        if (config.getAuthMechanismToUse() != null) { // local requires authentication
            throw new RpcException(String.format("Drillbit (%s) does not require auth, but auth is enabled.",
                    remoteEndpoint.getAddress()));
        }
    }
}

From source file:org.apache.drill.exec.rpc.data.DataClient.java

License:Apache License

@Override
protected void validateHandshake(BitServerHandshake handshake) throws RpcException {
    if (handshake.getRpcVersion() != DataRpcConfig.RPC_VERSION) {
        throw new RpcException(String.format("Invalid rpc version.  Expected %d, actual %d.",
                handshake.getRpcVersion(), DataRpcConfig.RPC_VERSION));
    }//from   w  w w.  j  a v a2 s .  com

    if (handshake.getAuthenticationMechanismsCount() != 0) { // remote requires authentication
        final SaslClient saslClient;
        try {
            saslClient = config.getAuthFactory(handshake.getAuthenticationMechanismsList()).createSaslClient(
                    UserGroupInformation.getLoginUser(), config.getSaslClientProperties(remoteEndpoint));
        } catch (final IOException e) {
            throw new RpcException(
                    String.format("Failed to initiate authenticate to %s", remoteEndpoint.getAddress()), e);
        }
        if (saslClient == null) {
            throw new RpcException("Unexpected failure. Could not initiate SASL exchange.");
        }
        connection.setSaslClient(saslClient);
    } else {
        if (config.getAuthMechanismToUse() != null) {
            throw new RpcException(String.format("Drillbit (%s) does not require auth, but auth is enabled.",
                    remoteEndpoint.getAddress()));
        }
    }
}

From source file:org.apache.drill.exec.rpc.security.ServerAuthenticationHandler.java

License:Apache License

private static byte[] evaluateResponse(final SaslServer saslServer, final byte[] responseBytes)
        throws SaslException {
    try {/*w  w w  .java2 s . c  om*/
        return UserGroupInformation.getLoginUser().doAs(new PrivilegedExceptionAction<byte[]>() {
            @Override
            public byte[] run() throws Exception {
                return saslServer.evaluateResponse(responseBytes);
            }
        });
    } catch (final UndeclaredThrowableException e) {
        throw new SaslException(String.format("Unexpected failure trying to authenticate using %s",
                saslServer.getMechanismName()), e.getCause());
    } catch (final IOException | InterruptedException e) {
        if (e instanceof SaslException) {
            throw (SaslException) e;
        } else {
            throw new SaslException(String.format("Unexpected failure trying to authenticate using %s",
                    saslServer.getMechanismName()), e);
        }
    }
}

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

License:Apache License

private void login(final DrillConfig config) throws DrillbitStartupException {
    try {//w  ww . java  2s.c o  m
        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.drill.exec.util.ImpersonationUtil.java

License:Apache License

/**
 * Create and return proxy user {@link org.apache.hadoop.security.UserGroupInformation} for give user name.
 *
 * @param proxyUserName Proxy user name (must be valid)
 * @return//ww w .j  av  a 2s.  c  o  m
 */
public static UserGroupInformation createProxyUgi(String proxyUserName) {
    try {
        if (Strings.isNullOrEmpty(proxyUserName)) {
            throw new DrillRuntimeException("Invalid value for proxy user name");
        }

        // If the request proxy user is same as process user name, return the process UGI.
        if (proxyUserName.equals(getProcessUserName())) {
            return getProcessUserUGI();
        }

        return CACHE.get(new Key(proxyUserName, UserGroupInformation.getLoginUser()));
    } catch (IOException | ExecutionException e) {
        final String errMsg = "Failed to create proxy user UserGroupInformation object: " + e.getMessage();
        logger.error(errMsg, e);
        throw new DrillRuntimeException(errMsg, e);
    }
}

From source file:org.apache.drill.exec.util.ImpersonationUtil.java

License:Apache License

/**
 * Return the {@link org.apache.hadoop.security.UserGroupInformation} of user who is running the Drillbit.
 *
 * @return Drillbit process user {@link org.apache.hadoop.security.UserGroupInformation}.
 *///from  www .  jav a2s .c o m
public static UserGroupInformation getProcessUserUGI() {
    try {
        return UserGroupInformation.getLoginUser();
    } catch (IOException e) {
        final String errMsg = "Failed to get process user UserGroupInformation object.";
        logger.error(errMsg, e);
        throw new DrillRuntimeException(errMsg, e);
    }
}

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 {/*from   ww  w. j  a  v  a2s  .  co 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.falcon.atlas.service.AtlasService.java

License:Apache License

private void addEntity(Entity entity, FalconEvent.OPERATION operation) throws FalconException {
    LOG.info("Adding {} entity to Atlas: {}", entity.getEntityType().name(), entity.getName());

    try {/*from   ww w. j a  v  a2  s  . com*/
        String user = entity.getACL() != null ? entity.getACL().getOwner()
                : UserGroupInformation.getLoginUser().getShortUserName();
        FalconEvent event = new FalconEvent(user, EventUtil.getUgi(), operation, System.currentTimeMillis(),
                entity);
        FalconEventPublisher.Data data = new FalconEventPublisher.Data(event);
        publisher.publish(data);
    } catch (Exception ex) {
        throw new FalconException("Unable to publish data to publisher " + ex.getMessage(), ex);
    }
}