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.oozie.action.hadoop.MainTestCase.java

License:Apache License

public static void execute(String user, final Callable<Void> callable) throws Exception {
    UserGroupInformation ugi = UserGroupInformation.createProxyUser(user, UserGroupInformation.getLoginUser());
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        public Void run() throws Exception {
            callable.call();/*from   www.  j ava2  s . c  o  m*/
            return null;
        }
    });
}

From source file:org.apache.oozie.client.ProxyOozieClient.java

License:Apache License

@Override
protected HttpURLConnection createConnection(URL url, final String method)
        throws IOException, OozieClientException {

    final URL decoratedUrl = decorateUrlWithUser(url);
    LOG.debug("ProxyOozieClient.createConnection: u={}, m={}", url, method);

    // Login User "falcon" has the kerberos credentials
    UserGroupInformation loginUserUGI = UserGroupInformation.getLoginUser();
    try {//  w  ww  .  j  a  va2 s  .  c o  m
        return loginUserUGI.doAs(new PrivilegedExceptionAction<HttpURLConnection>() {
            public HttpURLConnection run() throws Exception {
                HttpURLConnection conn = ProxyOozieClient.super.createConnection(decoratedUrl, method);

                int connectTimeout = Integer
                        .parseInt(RuntimeProperties.get().getProperty("oozie.connect.timeout", "1000"));
                conn.setConnectTimeout(connectTimeout);

                int readTimeout = Integer
                        .parseInt(RuntimeProperties.get().getProperty("oozie.read.timeout", "45000"));
                conn.setReadTimeout(readTimeout);

                return conn;
            }
        });
    } catch (InterruptedException e) {
        throw new IOException("Could not connect to oozie: " + e.getMessage(), e);
    }
}

From source file:org.apache.oozie.client.ProxyOozieClient.java

License:Apache License

protected URL decorateUrlWithUser(URL url) throws IOException {
    String strUrl = url.toString();

    if (!strUrl.contains(OozieClient.USER_NAME)) {
        // decorate the url with the proxy user in request
        String paramSeparator = (strUrl.contains("?")) ? "&" : "?";
        strUrl += paramSeparator + OozieClient.USER_NAME + "="
                + UserGroupInformation.getLoginUser().getUserName();
        // strUrl += "&" + RestConstants.DO_AS_PARAM + "=" + CurrentUser.getUser();

        url = new URL(strUrl);
        LOG.debug("Decorated url with user info: {}", url);
    }//from w  ww. j a  v  a  2s  . c o  m

    return url;
}

From source file:org.apache.oozie.dependency.HCatURIHandler.java

License:Apache License

private HCatClient getHCatClient(URI uri, Configuration conf) throws HCatAccessorException {
    HiveConf hiveConf = getHiveConf(uri, conf);
    try {/*from   www. j a va  2 s. c o m*/
        XLog.getLog(HCatURIHandler.class).info("Creating HCatClient for login_user [{0}] and server [{1}] ",
                UserGroupInformation.getLoginUser(), hiveConf.get(HiveConf.ConfVars.METASTOREURIS.varname));
        return HCatClient.create(hiveConf);
    } catch (HCatException e) {
        throw new HCatAccessorException(ErrorCode.E1501, e);
    } catch (IOException e) {
        throw new HCatAccessorException(ErrorCode.E1501, e);
    }
}

From source file:org.apache.oozie.dependency.HCatURIHandler.java

License:Apache License

