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:co.cask.cdap.internal.app.namespace.DefaultNamespaceAdminTest.java

License:Apache License

@Test
public void testDataDirCreation() throws Exception {
    // create a namespace with default settings, validate that data dir exists and has
    namespaceAdmin.create(new NamespaceMeta.Builder().setName("dd1").build());

    Location homeDir = namespacedLocationFactory.get(new NamespaceId("dd1").toId());
    Location dataDir = homeDir.append(Constants.Dataset.DEFAULT_DATA_DIR);
    Location tempDir = homeDir.append(cConf.get(Constants.AppFabric.TEMP_DIR));
    Location streamsDir = homeDir.append(cConf.get(Constants.Stream.BASE_DIR));
    Location deletedDir = streamsDir.append(StreamUtils.DELETED);

    for (Location loc : new Location[] { homeDir, dataDir, tempDir, streamsDir, deletedDir }) {
        Assert.assertTrue(loc.exists());
        Assert.assertEquals(UserGroupInformation.getCurrentUser().getPrimaryGroupName(), loc.getGroup());
    }//from w  w w.  ja v a  2 s  .  c o  m

    // Determine a group other than the current user's primary group to use for testing
    // Note: this is only meaningful if the user running this test is in at least 2 groups
    String[] groups = UserGroupInformation.getCurrentUser().getGroupNames();
    Assert.assertTrue(groups.length > 0);
    String nsGroup = groups[groups.length - 1];

    // create and validate a namespace with a default settings except that a group is configured
    namespaceAdmin.create(new NamespaceMeta.Builder().setName("dd2").setGroupName(nsGroup).build());

    homeDir = namespacedLocationFactory.get(new NamespaceId("dd2").toId());
    dataDir = homeDir.append(Constants.Dataset.DEFAULT_DATA_DIR);
    tempDir = homeDir.append(cConf.get(Constants.AppFabric.TEMP_DIR));
    streamsDir = homeDir.append(cConf.get(Constants.Stream.BASE_DIR));
    deletedDir = streamsDir.append(StreamUtils.DELETED);

    Assert.assertTrue(homeDir.exists());
    Assert.assertEquals(nsGroup, homeDir.getGroup());
    for (Location loc : new Location[] { dataDir, tempDir, streamsDir, deletedDir }) {
        Assert.assertTrue(loc.exists());
        Assert.assertEquals(nsGroup, loc.getGroup());
        Assert.assertEquals("rwx", loc.getPermissions().substring(3, 6));
    }

    // for a custom root, but no group configured, the data dir inherits the group from the root
    String basePath = "/custom/dd3";
    homeDir = baseLocationFactory.create(basePath);
    Assert.assertTrue(homeDir.mkdirs());
    String homeGroup = homeDir.getGroup();

    namespaceAdmin.create(new NamespaceMeta.Builder().setName("dd3").setRootDirectory(basePath).build());

    dataDir = homeDir.append(Constants.Dataset.DEFAULT_DATA_DIR);
    tempDir = homeDir.append(cConf.get(Constants.AppFabric.TEMP_DIR));
    streamsDir = homeDir.append(cConf.get(Constants.Stream.BASE_DIR));
    deletedDir = streamsDir.append(StreamUtils.DELETED);

    for (Location loc : new Location[] { homeDir, dataDir, tempDir, streamsDir, deletedDir }) {
        Assert.assertTrue(loc.exists());
        Assert.assertEquals(homeGroup, loc.getGroup());
    }

    // for a custom root and a group configured, the data dir gets the custom group and group 'rwx'
    basePath = "/custom/dd4";
    homeDir = baseLocationFactory.create(basePath);
    Assert.assertTrue(homeDir.mkdirs());
    String homePermissions = homeDir.getPermissions();

    namespaceAdmin.create(new NamespaceMeta.Builder().setName("dd4").setGroupName(nsGroup)
            .setRootDirectory(basePath).build());

    dataDir = homeDir.append(Constants.Dataset.DEFAULT_DATA_DIR);
    tempDir = homeDir.append(cConf.get(Constants.AppFabric.TEMP_DIR));
    streamsDir = homeDir.append(cConf.get(Constants.Stream.BASE_DIR));
    deletedDir = streamsDir.append(StreamUtils.DELETED);

    // home dir should have existing group and permissions
    Assert.assertTrue(homeDir.exists());
    Assert.assertEquals(homeGroup, homeDir.getGroup());
    Assert.assertEquals(homePermissions, homeDir.getPermissions());
    for (Location loc : new Location[] { dataDir, tempDir, streamsDir, deletedDir }) {
        Assert.assertTrue(loc.exists());
        Assert.assertEquals(nsGroup, loc.getGroup());
        Assert.assertEquals("rwx", loc.getPermissions().substring(3, 6));
    }
}

