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.gobblin.compliance.HivePartitionVersionFinder.java

License:Apache License

private void setVersions(final String name, final State state) throws IOException {
    try {// w ww  .ja v a  2s.  co  m
        UserGroupInformation loginUser = UserGroupInformation.getLoginUser();
        loginUser.doAs(new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws IOException {
                synchronized (lock) {
                    List<Partition> partitions = null;
                    for (String tableName : ComplianceRetentionJob.tableNamesList) {
                        for (String pattern : patterns) {
                            if (tableName.contains(pattern)) {
                                partitions = getPartitions(tableName);
                                addPartitionsToVersions(versions, name, partitions);
                            }
                        }
                    }
                }
                return null;
            }
        });
    } catch (InterruptedException | IOException e) {
        throw new IOException(e);
    }
}

From source file:org.apache.gobblin.util.hadoop.TokenUtils.java

License:Apache License

/**
 * function to fetch hcat token as per the specified hive configuration and then store the token
 * in to the credential store specified .
 *
 * @param userToProxy String value indicating the name of the user the token will be fetched for.
 * @param hiveConf the configuration based off which the hive client will be initialized.
 *///from   www.  j  a va 2  s.c  om
private static Token<DelegationTokenIdentifier> fetchHcatToken(final String userToProxy,
        final HiveConf hiveConf, final String tokenSignatureOverwrite, final IMetaStoreClient hiveClient)
        throws IOException, TException, InterruptedException {

    LOG.info(HiveConf.ConfVars.METASTORE_USE_THRIFT_SASL.varname + ": "
            + hiveConf.get(HiveConf.ConfVars.METASTORE_USE_THRIFT_SASL.varname));

    LOG.info(HiveConf.ConfVars.METASTORE_KERBEROS_PRINCIPAL.varname + ": "
            + hiveConf.get(HiveConf.ConfVars.METASTORE_KERBEROS_PRINCIPAL.varname));

    final Token<DelegationTokenIdentifier> hcatToken = new Token<>();

    hcatToken.decodeFromUrlString(
            hiveClient.getDelegationToken(userToProxy, UserGroupInformation.getLoginUser().getShortUserName()));

    // overwrite the value of the service property of the token if the signature
    // override is specified.
    // If the service field is set, do not overwrite that
    if (hcatToken.getService().getLength() <= 0 && tokenSignatureOverwrite != null
            && tokenSignatureOverwrite.trim().length() > 0) {
        hcatToken.setService(new Text(tokenSignatureOverwrite.trim().toLowerCase()));

        LOG.info(HIVE_TOKEN_SIGNATURE_KEY + ":" + tokenSignatureOverwrite);
    }

    LOG.info("Created hive metastore token for user:" + userToProxy + " with kind[" + hcatToken.getKind() + "]"
            + " and service[" + hcatToken.getService() + "]");
    return hcatToken;
}

From source file:org.apache.hawq.pxf.service.servlet.SecurityServletFilter.java

License:Apache License

/**
 * If user impersonation is configured, examines the request for the presense of the expected security headers
 * and create a proxy user to execute further request chain. Responds with an HTTP error if the header is missing
 * or the chain processing throws an exception.
 *
 * @param request http request/*from w  w w  .j ava2s .  c om*/
 * @param response http response
 * @param chain filter chain
 */
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {

    if (SecureLogin.isUserImpersonationEnabled()) {

        // retrieve user header and make sure header is present and is not empty
        final String user = ((HttpServletRequest) request).getHeader(USER_HEADER);
        if (user == null) {
            throw new IllegalArgumentException(MISSING_HEADER_ERROR);
        } else if (user.trim().isEmpty()) {
            throw new IllegalArgumentException(EMPTY_HEADER_ERROR);
        }

        // TODO refresh Kerberos token when security is enabled

        // prepare pivileged action to run on behalf of proxy user
        PrivilegedExceptionAction<Boolean> action = new PrivilegedExceptionAction<Boolean>() {
            @Override
            public Boolean run() throws IOException, ServletException {
                LOG.debug("Performing request chain call for proxy user = " + user);
                chain.doFilter(request, response);
                return true;
            }
        };

        // create proxy user UGI from the UGI of the logged in user and execute the servlet chain as that user
        UserGroupInformation proxyUGI = null;
        try {
            LOG.debug("Creating proxy user = " + user);
            proxyUGI = UserGroupInformation.createProxyUser(user, UserGroupInformation.getLoginUser());
            proxyUGI.doAs(action);
        } catch (UndeclaredThrowableException ute) {
            // unwrap the real exception thrown by the action
            throw new ServletException(ute.getCause());
        } catch (InterruptedException ie) {
            throw new ServletException(ie);
        } finally {
            try {
                if (proxyUGI != null) {
                    LOG.debug("Closing FileSystem for proxy user = " + proxyUGI.getUserName());
                    FileSystem.closeAllForUGI(proxyUGI);
                }
            } catch (Throwable t) {
                LOG.warn("Error closing FileSystem for proxy user = " + proxyUGI.getUserName());
            }
        }
    } else {
        // no user impersonation is configured
        chain.doFilter(request, response);
    }
}

From source file:org.apache.hawq.pxf.service.UGIProvider.java

License:Apache License

/**
 * Wrapper for {@link UserGroupInformation} creation
 *
 * @param effectiveUser the name of the user that we want to impersonate
 * @return a {@link UserGroupInformation} for impersonation.
 * @throws IOException//from  www  .j  a v a  2  s. c  o m
 */
UserGroupInformation createProxyUGI(String effectiveUser) throws IOException {
    return UserGroupInformation.createProxyUser(effectiveUser, UserGroupInformation.getLoginUser());
}

