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.sentry.provider.db.generic.tools.PermissionsMigrationToolCommon.java

License:Apache License

private void migrateSentryServiceConfig() throws Exception {
    Configuration conf = getSentryConf();
    String component = getComponent(conf);
    String serviceName = getServiceName(conf);
    GenericPrivilegeConverter converter = new GenericPrivilegeConverter(component, serviceName, false);

    // instantiate a client for sentry service.  This sets the ugi, so must
    // be done before getting the ugi below.
    try (SentryGenericServiceClient client = SentryGenericServiceClientFactory.create(getSentryConf())) {
        UserGroupInformation ugi = UserGroupInformation.getLoginUser();
        String requestorName = ugi.getShortUserName();

        for (TSentryRole r : client.listAllRoles(requestorName, component)) {
            for (TSentryPrivilege p : client.listAllPrivilegesByRoleName(requestorName, r.getRoleName(),
                    component, serviceName)) {

                Collection<String> privileges = Collections.singleton(converter.toString(p));
                Collection<String> migrated = transformPrivileges(privileges);
                if (!migrated.isEmpty()) {
                    LOGGER.info("{} For role {} migrating privileges from {} to {}", getDryRunMessage(),
                            r.getRoleName(), privileges, migrated);

                    if (!dryRun) {
                        Collection<TSentryPrivilege> tmp = new ArrayList<>();
                        for (String perm : migrated) {
                            tmp.add(converter.fromString(perm));
                        }/*  ww w  . j  a  va 2s .c om*/

                        /*
                         * Note that it is not possible to provide transactional (all-or-nothing) behavior for these configuration
                         * changes since the Sentry client/server protocol does not support. e.g. under certain failure conditions
                         * like crash of Sentry server or network disconnect between client/server, it is possible that the migration
                         * can not complete but can also not be rolled back. Hence this migration tool relies on the fact that privilege
                         * grant/revoke operations are idempotent and hence re-execution of the migration tool will fix any inconsistency
                         * due to such failures.
                         **/
                        for (TSentryPrivilege x : tmp) { // grant new permissions
                            client.grantPrivilege(requestorName, r.getRoleName(), component, x);
                        }

                        // Revoke old permission (only if not part of migrated permissions)
                        if (!tmp.contains(p)) {
                            client.revokePrivilege(requestorName, r.getRoleName(), component, p);
                        }
                    }
                }
            }
        }
    }
}

From source file:org.apache.sentry.provider.db.generic.tools.SentryConfigToolIndexer.java

License:Apache License

/**
 * Processes the necessary command based on the arguments parsed earlier.
 * @throws Exception//from  ww  w  .  j  a v a2s . c o  m
 */
public void run() throws Exception {
    String component = HBASE_INDEXER;
    Configuration conf = getSentryConf();

    String service = conf.get(SERVICE_NAME, getServiceName());

    if (service == null) {
        throw new IllegalArgumentException(
                "Service was not defined. Please, use -s command option, or sentry.provider.backend.generic.service-name configuration entry.");
    }

    LOGGER.info(String.format("Context: component=%s, service=%s", component, service));
    // instantiate a solr client for sentry service.  This sets the ugi, so must
    // be done before getting the ugi below.
    try (SentryGenericServiceClient client = SentryGenericServiceClientFactory.create(conf)) {
        UserGroupInformation ugi = UserGroupInformation.getLoginUser();
        String requestorName = ugi.getShortUserName();

        convertINIToSentryServiceCmds(component, service, requestorName, conf, client, getPolicyFile(),
                getValidate(), getImportPolicy(), getCheckCompat());
    }
}

From source file:org.apache.sentry.provider.db.generic.tools.SentryShellKafka.java

License:Apache License

