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

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

Introduction

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

Prototype

public String getShortUserName() 

Source Link

Document

Get the user's login name.

Usage

From source file:org.apache.accumulo.server.util.ChangeSecret.java

License:Apache License

private static void checkHdfsAccessPermissions(FileStatus stat, FsAction mode) throws Exception {
    FsPermission perm = stat.getPermission();
    UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
    String user = ugi.getShortUserName();
    List<String> groups = Arrays.asList(ugi.getGroupNames());
    if (user.equals(stat.getOwner())) {
        if (perm.getUserAction().implies(mode)) {
            return;
        }/*from   www  .  j av a2 s  .c o m*/
    } else if (groups.contains(stat.getGroup())) {
        if (perm.getGroupAction().implies(mode)) {
            return;
        }
    } else {
        if (perm.getOtherAction().implies(mode)) {
            return;
        }
    }
    throw new Exception(String.format("Permission denied: user=%s, path=\"%s\":%s:%s:%s%s", user,
            stat.getPath(), stat.getOwner(), stat.getGroup(), stat.isDirectory() ? "d" : "-", perm));
}

From source file:org.apache.ambari.view.filebrowser.HdfsApi.java

License:Apache License

public static boolean checkAccessPermissions(FileStatus stat, FsAction mode, UserGroupInformation ugi) {
    FsPermission perm = stat.getPermission();
    String user = ugi.getShortUserName();
    List<String> groups = Arrays.asList(ugi.getGroupNames());
    if (user.equals(stat.getOwner())) {
        if (perm.getUserAction().implies(mode)) {
            return true;
        }/*from   w  w  w. ja  v a 2 s  .  com*/
    } else if (groups.contains(stat.getGroup())) {
        if (perm.getGroupAction().implies(mode)) {
            return true;
        }
    } else {
        if (perm.getOtherAction().implies(mode)) {
            return true;
        }
    }
    return false;
}

From source file:org.apache.ambari.view.slider.SliderAppsViewControllerImpl.java

License:Apache License

private <T> T invokeHDFSClientRunnable(final HDFSClientRunnable<T> runnable,
        final Map<String, String> hadoopConfigs) throws IOException, InterruptedException {
    ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    try {//ww  w  . ja  v a2s . c om
        boolean securityEnabled = Boolean.valueOf(hadoopConfigs.get("security_enabled"));
        final HdfsConfiguration hdfsConfiguration = new HdfsConfiguration();
        for (Entry<String, String> entry : hadoopConfigs.entrySet()) {
            hdfsConfiguration.set(entry.getKey(), entry.getValue());
        }
        UserGroupInformation.setConfiguration(hdfsConfiguration);
        UserGroupInformation sliderUser;
        String loggedInUser = getUserToRunAs(hadoopConfigs);
        if (securityEnabled) {
            String viewPrincipal = getViewParameterValue(PARAM_VIEW_PRINCIPAL);
            String viewPrincipalKeytab = getViewParameterValue(PARAM_VIEW_PRINCIPAL_KEYTAB);
            UserGroupInformation ambariUser = UserGroupInformation
                    .loginUserFromKeytabAndReturnUGI(viewPrincipal, viewPrincipalKeytab);
            if (loggedInUser.equals(ambariUser.getShortUserName())) {
                // HDFS throws exception when caller tries to impresonate themselves.
                // User: admin@EXAMPLE.COM is not allowed to impersonate admin
                sliderUser = ambariUser;
            } else {
                sliderUser = UserGroupInformation.createProxyUser(loggedInUser, ambariUser);
            }
        } else {
            sliderUser = UserGroupInformation.getBestUGI(null, loggedInUser);
        }
        try {
            T value = sliderUser.doAs(new PrivilegedExceptionAction<T>() {
                @Override
                public T run() throws Exception {
                    String fsPath = hadoopConfigs.get("fs.defaultFS");
                    FileSystem fs = FileSystem.get(URI.create(fsPath), hdfsConfiguration);
                    try {
                        return runnable.run(fs);
                    } finally {
                        fs.close();
                    }
                }
            });
            return value;
        } catch (UndeclaredThrowableException e) {
            throw e;
        }
    } finally {
        Thread.currentThread().setContextClassLoader(currentClassLoader);
    }
}

From source file:org.apache.ambari.view.slider.SliderAppsViewControllerImpl.java

License:Apache License

