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

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

Introduction

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

Prototype

@InterfaceAudience.Public
@InterfaceStability.Evolving
public static UserGroupInformation getCurrentUser() throws IOException 

Source Link

Document

Return the current user, including any doAs in the current stack.

Usage

From source file:org.apache.sentry.service.thrift.HiveSimpleConnectionFactory.java

License:Apache License

/**
 * Connect to HMS in unsecure mode or in Kerberos mode according to config.
 *
 * @return HMS connection// ww  w .  j av a  2 s .co  m
 * @throws IOException          if could not establish connection
 * @throws InterruptedException if connection was interrupted
 * @throws MetaException        if other errors happened
 */
public HMSClient connect() throws IOException, InterruptedException, MetaException {
    UserGroupInformation clientUGI;

    if (insecure) {
        clientUGI = UserGroupInformation.getCurrentUser();
    } else {
        clientUGI = UserGroupInformation.getUGIFromSubject(kerberosContext.getSubject());
    }
    return new HMSClient(clientUGI.doAs(new PrivilegedExceptionAction<HiveMetaStoreClient>() {
        @Override
        public HiveMetaStoreClient run() throws MetaException {
            return new HiveMetaStoreClient(hiveConf);
        }
    }));
}

From source file:org.apache.sentry.sqoop.binding.SqoopAuthBinding.java

License:Apache License

public SqoopAuthBinding(Configuration authConf, String serverName) throws Exception {
    this.authConf = authConf;
    this.authConf.set(AuthzConfVars.AUTHZ_SERVER_NAME.getVar(), serverName);
    this.sqoopServer = new Server(serverName);
    this.authProvider = createAuthProvider();
    /** The Sqoop server principal will use the binding */
    this.bindingSubject = new Subject(UserGroupInformation.getCurrentUser().getShortUserName());
}

From source file:org.apache.slider.client.SliderClient.java

License:Apache License

private void actionDiagnosticClient(ActionDiagnosticArgs diagnosticArgs) throws SliderException, IOException {
    try {//from   www  .  ja v  a  2s  .co  m
        String currentCommandPath = SliderUtils.getCurrentCommandPath();
        SliderVersionInfo.loadAndPrintVersionInfo(log);
        String clientConfigPath = SliderUtils.getClientConfigPath();
        String jdkInfo = SliderUtils.getJDKInfo();
        println("The slider command path: %s", currentCommandPath);
        println("The slider-client.xml used by current running command path: %s", clientConfigPath);
        println(jdkInfo);

        // security info
        Configuration config = getConfig();
        if (SliderUtils.isHadoopClusterSecure(config)) {
            println("Hadoop Cluster is secure");
            println("Login user is %s", UserGroupInformation.getLoginUser());
            println("Current user is %s", UserGroupInformation.getCurrentUser());

        } else {
            println("Hadoop Cluster is insecure");
        }

        // verbose?
        if (diagnosticArgs.verbose) {
            // do the environment
            Map<String, String> env = System.getenv();
            Set<String> envList = ConfigHelper.sortedConfigKeys(env.entrySet());
            StringBuilder builder = new StringBuilder("Environment variables:\n");
            for (String key : envList) {
                builder.append(key).append("=").append(env.get(key)).append("\n");
            }
            println(builder.toString());

            // Java properties
            builder = new StringBuilder("JVM Properties\n");
            Map<String, String> props = SliderUtils.sortedMap(SliderUtils.toMap(System.getProperties()));
            for (Entry<String, String> entry : props.entrySet()) {
                builder.append(entry.getKey()).append("=").append(entry.getValue()).append("\n");
            }

            println(builder.toString());

            // then the config
            println("Slider client configuration:\n" + ConfigHelper.dumpConfigToString(config));

        }

        SliderUtils.validateSliderClientEnvironment(log);
    } catch (SliderException e) {
        log.error(e.toString());
        throw e;
    } catch (IOException e) {
        log.error(e.toString());
        throw e;
    }

}

From source file:org.apache.slider.client.TokensOperation.java

License:Apache License