private HCatClientWithToken getHCatClient(URI uri, Configuration conf, String user)
        throws HCatAccessorException {
    final HiveConf hiveConf = getHiveConf(uri, conf);
    String delegationToken = null;
    try {//from w w  w  .j  a  v a 2s .c o m
        // Get UGI to doAs() as the specified user
        UserGroupInformation ugi = UserGroupInformation.createProxyUser(user,
                UserGroupInformation.getLoginUser());
        // Define the label for the Delegation Token for the HCat instance.
        hiveConf.set("hive.metastore.token.signature", "HCatTokenSignature");
        if (hiveConf.getBoolean(HiveConf.ConfVars.METASTORE_USE_THRIFT_SASL.varname, false)) {
            HCatClient tokenClient = null;
            try {
                // Retrieve Delegation token for HCatalog
                tokenClient = HCatClient.create(hiveConf);
                delegationToken = tokenClient.getDelegationToken(user,
                        UserGroupInformation.getLoginUser().getUserName());
                // Store Delegation token in the UGI
                Token<DelegationTokenIdentifier> token = new Token<DelegationTokenIdentifier>();
                token.decodeFromUrlString(delegationToken);
                token.setService(new Text(hiveConf.get("hive.metastore.token.signature")));
                ugi.addToken(token);
            } finally {
                if (tokenClient != null) {
                    tokenClient.close();
                }
            }
        }
        XLog.getLog(HCatURIHandler.class).info(
                "Creating HCatClient for user [{0}] login_user [{1}] and server [{2}] ", user,
                UserGroupInformation.getLoginUser(), hiveConf.get(HiveConf.ConfVars.METASTOREURIS.varname));
        HCatClient hcatClient = ugi.doAs(new PrivilegedExceptionAction<HCatClient>() {
            @Override
            public HCatClient run() throws Exception {
                HCatClient client = HCatClient.create(hiveConf);
                return client;
            }
        });
        HCatClientWithToken clientWithToken = new HCatClientWithToken(hcatClient, delegationToken);
        return clientWithToken;
    } catch (IOException e) {
        throw new HCatAccessorException(ErrorCode.E1501, e.getMessage());
    } catch (Exception e) {
        throw new HCatAccessorException(ErrorCode.E1501, e.getMessage());
    }
}

From source file:org.apache.oozie.service.KerberosHadoopAccessorService.java

License:Open Source License

private UserGroupInformation getUGI(String user) throws IOException {
    UserGroupInformation ugi = userUgiMap.get(user);
    if (ugi == null) {
        // taking care of a race condition, the latest UGI will be discarded
        ugi = UserGroupInformation.createProxyUser(user, UserGroupInformation.getLoginUser());
        userUgiMap.putIfAbsent(user, ugi);
    }// w  w w. j a v  a  2s .  c o m
    return ugi;
}

From source file:org.apache.oozie.service.UserGroupInformationService.java

License:Apache License

public UserGroupInformation getProxyUser(String user) throws IOException {
    cache.putIfAbsent(user, UserGroupInformation.createProxyUser(user, UserGroupInformation.getLoginUser()));
    return cache.get(user);
}

From source file:org.apache.oozie.util.AuthUrlClient.java

License:Apache License

/**
 * Calls other Oozie server over HTTP./*from   w ww .ja va2  s.co  m*/
 *
 * @param server The URL of the other Oozie server
 * @return BufferedReader of inputstream.
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static BufferedReader callServer(String server) throws IOException {

    if (AuthenticatorClass == null) {
        throw new IOException(errorMsg);
    }

    final URL url = new URL(server);
    BufferedReader reader = null;
    try {
        reader = UserGroupInformation.getLoginUser().doAs(new PrivilegedExceptionAction<BufferedReader>() {
            @Override
            public BufferedReader run() throws IOException {
                HttpURLConnection conn = getConnection(url);
                BufferedReader reader = null;
                if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) {
                    InputStream is = conn.getInputStream();
                    reader = new BufferedReader(new InputStreamReader(is));
                }
                return reader;
            }
        });
    } catch (InterruptedException ie) {
        throw new IOException(ie);
    }
    return reader;
}

From source file:org.apache.phoenix.queryserver.server.Main.java

License:Apache License