private <T> T invokeSliderClientRunnable(final SliderClientContextRunnable<T> runnable)
        throws IOException, InterruptedException, YarnException {
    ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    try {/*from  w w  w. j  a v a2s . c o m*/
        boolean securityEnabled = Boolean.valueOf(getHadoopConfigs().get("security_enabled"));
        UserGroupInformation.setConfiguration(getSliderClientConfiguration());
        UserGroupInformation sliderUser;
        String loggedInUser = getUserToRunAs();
        if (securityEnabled) {
            String viewPrincipal = getViewParameterValue(PARAM_VIEW_PRINCIPAL);
            String viewPrincipalKeytab = getViewParameterValue(PARAM_VIEW_PRINCIPAL_KEYTAB);
            UserGroupInformation ambariUser = UserGroupInformation
                    .loginUserFromKeytabAndReturnUGI(viewPrincipal, viewPrincipalKeytab);
            if (loggedInUser.equals(ambariUser.getShortUserName())) {
                // HDFS throws exception when caller tries to impresonate themselves.
                // User: admin@EXAMPLE.COM is not allowed to impersonate admin
                sliderUser = ambariUser;
            } else {
                sliderUser = UserGroupInformation.createProxyUser(loggedInUser, ambariUser);
            }
        } else {
            sliderUser = UserGroupInformation.getBestUGI(null, loggedInUser);
        }
        try {
            T value = sliderUser.doAs(new PrivilegedExceptionAction<T>() {
                @Override
                public T run() throws Exception {
                    final SliderClient sliderClient = createSliderClient();
                    try {
                        return runnable.run(sliderClient);
                    } finally {
                        destroySliderClient(sliderClient);
                    }
                }
            });
            return value;
        } catch (UndeclaredThrowableException e) {
            Throwable cause = e.getCause();
            if (cause instanceof YarnException) {
                YarnException ye = (YarnException) cause;
                throw ye;
            }
            throw e;
        }
    } finally {
        Thread.currentThread().setContextClassLoader(currentClassLoader);
    }
}

From source file:org.apache.atlas.AtlasBaseClient.java

License:Apache License

protected AtlasBaseClient(UserGroupInformation ugi, String[] baseUrls) {
    this(ugi, ugi.getShortUserName(), baseUrls);
}

From source file:org.apache.atlas.AtlasClient.java

License:Apache License

private AtlasClient(UserGroupInformation ugi, String[] baseUrls) {
    this(ugi, ugi.getShortUserName(), baseUrls);
}

From source file:org.apache.atlas.hive.bridge.HiveMetaStoreBridge.java

License:Apache License

public static void main(String[] argv) throws Exception {

    Configuration atlasConf = ApplicationProperties.get();
    String atlasEndpoint = atlasConf.getString(ATLAS_ENDPOINT, DEFAULT_DGI_URL);
    AtlasClient atlasClient;/*from www.java  2 s  .c o  m*/

    if (!AuthenticationUtil.isKerberosAuthicationEnabled()) {
        String[] basicAuthUsernamePassword = AuthenticationUtil.getBasicAuthenticationInput();
        atlasClient = new AtlasClient(new String[] { atlasEndpoint }, basicAuthUsernamePassword);
    } else {
        UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
        atlasClient = new AtlasClient(ugi, ugi.getShortUserName(), atlasEndpoint);
    }

    HiveMetaStoreBridge hiveMetaStoreBridge = new HiveMetaStoreBridge(new HiveConf(), atlasClient);
    hiveMetaStoreBridge.registerHiveDataModel();
    hiveMetaStoreBridge.importHiveMetadata();
}

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

License:Apache License

/**
 * Returns the user. Order of preference:
 * 1. Given userName/*from  www. jav a 2 s.co m*/
 * 2. ugi.getShortUserName()
 * 3. UserGroupInformation.getCurrentUser().getShortUserName()
 * 4. System.getProperty("user.name")
 */

public static String getUser(String userName, UserGroupInformation ugi) {
    if (StringUtils.isNotEmpty(userName)) {
        return userName;
    }

    if (ugi != null && StringUtils.isNotEmpty(ugi.getShortUserName())) {
        return ugi.getShortUserName();
    }

    try {
        return UserGroupInformation.getCurrentUser().getShortUserName();
    } catch (IOException e) {
        LOG.warn("Failed for UserGroupInformation.getCurrentUser()");
        return System.getProperty("user.name");
    }
}

From source file:org.apache.atlas.security.SecureClientUtils.java

License:Apache License