public int actionTokens(ActionTokensArgs args, FileSystem fs, Configuration conf, YarnClientImpl yarnClient)
        throws IOException, YarnException {
    Credentials credentials;//w  w w .jav  a2s .co m
    String footnote = "";
    UserGroupInformation user = UserGroupInformation.getCurrentUser();
    boolean isSecure = UserGroupInformation.isSecurityEnabled();
    if (args.keytab != null) {
        File keytab = args.keytab;
        if (!keytab.isFile()) {
            throw new NotFoundException(E_NO_KEYTAB + keytab.getAbsolutePath());
        }
        String principal = args.principal;
        log.info("Logging in as {} from keytab {}", principal, keytab);
        user = UserGroupInformation.loginUserFromKeytabAndReturnUGI(principal, keytab.getCanonicalPath());
    }
    Credentials userCredentials = user.getCredentials();
    File output = args.output;
    if (output != null) {
        if (!isSecure) {
            throw new BadClusterStateException(E_INSECURE);
        }
        credentials = new Credentials(userCredentials);
        // filesystem
        addRMRenewableFSDelegationTokens(conf, fs, credentials);
        addRMDelegationToken(yarnClient, credentials);
        if (maybeAddTimelineToken(conf, credentials) != null) {
            log.debug("Added timeline token");
        }
        saveTokens(output, credentials);
        String filename = output.getCanonicalPath();
        footnote = String.format(
                "%d tokens saved to %s\n" + "To use these in the environment:\n" + "export %s=%s",
                credentials.numberOfTokens(), filename, UserGroupInformation.HADOOP_TOKEN_FILE_LOCATION,
                filename);
    } else if (args.source != null) {
        File source = args.source;
        log.info("Reading credentials from file {}", source);
        if (!source.isFile()) {
            throw new NotFoundException(E_MISSING_SOURCE_FILE + source.getAbsolutePath());
        }
        credentials = Credentials.readTokenStorageFile(args.source, conf);
    } else {
        StringBuffer origin = new StringBuffer();
        File file = locateEnvCredentials(System.getenv(), conf, origin);
        if (file != null) {
            log.info("Credential Source {}", origin);
        } else {
            log.info("Credential source: logged in user");
        }
        credentials = userCredentials;
    }
    // list the tokens
    log.info("\n{}", dumpTokens(credentials, "\n"));
    if (!footnote.isEmpty()) {
        log.info(footnote);
    }
    return 0;
}

From source file:org.apache.slider.common.tools.SliderUtils.java

License:Apache License

/**
 * Turn on security. This is setup to only run once.
 * @param conf configuration to build up security
 * @return true if security was initialized in this call
 * @throws IOException IO/Net problems//from   www  .  ja va  2 s  . com
 * @throws BadConfigException the configuration and system state are inconsistent
 */
public static boolean initProcessSecurity(Configuration conf) throws IOException, BadConfigException {

    if (processSecurityAlreadyInitialized.compareAndSet(true, true)) {
        //security is already inited
        return false;
    }

    log.info("JVM initialized into secure mode with kerberos realm {}", SliderUtils.getKerberosRealm());
    //this gets UGI to reset its previous world view (i.e simple auth)
    //security
    log.debug("java.security.krb5.realm={}", System.getProperty(JAVA_SECURITY_KRB5_REALM, ""));
    log.debug("java.security.krb5.kdc={}", System.getProperty(JAVA_SECURITY_KRB5_KDC, ""));
    log.debug("hadoop.security.authentication={}",
            conf.get(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION));
    log.debug("hadoop.security.authorization={}",
            conf.get(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION));
    /*    SecurityUtil.setAuthenticationMethod(
            UserGroupInformation.AuthenticationMethod.KERBEROS, conf);*/
    UserGroupInformation.setConfiguration(conf);
    UserGroupInformation authUser = UserGroupInformation.getCurrentUser();
    log.debug("Authenticating as " + authUser.toString());
    log.debug("Login user is {}", UserGroupInformation.getLoginUser());
    if (!UserGroupInformation.isSecurityEnabled()) {
        throw new BadConfigException("Although secure mode is enabled,"
                + "the application has already set up its user as an insecure entity %s", authUser);
    }
    if (authUser.getAuthenticationMethod() == UserGroupInformation.AuthenticationMethod.SIMPLE) {
        throw new BadConfigException("Auth User is not Kerberized %s"
                + " -security has already been set up with the wrong authentication method. "
                + "This can occur if a file system has already been created prior to the loading of "
                + "the security configuration.", authUser);

    }

    SliderUtils.verifyPrincipalSet(conf, YarnConfiguration.RM_PRINCIPAL);
    SliderUtils.verifyPrincipalSet(conf, DFSConfigKeys.DFS_NAMENODE_KERBEROS_PRINCIPAL_KEY);
    return true;
}

From source file:org.apache.slider.common.tools.SliderUtils.java

License:Apache License