@Override
public void run() throws Exception {
    Command command = null;//from  w w  w .  j ava2s .  c om
    String component = AuthorizationComponent.KAFKA;
    Configuration conf = getSentryConf();

    String service = conf.get(KAFKA_SERVICE_NAME, "kafka1");
    SentryGenericServiceClient client = SentryGenericServiceClientFactory.create(conf);
    UserGroupInformation ugi = UserGroupInformation.getLoginUser();
    String requestorName = ugi.getShortUserName();

    if (isCreateRole) {
        command = new CreateRoleCmd(roleName, component);
    } else if (isDropRole) {
        command = new DropRoleCmd(roleName, component);
    } else if (isAddRoleGroup) {
        command = new AddRoleToGroupCmd(roleName, groupName, component);
    } else if (isDeleteRoleGroup) {
        command = new DeleteRoleFromGroupCmd(roleName, groupName, component);
    } else if (isGrantPrivilegeRole) {
        command = new GrantPrivilegeToRoleCmd(roleName, component, privilegeStr,
                new KafkaTSentryPrivilegeConverter(component, service));
    } else if (isRevokePrivilegeRole) {
        command = new RevokePrivilegeFromRoleCmd(roleName, component, privilegeStr,
                new KafkaTSentryPrivilegeConverter(component, service));
    } else if (isListRole) {
        command = new ListRolesCmd(groupName, component);
    } else if (isListPrivilege) {
        command = new ListPrivilegesByRoleCmd(roleName, component, service,
                new KafkaTSentryPrivilegeConverter(component, service));
    }

    // check the requestor name
    if (StringUtils.isEmpty(requestorName)) {
        // The exception message will be recorded in log file.
        throw new Exception("The requestor name is empty.");
    }

    if (command != null) {
        command.execute(client, requestorName);
    }
}

From source file:org.apache.sentry.provider.db.generic.tools.SentryShellSolr.java

License:Apache License

@Override
public void run() throws Exception {
    Command command = null;/* w w  w . ja va  2 s  .c o  m*/
    String component = "SOLR";
    Configuration conf = getSentryConf();

    String service = conf.get(SOLR_SERVICE_NAME, "service1");
    SentryGenericServiceClient client = SentryGenericServiceClientFactory.create(conf);
    UserGroupInformation ugi = UserGroupInformation.getLoginUser();
    String requestorName = ugi.getShortUserName();

    if (isCreateRole) {
        command = new CreateRoleCmd(roleName, component);
    } else if (isDropRole) {
        command = new DropRoleCmd(roleName, component);
    } else if (isAddRoleGroup) {
        command = new AddRoleToGroupCmd(roleName, groupName, component);
    } else if (isDeleteRoleGroup) {
        command = new DeleteRoleFromGroupCmd(roleName, groupName, component);
    } else if (isGrantPrivilegeRole) {
        command = new GrantPrivilegeToRoleCmd(roleName, component, privilegeStr,
                new SolrTSentryPrivilegeConverter(component, service));
    } else if (isRevokePrivilegeRole) {
        command = new RevokePrivilegeFromRoleCmd(roleName, component, privilegeStr,
                new SolrTSentryPrivilegeConverter(component, service));
    } else if (isListRole) {
        command = new ListRolesCmd(groupName, component);
    } else if (isListPrivilege) {
        command = new ListPrivilegesByRoleCmd(roleName, component, service,
                new SolrTSentryPrivilegeConverter(component, service));
    }

    // check the requestor name
    if (StringUtils.isEmpty(requestorName)) {
        // The exception message will be recorded in log file.
        throw new Exception("The requestor name is empty.");
    }

    if (command != null) {
        command.execute(client, requestorName);
    }
}

From source file:org.apache.sentry.shell.SentryCli.java

License:Apache License

/**
 * Initialize CLI//from   w  ww  .jav a  2 s .c om
 */