@Override
public int run(String[] args) throws Exception {
    logProcessInfo(getConf());//from   w  w w. j  a v  a 2 s  .c o m
    try {
        final boolean isKerberos = "kerberos"
                .equalsIgnoreCase(getConf().get(QueryServices.QUERY_SERVER_HBASE_SECURITY_CONF_ATTRIB));

        // handle secure cluster credentials
        if (isKerberos) {
            String hostname = Strings.domainNamePointerToHostName(DNS.getDefaultHost(
                    getConf().get(QueryServices.QUERY_SERVER_DNS_INTERFACE_ATTRIB, "default"),
                    getConf().get(QueryServices.QUERY_SERVER_DNS_NAMESERVER_ATTRIB, "default")));
            if (LOG.isDebugEnabled()) {
                LOG.debug("Login to " + hostname + " using "
                        + getConf().get(QueryServices.QUERY_SERVER_KEYTAB_FILENAME_ATTRIB) + " and principal "
                        + getConf().get(QueryServices.QUERY_SERVER_KERBEROS_PRINCIPAL_ATTRIB) + ".");
            }
            SecurityUtil.login(getConf(), QueryServices.QUERY_SERVER_KEYTAB_FILENAME_ATTRIB,
                    QueryServices.QUERY_SERVER_KERBEROS_PRINCIPAL_ATTRIB, hostname);
            LOG.info("Login successful.");
        }

        Class<? extends PhoenixMetaFactory> factoryClass = getConf().getClass(
                QueryServices.QUERY_SERVER_META_FACTORY_ATTRIB, PhoenixMetaFactoryImpl.class,
                PhoenixMetaFactory.class);
        int port = getConf().getInt(QueryServices.QUERY_SERVER_HTTP_PORT_ATTRIB,
                QueryServicesOptions.DEFAULT_QUERY_SERVER_HTTP_PORT);
        LOG.debug("Listening on port " + port);
        PhoenixMetaFactory factory = factoryClass.getDeclaredConstructor(Configuration.class)
                .newInstance(getConf());
        Meta meta = factory.create(Arrays.asList(args));
        Service service = new LocalService(meta);

        // Start building the Avatica HttpServer
        final HttpServer.Builder builder = new HttpServer.Builder().withPort(port).withHandler(service,
                getSerialization(getConf()));

        // Enable SPNEGO and Impersonation when using Kerberos
        if (isKerberos) {
            UserGroupInformation ugi = UserGroupInformation.getLoginUser();

            // Make sure the proxyuser configuration is up to date
            ProxyUsers.refreshSuperUserGroupsConfiguration(getConf());

            String keytabPath = getConf().get(QueryServices.QUERY_SERVER_KEYTAB_FILENAME_ATTRIB);
            File keytab = new File(keytabPath);

            // Enable SPNEGO and impersonation (through standard Hadoop configuration means)
            builder.withSpnego(ugi.getUserName()).withAutomaticLogin(keytab)
                    .withImpersonation(new PhoenixDoAsCallback(ugi));
        }

        // Build and start the HttpServer
        server = builder.build();
        server.start();
        runningLatch.countDown();
        server.join();
        return 0;
    } catch (Throwable t) {
        LOG.fatal("Unrecoverable service error. Shutting down.", t);
        this.t = t;
        return -1;
    }
}

From source file:org.apache.phoenix.queryserver.server.QueryServer.java

License:Apache License