public static URLConnectionClientHandler getClientConnectionHandler(DefaultClientConfig config,
        org.apache.commons.configuration.Configuration clientConfig, String doAsUser,
        final UserGroupInformation ugi) {
    config.getProperties().put(URLConnectionClientHandler.PROPERTY_HTTP_URL_CONNECTION_SET_METHOD_WORKAROUND,
            true);//from w  w  w . j  av  a  2 s  .  c  om
    Configuration conf = new Configuration();
    conf.addResource(conf.get(SSLFactory.SSL_CLIENT_CONF_KEY, SecurityProperties.SSL_CLIENT_PROPERTIES));
    UserGroupInformation.setConfiguration(conf);
    final ConnectionConfigurator connConfigurator = newConnConfigurator(conf);
    String authType = "simple";
    if (clientConfig != null) {
        authType = clientConfig.getString("atlas.http.authentication.type", "simple");
    }
    Authenticator authenticator = new PseudoDelegationTokenAuthenticator();
    if (!authType.equals("simple")) {
        authenticator = new KerberosDelegationTokenAuthenticator();
    }
    authenticator.setConnectionConfigurator(connConfigurator);
    final DelegationTokenAuthenticator finalAuthenticator = (DelegationTokenAuthenticator) authenticator;
    final DelegationTokenAuthenticatedURL.Token token = new DelegationTokenAuthenticatedURL.Token();
    HttpURLConnectionFactory httpURLConnectionFactory = null;
    try {
        UserGroupInformation ugiToUse = ugi != null ? ugi : UserGroupInformation.getCurrentUser();
        final UserGroupInformation actualUgi = (ugiToUse
                .getAuthenticationMethod() == UserGroupInformation.AuthenticationMethod.PROXY)
                        ? ugiToUse.getRealUser()
                        : ugiToUse;
        LOG.info("Real User: {}, is from ticket cache? {}", actualUgi, actualUgi.isLoginTicketBased());
        if (StringUtils.isEmpty(doAsUser)) {
            doAsUser = actualUgi.getShortUserName();
        }
        LOG.info("doAsUser: {}", doAsUser);
        final String finalDoAsUser = doAsUser;
        httpURLConnectionFactory = new HttpURLConnectionFactory() {
            @Override
            public HttpURLConnection getHttpURLConnection(final URL url) throws IOException {
                try {
                    return actualUgi.doAs(new PrivilegedExceptionAction<HttpURLConnection>() {
                        @Override
                        public HttpURLConnection run() throws Exception {
                            try {
                                return new DelegationTokenAuthenticatedURL(finalAuthenticator, connConfigurator)
                                        .openConnection(url, token, finalDoAsUser);
                            } catch (Exception e) {
                                throw new IOException(e);
                            }
                        }
                    });
                } catch (Exception e) {
                    if (e instanceof IOException) {
                        throw (IOException) e;
                    } else {
                        throw new IOException(e);
                    }
                }
            }
        };
    } catch (IOException e) {
        LOG.warn("Error obtaining user", e);
    }

    return new URLConnectionClientHandler(httpURLConnectionFactory);
}

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

License:Apache License

@Override
public UserGroupInformation createAndLoginUser(final Map<String, ?> properties) throws IOException {
    final Configuration conf = new Configuration();
    conf.set(CommonConfigurationKeys.HADOOP_SECURITY_AUTHENTICATION,
            UserGroupInformation.AuthenticationMethod.KERBEROS.toString());
    UserGroupInformation.setConfiguration(conf);

    final String keytab = (String) properties.get(DrillProperties.KEYTAB);
    final boolean assumeSubject = properties.containsKey(DrillProperties.KERBEROS_FROM_SUBJECT)
            && Boolean.parseBoolean((String) properties.get(DrillProperties.KERBEROS_FROM_SUBJECT));
    try {//  ww w .j  a v a2  s  .c o m
        final UserGroupInformation ugi;
        if (assumeSubject) {
            ugi = UserGroupInformation.getUGIFromSubject(Subject.getSubject(AccessController.getContext()));
            logger.debug("Assuming subject for {}.", ugi.getShortUserName());
        } else {
            if (keytab != null) {
                ugi = UserGroupInformation
                        .loginUserFromKeytabAndReturnUGI((String) properties.get(DrillProperties.USER), keytab);
                logger.debug("Logged in {} using keytab.", ugi.getShortUserName());
            } else {
                // includes Kerberos ticket login
                ugi = UserGroupInformation.getCurrentUser();
                logger.debug("Logged in {} using ticket.", ugi.getShortUserName());
            }
        }
        return ugi;
    } catch (final IOException e) {
        logger.debug("Login failed.", e);
        final Throwable cause = e.getCause();
        if (cause instanceof LoginException) {
            throw new SaslException("Failed to login.", cause);
        }
        throw new SaslException("Unexpected failure trying to login.", cause);
    }
}