From source file:org.apache.hawq.ranger.authorization.RangerHawqPluginResource.java

License:Apache License

/**
 * Constructor. Creates a new instance of the resource that uses <code>RangerHawqAuthorizer</code>.
 *///from w w w  .j a v a2s .  com
public RangerHawqPluginResource() {
    // set UserGroupInformation under kerberos authentication
    if (Utils.getAuth() == Utils.AuthMethod.KERBEROS) {
        Configuration conf = new Configuration();
        conf.set("hadoop.security.authentication", "kerberos");
        UserGroupInformation.setConfiguration(conf);

        String prin = Utils.getPrincipal();
        String keytab = Utils.getKeytab();

        if (!prin.equals("") && !keytab.equals("")) {
            try {
                UserGroupInformation.loginUserFromKeytab(prin, keytab);
            } catch (Exception e) {
                LOG.warn(String.format("loginUserFromKeytab failed, user[%s], keytab[%s]", prin, keytab));
            }
        }
    }

    if (LOG.isDebugEnabled()) {
        try {
            UserGroupInformation user = UserGroupInformation.getLoginUser();
            LOG.debug(String.format("login user: %s", user));
        } catch (Exception e) {
            LOG.warn("get login user failed exception: " + e);
        }
    }

    this.authorizer = RangerHawqAuthorizer.getInstance();

}

From source file:org.apache.hcatalog.templeton.SecureProxySupport.java

License:Apache License

private Token<?> getFSDelegationToken(String user, final Configuration conf)
        throws IOException, InterruptedException {
    LOG.info("user: " + user + " loginUser: " + UserGroupInformation.getLoginUser().getUserName());
    final UserGroupInformation ugi = UgiFactory.getUgi(user);

    final TokenWrapper twrapper = new TokenWrapper();
    ugi.doAs(new PrivilegedExceptionAction<Object>() {
        public Object run() throws IOException {
            FileSystem fs = FileSystem.get(conf);
            twrapper.token = fs.getDelegationToken(ugi.getShortUserName());
            return null;
        }/*from   www  .  j a v  a 2  s . c o m*/
    });
    return twrapper.token;

}

From source file:org.apache.hcatalog.templeton.SecureProxySupport.java

License:Apache License

private void writeProxyDelegationTokens(final Token<?> fsToken, final Token<?> msToken,
        final Configuration conf, String user, final Path tokenPath) throws IOException, InterruptedException {

    LOG.info("user: " + user + " loginUser: " + UserGroupInformation.getLoginUser().getUserName());
    final UserGroupInformation ugi = UgiFactory.getUgi(user);

    ugi.doAs(new PrivilegedExceptionAction<Object>() {
        public Object run() throws IOException {
            Credentials cred = new Credentials();
            cred.addToken(fsToken.getService(), fsToken);
            cred.addToken(msToken.getService(), msToken);
            cred.writeTokenStorageFile(tokenPath, conf);
            return null;
        }//ww w. j  av  a 2s  . co m
    });

}

From source file:org.apache.hcatalog.templeton.SecureProxySupport.java

License:Apache License

private String buildHcatDelegationToken(String user)
        throws IOException, InterruptedException, MetaException, TException {
    HiveConf c = new HiveConf();
    final HiveMetaStoreClient client = new HiveMetaStoreClient(c);
    LOG.info("user: " + user + " loginUser: " + UserGroupInformation.getLoginUser().getUserName());
    final TokenWrapper twrapper = new TokenWrapper();
    final UserGroupInformation ugi = UgiFactory.getUgi(user);
    String s = ugi.doAs(new PrivilegedExceptionAction<String>() {
        public String run() throws IOException, MetaException, TException {
            String u = ugi.getUserName();
            return client.getDelegationToken(u);
        }/*from   www . ja v  a 2  s . c  om*/
    });
    return s;
}

From source file:org.apache.hcatalog.templeton.tool.TempletonUtils.java

License:Apache License

public static Path hadoopFsPath(String fname, Configuration conf, String user)
        throws URISyntaxException, FileNotFoundException, IOException, InterruptedException {
    if (fname == null || conf == null) {
        return null;
    }/*from   w ww. j  a  va  2 s  .c  o  m*/

    final Configuration fConf = new Configuration(conf);
    final String finalFName = new String(fname);

    UserGroupInformation ugi = UserGroupInformation.getLoginUser();
    final FileSystem defaultFs = ugi.doAs(new PrivilegedExceptionAction<FileSystem>() {
        public FileSystem run()
                throws URISyntaxException, FileNotFoundException, IOException, InterruptedException {
            return FileSystem.get(new URI(finalFName), fConf);
        }
    });

    URI u = new URI(fname);
    Path p = new Path(u).makeQualified(defaultFs);

    if (hadoopFsIsMissing(defaultFs, p))
        throw new FileNotFoundException("File " + fname + " does not exist.");

    return p;
}

From source file:org.apache.hcatalog.templeton.UgiFactory.java

License:Apache License

static UserGroupInformation getUgi(String user) throws IOException {
    UserGroupInformation ugi = userUgiMap.get(user);
    if (ugi == null) {
        //create new ugi and add to map
        final UserGroupInformation newUgi = UserGroupInformation.createProxyUser(user,
                UserGroupInformation.getLoginUser());

        //if another thread adds an entry before the check in this one
        // the one created here will not be added.
        userUgiMap.putIfAbsent(user, newUgi);

        //use the UGI object that got added
        return userUgiMap.get(user);

    }/*from   w  w w .  j  av  a 2s . co  m*/
    return ugi;
}