@Override
public int run(String[] args) throws Exception {
    logProcessInfo(getConf());//from  ww  w  .  j  ava 2  s  . c  o  m
    final boolean loadBalancerEnabled = getConf().getBoolean(
            QueryServices.PHOENIX_QUERY_SERVER_LOADBALANCER_ENABLED,
            QueryServicesOptions.DEFAULT_PHOENIX_QUERY_SERVER_LOADBALANCER_ENABLED);
    try {
        final boolean isKerberos = "kerberos"
                .equalsIgnoreCase(getConf().get(QueryServices.QUERY_SERVER_HBASE_SECURITY_CONF_ATTRIB));
        final boolean disableSpnego = getConf().getBoolean(
                QueryServices.QUERY_SERVER_SPNEGO_AUTH_DISABLED_ATTRIB,
                QueryServicesOptions.DEFAULT_QUERY_SERVER_SPNEGO_AUTH_DISABLED);
        String hostname;
        final boolean disableLogin = getConf().getBoolean(QueryServices.QUERY_SERVER_DISABLE_KERBEROS_LOGIN,
                QueryServicesOptions.DEFAULT_QUERY_SERVER_DISABLE_KERBEROS_LOGIN);

        // handle secure cluster credentials
        if (isKerberos && !disableSpnego && !disableLogin) {
            hostname = Strings.domainNamePointerToHostName(DNS.getDefaultHost(
                    getConf().get(QueryServices.QUERY_SERVER_DNS_INTERFACE_ATTRIB, "default"),
                    getConf().get(QueryServices.QUERY_SERVER_DNS_NAMESERVER_ATTRIB, "default")));
            if (LOG.isDebugEnabled()) {
                LOG.debug("Login to " + hostname + " using "
                        + getConf().get(QueryServices.QUERY_SERVER_KEYTAB_FILENAME_ATTRIB) + " and principal "
                        + getConf().get(QueryServices.QUERY_SERVER_KERBEROS_PRINCIPAL_ATTRIB) + ".");
            }
            SecurityUtil.login(getConf(), QueryServices.QUERY_SERVER_KEYTAB_FILENAME_ATTRIB,
                    QueryServices.QUERY_SERVER_KERBEROS_PRINCIPAL_ATTRIB, hostname);
            LOG.info("Login successful.");
        } else {
            hostname = InetAddress.getLocalHost().getHostName();
            LOG.info(" Kerberos is off and hostname is : " + hostname);
        }

        Class<? extends PhoenixMetaFactory> factoryClass = getConf().getClass(
                QueryServices.QUERY_SERVER_META_FACTORY_ATTRIB, PhoenixMetaFactoryImpl.class,
                PhoenixMetaFactory.class);
        int port = getConf().getInt(QueryServices.QUERY_SERVER_HTTP_PORT_ATTRIB,
                QueryServicesOptions.DEFAULT_QUERY_SERVER_HTTP_PORT);
        LOG.debug("Listening on port " + port);
        PhoenixMetaFactory factory = factoryClass.getDeclaredConstructor(Configuration.class)
                .newInstance(getConf());
        Meta meta = factory.create(Arrays.asList(args));
        Service service = new LocalService(meta);

        // Start building the Avatica HttpServer
        final HttpServer.Builder builder = new HttpServer.Builder().withPort(port).withHandler(service,
                getSerialization(getConf()));

        // Enable SPNEGO and Impersonation when using Kerberos
        if (isKerberos) {
            UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
            LOG.debug("Current user is " + ugi);
            if (!ugi.hasKerberosCredentials()) {
                ugi = UserGroupInformation.getLoginUser();
                LOG.debug("Current user does not have Kerberos credentials, using instead " + ugi);
            }

            // Make sure the proxyuser configuration is up to date
            ProxyUsers.refreshSuperUserGroupsConfiguration(getConf());

            String keytabPath = getConf().get(QueryServices.QUERY_SERVER_KEYTAB_FILENAME_ATTRIB);
            File keytab = new File(keytabPath);

            String realmsString = getConf().get(QueryServices.QUERY_SERVER_KERBEROS_ALLOWED_REALMS, null);
            String[] additionalAllowedRealms = null;
            if (null != realmsString) {
                additionalAllowedRealms = StringUtils.split(realmsString, ',');
            }

            // Enable SPNEGO and impersonation (through standard Hadoop configuration means)
            builder.withSpnego(ugi.getUserName(), additionalAllowedRealms).withAutomaticLogin(keytab)
                    .withImpersonation(new PhoenixDoAsCallback(ugi, getConf()));

        }
        setRemoteUserExtractorIfNecessary(builder, getConf());

        // Build and start the HttpServer
        server = builder.build();
        server.start();
        if (loadBalancerEnabled) {
            registerToServiceProvider(hostname);
        }
        runningLatch.countDown();
        server.join();
        return 0;
    } catch (Throwable t) {
        LOG.fatal("Unrecoverable service error. Shutting down.", t);
        this.t = t;
        return -1;
    } finally {
        if (loadBalancerEnabled) {
            unRegister();
        }
    }
}