From source file:co.cask.cdap.internal.app.runtime.batch.MapReduceRuntimeService.java

License:Apache License

/**
 * Creates a MapReduce {@link Job} instance.
 *
 * @param hadoopTmpDir directory for the "hadoop.tmp.dir" configuration
 *///w  w w  . j av  a  2  s . c  o  m
private Job createJob(File hadoopTmpDir) throws IOException {
    Job job = Job.getInstance(new Configuration(hConf));
    Configuration jobConf = job.getConfiguration();

    if (MapReduceTaskContextProvider.isLocal(jobConf)) {
        // Set the MR framework local directories inside the given tmp directory.
        // Setting "hadoop.tmp.dir" here has no effect due to Explore Service need to set "hadoop.tmp.dir"
        // as system property for Hive to work in local mode. The variable substitution of hadoop conf
        // gives system property the highest precedence.
        jobConf.set("mapreduce.cluster.local.dir", new File(hadoopTmpDir, "local").getAbsolutePath());
        jobConf.set("mapreduce.jobtracker.system.dir", new File(hadoopTmpDir, "system").getAbsolutePath());
        jobConf.set("mapreduce.jobtracker.staging.root.dir",
                new File(hadoopTmpDir, "staging").getAbsolutePath());
        jobConf.set("mapreduce.cluster.temp.dir", new File(hadoopTmpDir, "temp").getAbsolutePath());
    }

    if (UserGroupInformation.isSecurityEnabled()) {
        // If runs in secure cluster, this program runner is running in a yarn container, hence not able
        // to get authenticated with the history.
        jobConf.unset("mapreduce.jobhistory.address");
        jobConf.setBoolean(Job.JOB_AM_ACCESS_DISABLED, false);

        Credentials credentials = UserGroupInformation.getCurrentUser().getCredentials();
        LOG.info("Running in secure mode; adding all user credentials: {}", credentials.getAllTokens());
        job.getCredentials().addAll(credentials);
    }
    return job;
}

From source file:co.cask.cdap.internal.app.services.http.AuthorizationBootstrapperTest.java

License:Apache License

@Test
public void test() throws Exception {
    final Principal systemUser = new Principal(UserGroupInformation.getCurrentUser().getShortUserName(),
            Principal.PrincipalType.USER);
    // initial state: no privileges for system or admin users
    Predicate<EntityId> systemUserFilter = authorizationEnforcementService.createFilter(systemUser);
    Predicate<EntityId> adminUserFilter = authorizationEnforcementService.createFilter(ADMIN_USER);
    Assert.assertFalse(systemUserFilter.apply(instanceId));
    Assert.assertFalse(systemUserFilter.apply(NamespaceId.SYSTEM));
    Assert.assertFalse(adminUserFilter.apply(NamespaceId.DEFAULT));

    // privileges should be granted after running bootstrap
    authorizationBootstrapper.run();/*from  ww  w .  ja  v a  2s. com*/
    Tasks.waitFor(true, new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            Predicate<EntityId> systemUserFilter = authorizationEnforcementService.createFilter(systemUser);
            Predicate<EntityId> adminUserFilter = authorizationEnforcementService.createFilter(ADMIN_USER);
            return systemUserFilter.apply(instanceId) && systemUserFilter.apply(NamespaceId.SYSTEM)
                    && adminUserFilter.apply(NamespaceId.DEFAULT);
        }
    }, 10, TimeUnit.SECONDS);

    txManager.startAndWait();
    datasetService.startAndWait();
    waitForService(Constants.Service.DATASET_MANAGER);
    defaultNamespaceEnsurer.startAndWait();
    systemArtifactLoader.startAndWait();
    waitForService(defaultNamespaceEnsurer);
    waitForService(systemArtifactLoader);
    // ensure that the default namespace was created, and that the system user has privileges to access it
    Tasks.waitFor(true, new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            try {
                return namespaceQueryAdmin.exists(NamespaceId.DEFAULT);
            } catch (Exception e) {
                return false;
            }
        }
    }, 10, TimeUnit.SECONDS);
    Assert.assertTrue(defaultNamespaceEnsurer.isRunning());
    // ensure that the system artifact was deployed, and that the system user has privileges to access it
    // this will throw an ArtifactNotFoundException if the artifact was not deployed, and UnauthorizedException if
    // the user does not have required privileges
    Tasks.waitFor(true, new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            try {
                artifactRepository.getArtifact(SYSTEM_ARTIFACT.toId());
                return true;
            } catch (Exception e) {
                return false;
            }
        }
    }, 20, TimeUnit.SECONDS);
    Assert.assertTrue(systemArtifactLoader.isRunning());
    // ensure that system datasets can be created by the system user
    Dataset systemDataset = DatasetsUtil.getOrCreateDataset(dsFramework,
            NamespaceId.SYSTEM.dataset("system-dataset"), Table.class.getName(), DatasetProperties.EMPTY,
            Collections.<String, String>emptyMap(), this.getClass().getClassLoader());
    Assert.assertNotNull(systemDataset);
    // as part of bootstrapping, admin users were also granted admin privileges on the CDAP instance, so they can
    // create namespaces
    SecurityRequestContext.setUserId(ADMIN_USER.getName());
    namespaceAdmin.create(new NamespaceMeta.Builder().setName("success").build());
    SecurityRequestContext.setUserId("bob");
    try {
        namespaceAdmin.create(new NamespaceMeta.Builder().setName("failure").build());
        Assert.fail("Bob should not have been able to create a namespace since he is not an admin user");
    } catch (UnauthorizedException expected) {
        // expected
    }
}