/**
 * Get the current user -relays to/*  w w  w.  ja va2s . c  o m*/
 * {@link UserGroupInformation#getCurrentUser()}
 * with any Slider-specific post processing and exception handling
 * @return user info
 * @throws IOException on a failure to get the credentials
 */
public static UserGroupInformation getCurrentUser() throws IOException {

    try {
        UserGroupInformation currentUser = UserGroupInformation.getCurrentUser();
        return currentUser;
    } catch (IOException e) {
        log.info("Failed to get user info", e);
        throw e;
    }
}

From source file:org.apache.slider.core.launch.AbstractLauncher.java

License:Apache License

/**
 * This is critical for an insecure cluster -it passes
 * down the username to YARN, and so gives the code running
 * in containers the rights it needs to work with
 * data.//from  www  .j a  va2  s.  c  o  m
 * @throws IOException problems working with current user
 */
protected void propagateUsernameInInsecureCluster() throws IOException {
    //insecure cluster: propagate user name via env variable
    String userName = UserGroupInformation.getCurrentUser().getUserName();
    env.put(SliderKeys.HADOOP_USER_NAME, userName);
}

From source file:org.apache.slider.core.restclient.SliderURLConnectionFactory.java

License:Apache License

/**
 * Opens a url with read and connect timeouts
 *
 * @param url//from   ww  w .  j  a v  a  2 s.  c  o m
 *          URL to open
 * @param isSpnego
 *          whether the url should be authenticated via SPNEGO
 * @return URLConnection
 * @throws IOException
 * @throws AuthenticationException
 */
public URLConnection openConnection(URL url, boolean isSpnego) throws IOException, AuthenticationException {
    if (isSpnego) {
        log.debug("open AuthenticatedURL connection {}", url);
        UserGroupInformation.getCurrentUser().checkTGTAndReloginFromKeytab();
        final AuthenticatedURL.Token authToken = new AuthenticatedURL.Token();
        return new AuthenticatedURL(new KerberosUgiAuthenticator(), connConfigurator).openConnection(url,
                authToken);
    } else {
        log.debug("open URL connection {}", url);
        URLConnection connection = url.openConnection();
        if (connection instanceof HttpURLConnection) {
            connConfigurator.configure((HttpURLConnection) connection);
        }
        return connection;
    }
}

From source file:org.apache.slider.providers.ProviderUtils.java

License:Apache License

/**
 * build the log directory//  www . j  a  va  2s. c om
 * @return the log dir
 */
public String getLogdir() throws IOException {
    String logdir = System.getenv("LOGDIR");
    if (logdir == null) {
        logdir = SliderKeys.TMP_LOGDIR_PREFIX + UserGroupInformation.getCurrentUser().getShortUserName();
    }
    return logdir;
}

From source file:org.apache.slider.server.appmaster.rpc.RpcBinder.java

License:Apache License

public static SliderClusterProtocol getProxy(final Configuration conf, ApplicationReport application,
        final int rpcTimeout) throws IOException, SliderException, InterruptedException {

    String host = application.getHost();
    int port = application.getRpcPort();
    String address = host + ":" + port;
    if (host == null || 0 == port) {
        throw new SliderException(SliderExitCodes.EXIT_CONNECTIVITY_PROBLEM,
                "Slider instance " + application.getName() + " isn't providing a valid address for the"
                        + " Slider RPC protocol: " + address);
    }/*ww w . j ava  2s.  c  o m*/

    UserGroupInformation currentUser = UserGroupInformation.getCurrentUser();
    final UserGroupInformation newUgi = UserGroupInformation.createRemoteUser(currentUser.getUserName());
    final InetSocketAddress serviceAddr = NetUtils.createSocketAddrForHost(application.getHost(),
            application.getRpcPort());
    SliderClusterProtocol realProxy;

    log.debug("Connecting to {}", serviceAddr);
    if (UserGroupInformation.isSecurityEnabled()) {
        org.apache.hadoop.yarn.api.records.Token clientToAMToken = application.getClientToAMToken();
        Token<ClientToAMTokenIdentifier> token = ConverterUtils.convertFromYarn(clientToAMToken, serviceAddr);
        newUgi.addToken(token);
        realProxy = newUgi.doAs(new PrivilegedExceptionAction<SliderClusterProtocol>() {
            @Override
            public SliderClusterProtocol run() throws IOException {
                return connectToServer(serviceAddr, newUgi, conf, rpcTimeout);
            }
        });
    } else {
        return connectToServer(serviceAddr, newUgi, conf, rpcTimeout);
    }
    return realProxy;
}