private void init() {
    Map<String, String> env = System.getenv();
    String log4jconf = cmd.getOptionValue(LOG4J_CONF);
    if (log4jconf != null && log4jconf.length() > 0) {
        Properties log4jProperties = new Properties();

        // Firstly load log properties from properties file
        try (FileInputStream istream = new FileInputStream(log4jconf)) {
            log4jProperties.load(istream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        PropertyConfigurator.configure(log4jProperties);
    }

    String host = cmd.getOptionValue(hostOpt);
    if (host == null) {
        host = env.get(hostEnv);
    }

    String pathConf = cmd.getOptionValue(configOpt);
    if (pathConf == null) {
        pathConf = env.get(configEnv);
    }
    if (host == null && pathConf == null) {
        host = localhost + ":" + defaultPort;
    }

    Configuration conf = new Configuration();

    if (pathConf != null) {
        conf.addResource(new Path(pathConf), true);
    } else {
        conf.set(SECURITY_MODE, SECURITY_MODE_NONE);
    }

    if (host != null) {
        conf.set(ApiConstants.ClientConfig.SERVER_RPC_ADDRESS, host);
    }

    requestorName = cmd.getOptionValue(userOpt);
    if (requestorName == null) {
        requestorName = env.get(userEnv);
    }
    if (requestorName == null) {

        UserGroupInformation ugi = null;
        try {
            ugi = UserGroupInformation.getLoginUser();
        } catch (IOException e) {
            e.printStackTrace();
        }
        requestorName = ugi.getShortUserName();
    }

    try {
        sentryClient = SentryServiceClientFactory.create(conf);
        sentryGenericClient = SentryGenericServiceClientFactory.create(conf);
    } catch (Exception e) {
        System.out.println("Failed to connect to Sentry server: " + e.toString());
    }
}

From source file:org.apache.sentry.tests.e2e.kafka.AbstractKafkaSentryTestBase.java

License:Apache License

public static void setUserGroups() throws Exception {
    for (String user : StaticUserGroupRole.getUsers()) {
        Set<String> groups = StaticUserGroupRole.getGroups(user);
        policyFile.addGroupsToUser(user, groups.toArray(new String[groups.size()]));
    }/* w  w  w. ja va 2s .  c om*/
    UserGroupInformation loginUser = UserGroupInformation.getLoginUser();
    policyFile.addGroupsToUser(loginUser.getShortUserName(), loginUser.getGroupNames());

    policyFile.write(policyFilePath);
}

From source file:org.apache.sentry.tests.e2e.sqoop.AbstractSqoopSentryTestBase.java

License:Apache License

public static void setUserGroups() throws Exception {
    for (String user : StaticUserGroupRole.getUsers()) {
        Set<String> groups = StaticUserGroupRole.getGroups(user);
        policyFile.addGroupsToUser(user, groups.toArray(new String[groups.size()]));
    }/* ww  w  .j a  v a2s.  c o m*/
    policyFile.addGroupsToUser(ADMIN_USER, ADMIN_GROUP);
    UserGroupInformation loginUser = UserGroupInformation.getLoginUser();
    policyFile.addGroupsToUser(loginUser.getShortUserName(), loginUser.getGroupNames());
    policyFile.write(policyFilePath);
}

From source file:org.apache.solr.security.DelegationTokenKerberosFilter.java

License:Apache License

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    // HttpClient 4.4.x throws NPE if query string is null and parsed through URLEncodedUtils.
    // See HTTPCLIENT-1746 and HADOOP-12767
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String queryString = httpRequest.getQueryString();
    final String nonNullQueryString = queryString == null ? "" : queryString;
    HttpServletRequest requestNonNullQueryString = new HttpServletRequestWrapper(httpRequest) {
        @Override//from ww w .  ja  va  2  s .  c  o  m
        public String getQueryString() {
            return nonNullQueryString;
        }
    };

    // include Impersonator User Name in case someone (e.g. logger) wants it
    FilterChain filterChainWrapper = new FilterChain() {
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
                throws IOException, ServletException {
            HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;

            UserGroupInformation ugi = HttpUserGroupInformation.get();
            if (ugi != null
                    && ugi.getAuthenticationMethod() == UserGroupInformation.AuthenticationMethod.PROXY) {
                UserGroupInformation realUserUgi = ugi.getRealUser();
                if (realUserUgi != null) {
                    httpRequest.setAttribute(KerberosPlugin.IMPERSONATOR_USER_NAME,
                            realUserUgi.getShortUserName());
                }
            }
            filterChain.doFilter(servletRequest, servletResponse);
        }
    };

    super.doFilter(requestNonNullQueryString, response, filterChainWrapper);
}

From source file:org.apache.sqoop.security.authorization.AuthorizationEngine.java

License:Apache License

private static void checkPrivilege(MPrivilege... privileges) {
    AuthorizationHandler handler = AuthorizationManager.getAuthorizationHandler();
    UserGroupInformation user = HttpUserGroupInformation.get();
    String user_name = user == null ? StringUtils.EMPTY : user.getShortUserName();
    MPrincipal principal = new MPrincipal(user_name, MPrincipal.TYPE.USER);

    // SQOOP-2256: Hack code, do not check privilege when the user is the creator
    // If the user is the owner/creator of this resource, then privilege will
    // not be checked. It is a hack code for the time being. The concept of
    // "Owner" will be added in the future and this code will be removed.
    ArrayList<MPrivilege> privilegesNeedCheck = new ArrayList<MPrivilege>();
    for (MPrivilege privilege : privileges) {
        Repository repository = RepositoryManager.getInstance().getRepository();
        if (MResource.TYPE.LINK.name().equalsIgnoreCase(privilege.getResource().getType())) {
            MLink link = repository.findLink(Long.valueOf(privilege.getResource().getName()));
            if (!user_name.equals(link.getCreationUser())) {
                privilegesNeedCheck.add(privilege);
            }// w  ww .ja v  a2 s. c o m
        } else if (MResource.TYPE.JOB.name().equalsIgnoreCase(privilege.getResource().getType())) {
            MJob job = repository.findJob(Long.valueOf(privilege.getResource().getName()));
            if (!user_name.equals(job.getCreationUser())) {
                privilegesNeedCheck.add(privilege);
            }
        } else {
            privilegesNeedCheck.add(privilege);
        }
    }

    handler.checkPrivileges(principal, privilegesNeedCheck);
}

From source file:org.apache.tajo.master.querymaster.QueryMasterTask.java

License:Apache License

/**
 * It initializes the final output and staging directory and sets
 * them to variables./*from   ww  w  .j a  va  2  s  .c o  m*/
 */
public static Path initStagingDir(TajoConf conf, String queryId, QueryContext context) throws IOException {

    String realUser;
    String currentUser;
    UserGroupInformation ugi;
    ugi = UserGroupInformation.getLoginUser();
    realUser = ugi.getShortUserName();
    currentUser = UserGroupInformation.getCurrentUser().getShortUserName();

    FileSystem fs;
    Path stagingDir;

    ////////////////////////////////////////////
    // Create Output Directory
    ////////////////////////////////////////////

    String outputPath = context.get(QueryVars.OUTPUT_TABLE_PATH, "");
    if (context.isCreateTable() || context.isInsert()) {
        if (outputPath == null || outputPath.isEmpty()) {
            // hbase
            stagingDir = new Path(TajoConf.getDefaultRootStagingDir(conf), queryId);
        } else {
            stagingDir = StorageUtil.concatPath(context.getOutputPath(), TMP_STAGING_DIR_PREFIX, queryId);
        }
    } else {
        stagingDir = new Path(TajoConf.getDefaultRootStagingDir(conf), queryId);
    }

    // initializ
    fs = stagingDir.getFileSystem(conf);

    if (fs.exists(stagingDir)) {
        throw new IOException("The staging directory '" + stagingDir + "' already exists");
    }
    fs.mkdirs(stagingDir, new FsPermission(STAGING_DIR_PERMISSION));
    FileStatus fsStatus = fs.getFileStatus(stagingDir);
    String owner = fsStatus.getOwner();

    if (!owner.isEmpty() && !(owner.equals(currentUser) || owner.equals(realUser))) {
        throw new IOException("The ownership on the user's query " + "directory " + stagingDir
                + " is not as expected. " + "It is owned by " + owner + ". The directory must "
                + "be owned by the submitter " + currentUser + " or " + "by " + realUser);
    }

    if (!fsStatus.getPermission().equals(STAGING_DIR_PERMISSION)) {
        LOG.info("Permissions on staging directory " + stagingDir + " are " + "incorrect: "
                + fsStatus.getPermission() + ". Fixing permissions " + "to correct value "
                + STAGING_DIR_PERMISSION);
        fs.setPermission(stagingDir, new FsPermission(STAGING_DIR_PERMISSION));
    }

    Path stagingResultDir = new Path(stagingDir, TajoConstants.RESULT_DIR_NAME);
    fs.mkdirs(stagingResultDir);

    return stagingDir;
}