From source file:co.cask.cdap.security.auth.context.MasterAuthenticationContext.java

License:Apache License

@Override
public Principal getPrincipal() {
    // When requests come in via rest endpoints, the userId is updated inside SecurityRequestContext, so give that
    // precedence.
    String userId = SecurityRequestContext.getUserId();
    // This userId can be null, when the master itself is asynchoronously updating the policy cache, since
    // during that process the router will not set the SecurityRequestContext. In that case, obtain the userId from
    // the UserGroupInformation, which will be the user that the master is running as.
    if (userId == null) {
        try {/* ww w  .  j a  va2  s  .  c  o  m*/
            userId = UserGroupInformation.getCurrentUser().getShortUserName();
        } catch (IOException e) {
            throw Throwables.propagate(e);
        }
    }
    return new Principal(userId, Principal.PrincipalType.USER);
}

From source file:co.cask.cdap.security.auth.context.ProgramContainerAuthenticationContext.java

License:Apache License

@Override
public Principal getPrincipal() {
    try {/*from w  ww.  j ava 2s  . c  om*/
        return new Principal(UserGroupInformation.getCurrentUser().getShortUserName(),
                Principal.PrincipalType.USER);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:co.cask.cdap.security.authorization.AuthorizationBootstrapper.java

License:Apache License

@Inject
AuthorizationBootstrapper(CConfiguration cConf, PrivilegesManager privilegesManager) {
    this.enabled = cConf.getBoolean(Constants.Security.ENABLED)
            && cConf.getBoolean(Constants.Security.Authorization.ENABLED);
    String currentUser;/* w w w . j av a  2s.c o m*/
    try {
        currentUser = UserGroupInformation.getCurrentUser().getShortUserName();
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
    this.systemUser = new Principal(currentUser, Principal.PrincipalType.USER);
    this.adminUsers = getAdminUsers(cConf);
    if (enabled && adminUsers.isEmpty()) {
        LOG.info("Admin users specified by {} is empty.", Constants.Security.Authorization.ADMIN_USERS);
    }
    this.instanceId = new InstanceId(cConf.get(Constants.INSTANCE_NAME));
    this.privilegesManager = privilegesManager;
}

From source file:co.cask.cdap.security.authorization.DefaultAuthorizationEnforcementServiceTest.java

License:Apache License

@Test
public void testSystemUser() throws Exception {
    CConfiguration cConfCopy = CConfiguration.copy(CCONF);
    Principal systemUser = new Principal(UserGroupInformation.getCurrentUser().getShortUserName(),
            Principal.PrincipalType.USER);
    cConfCopy.setInt(Constants.Security.Authorization.CACHE_REFRESH_INTERVAL_SECS, 1);
    try (AuthorizerInstantiator authorizerInstantiator = new AuthorizerInstantiator(cConfCopy,
            AUTH_CONTEXT_FACTORY)) {//from   www  .ja v  a  2  s  .  com
        Authorizer authorizer = authorizerInstantiator.get();
        DefaultAuthorizationEnforcementService authorizationEnforcementService = new DefaultAuthorizationEnforcementService(
                authorizer, cConfCopy, AUTH_CONTEXT);
        NamespaceId ns1 = new NamespaceId("ns1");
        InstanceId instanceId = new InstanceId(cConfCopy.get(Constants.INSTANCE_NAME));
        AuthorizationBootstrapper bootstrapper = new AuthorizationBootstrapper(cConfCopy, authorizer);
        bootstrapper.run();
        authorizationEnforcementService.startAndWait();
        try {
            waitForBootstrap(authorizationEnforcementService);
            authorizationEnforcementService.enforce(instanceId, systemUser, Action.ADMIN);
            authorizationEnforcementService.enforce(NamespaceId.SYSTEM, systemUser,
                    EnumSet.allOf(Action.class));
            Predicate<EntityId> filter = authorizationEnforcementService.createFilter(systemUser);
            Assert.assertFalse(filter.apply(ns1));
            Assert.assertTrue(filter.apply(instanceId));
            Assert.assertTrue(filter.apply(NamespaceId.SYSTEM));
        } finally {
            authorizationEnforcementService.stopAndWait();
        }
    }
}

From source file:co.cask.cdap.security.hive.HiveTokenUtils.java

License:Apache License

public static Credentials obtainToken(Credentials credentials) {
    ClassLoader hiveClassloader = ExploreUtils.getExploreClassloader();
    ClassLoader contextClassloader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(hiveClassloader);

    try {/*from  w  w  w  . j a  va2  s.c  o  m*/
        LOG.info("Obtaining delegation token for Hive");
        Class hiveConfClass = hiveClassloader.loadClass("org.apache.hadoop.hive.conf.HiveConf");
        Object hiveConf = hiveConfClass.newInstance();

        Class hiveClass = hiveClassloader.loadClass("org.apache.hadoop.hive.ql.metadata.Hive");
        @SuppressWarnings("unchecked")
        Method hiveGet = hiveClass.getMethod("get", hiveConfClass);
        Object hiveObject = hiveGet.invoke(null, hiveConf);

        String user = UserGroupInformation.getCurrentUser().getShortUserName();
        @SuppressWarnings("unchecked")
        Method getDelegationToken = hiveClass.getMethod("getDelegationToken", String.class, String.class);
        String tokenStr = (String) getDelegationToken.invoke(hiveObject, user, user);

        Token<DelegationTokenIdentifier> delegationToken = new Token<>();
        delegationToken.decodeFromUrlString(tokenStr);
        delegationToken.setService(new Text(HiveAuthFactory.HS2_CLIENT_TOKEN));
        LOG.info("Adding delegation token {} from MetaStore for service {} for user {}", delegationToken,
                delegationToken.getService(), user);
        credentials.addToken(delegationToken.getService(), delegationToken);
        return credentials;
    } catch (Exception e) {
        LOG.error("Exception when fetching delegation token from Hive MetaStore", e);
        throw Throwables.propagate(e);
    } finally {
        Thread.currentThread().setContextClassLoader(contextClassloader);
    }
}

From source file:co.cask.cdap.security.impersonation.CurrentUGIProvider.java

License:Apache License

@Override
public UserGroupInformation getConfiguredUGI(ImpersonationInfo impersonationInfo) throws IOException {
    return UserGroupInformation.getCurrentUser();
}

From source file:co.cask.cdap.security.impersonation.DefaultImpersonator.java

License:Apache License

private UserGroupInformation getUGI(NamespacedEntityId entityId, ImpersonatedOpType impersonatedOpType)
        throws IOException, NamespaceNotFoundException {
    // don't impersonate if kerberos isn't enabled OR if the operation is in the system namespace
    if (!kerberosEnabled || NamespaceId.SYSTEM.equals(entityId.getNamespaceId())) {
        return UserGroupInformation.getCurrentUser();
    }/*from  ww  w  .  ja  v a2 s  . co m*/
    try {
        ImpersonationInfo info = SecurityUtil.createImpersonationInfo(ownerAdmin, cConf, entityId,
                impersonatedOpType);
        LOG.debug("Impersonating principal {} for entity {}, keytab path is {}", info.getPrincipal(), entityId,
                info.getKeytabURI());
        return getUGI(info);
    } catch (Exception e) {
        Throwables.propagateIfInstanceOf(e, IOException.class);
        throw Throwables.propagate(e);
    }
}