Java Code Examples for org.apache.hadoop.security.UserGroupInformation.getShortUserName()

The following are Jave code examples for showing how to use getShortUserName() of the org.apache.hadoop.security.UserGroupInformation class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: hadoop   File: TestWebDelegationToken.java   View Source Code Vote up 6 votes
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
  UserGroupInformation ugi = HttpUserGroupInformation.get();
  if (ugi != null) {
    String ret = "remoteuser=" + req.getRemoteUser() + ":ugi=" +
        ugi.getShortUserName();
    if (ugi.getAuthenticationMethod() ==
        UserGroupInformation.AuthenticationMethod.PROXY) {
      ret = "realugi=" + ugi.getRealUser().getShortUserName() + ":" + ret;
    }
    resp.setStatus(HttpServletResponse.SC_OK);
    resp.getWriter().write(ret);
  } else {
    resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
  }
}
 
Example 2
Project: hadoop   File: TestContainerManagerRecovery.java   View Source Code Vote up 6 votes
private StartContainersResponse startContainer(Context context,
    final ContainerManagerImpl cm, ContainerId cid,
    ContainerLaunchContext clc, LogAggregationContext logAggregationContext)
        throws Exception {
  UserGroupInformation user = UserGroupInformation.createRemoteUser(
      cid.getApplicationAttemptId().toString());
  StartContainerRequest scReq = StartContainerRequest.newInstance(
      clc, TestContainerManager.createContainerToken(cid, 0,
          context.getNodeId(), user.getShortUserName(),
          context.getContainerTokenSecretManager(), logAggregationContext));
  final List<StartContainerRequest> scReqList =
      new ArrayList<StartContainerRequest>();
  scReqList.add(scReq);
  NMTokenIdentifier nmToken = new NMTokenIdentifier(
      cid.getApplicationAttemptId(), context.getNodeId(),
      user.getShortUserName(),
      context.getNMTokenSecretManager().getCurrentKey().getKeyId());
  user.addTokenIdentifier(nmToken);
  return user.doAs(new PrivilegedExceptionAction<StartContainersResponse>() {
    @Override
    public StartContainersResponse run() throws Exception {
      return cm.startContainers(
          StartContainersRequest.newInstance(scReqList));
    }
  });
}
 
Example 3
Project: ditb   File: FSUtils.java   View Source Code Vote up 6 votes
/**
 * Throw an exception if an action is not permitted by a user on a file.
 *
 * @param ugi
 *          the user
 * @param file
 *          the file
 * @param action
 *          the action
 */
public static void checkAccess(UserGroupInformation ugi, FileStatus file,
    FsAction action) throws AccessDeniedException {
  if (ugi.getShortUserName().equals(file.getOwner())) {
    if (file.getPermission().getUserAction().implies(action)) {
      return;
    }
  } else if (contains(ugi.getGroupNames(), file.getGroup())) {
    if (file.getPermission().getGroupAction().implies(action)) {
      return;
    }
  } else if (file.getPermission().getOtherAction().implies(action)) {
    return;
  }
  throw new AccessDeniedException("Permission denied:" + " action=" + action
      + " path=" + file.getPath() + " user=" + ugi.getShortUserName());
}
 
Example 4
Project: hadoop   File: ClientRMService.java   View Source Code Vote up 6 votes
private String checkReservationACLs(String queueName, String auditConstant)
    throws YarnException {
  UserGroupInformation callerUGI;
  try {
    callerUGI = UserGroupInformation.getCurrentUser();
  } catch (IOException ie) {
    RMAuditLogger.logFailure("UNKNOWN", auditConstant, queueName,
        "ClientRMService", "Error getting UGI");
    throw RPCUtil.getRemoteException(ie);
  }
  // Check if user has access on the managed queue
  if (!queueACLsManager.checkAccess(callerUGI, QueueACL.SUBMIT_APPLICATIONS,
      queueName)) {
    RMAuditLogger.logFailure(
        callerUGI.getShortUserName(),
        auditConstant,
        "User doesn't have permissions to "
            + QueueACL.SUBMIT_APPLICATIONS.toString(), "ClientRMService",
        AuditConstants.UNAUTHORIZED_USER);
    throw RPCUtil.getRemoteException(new AccessControlException("User "
        + callerUGI.getShortUserName() + " cannot perform operation "
        + QueueACL.SUBMIT_APPLICATIONS.name() + " on queue" + queueName));
  }
  return callerUGI.getShortUserName();
}
 
Example 5
Project: hadoop   File: FileSystem.java   View Source Code Vote up 6 votes
/**
 * This method provides the default implementation of
 * {@link #access(Path, FsAction)}.
 *
 * @param stat FileStatus to check
 * @param mode type of access to check
 * @throws IOException for any error
 */
@InterfaceAudience.Private
static void checkAccessPermissions(FileStatus stat, FsAction mode)
    throws IOException {
  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;
    }
  } else if (groups.contains(stat.getGroup())) {
    if (perm.getGroupAction().implies(mode)) {
      return;
    }
  } else {
    if (perm.getOtherAction().implies(mode)) {
      return;
    }
  }
  throw new AccessControlException(String.format(
    "Permission denied: user=%s, path=\"%s\":%s:%s:%s%s", user, stat.getPath(),
    stat.getOwner(), stat.getGroup(), stat.isDirectory() ? "d" : "-", perm));
}
 
Example 6
Project: hadoop   File: JobACLsManager.java   View Source Code Vote up 6 votes
/**
 * If authorization is enabled, checks whether the user (in the callerUGI)
 * is authorized to perform the operation specified by 'jobOperation' on
 * the job by checking if the user is jobOwner or part of job ACL for the
 * specific job operation.
 * <ul>
 * <li>The owner of the job can do any operation on the job</li>
 * <li>For all other users/groups job-acls are checked</li>
 * </ul>
 * @param callerUGI
 * @param jobOperation
 * @param jobOwner
 * @param jobACL
 */
public boolean checkAccess(UserGroupInformation callerUGI,
    JobACL jobOperation, String jobOwner, AccessControlList jobACL) {

  if (LOG.isDebugEnabled()) {
    LOG.debug("checkAccess job acls, jobOwner: " + jobOwner + " jobacl: "
        + jobOperation.toString() + " user: " + callerUGI.getShortUserName());
  }
  String user = callerUGI.getShortUserName();
  if (!areACLsEnabled()) {
    return true;
  }

  // Allow Job-owner for any operation on the job
  if (isMRAdmin(callerUGI)
      || user.equals(jobOwner)
      || jobACL.isUserAllowed(callerUGI)) {
    return true;
  }

  return false;
}
 
Example 7
Project: hadoop   File: TestDFSShell.java   View Source Code Vote up 5 votes
@Test (timeout = 30000)
public void testLsr() throws Exception {
  final Configuration conf = new HdfsConfiguration();
  MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
  DistributedFileSystem dfs = cluster.getFileSystem();

  try {
    final String root = createTree(dfs, "lsr");
    dfs.mkdirs(new Path(root, "zzz"));
    
    runLsr(new FsShell(conf), root, 0);
    
    final Path sub = new Path(root, "sub");
    dfs.setPermission(sub, new FsPermission((short)0));

    final UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
    final String tmpusername = ugi.getShortUserName() + "1";
    UserGroupInformation tmpUGI = UserGroupInformation.createUserForTesting(
        tmpusername, new String[] {tmpusername});
    String results = tmpUGI.doAs(new PrivilegedExceptionAction<String>() {
      @Override
      public String run() throws Exception {
        return runLsr(new FsShell(conf), root, 1);
      }
    });
    assertTrue(results.contains("zzz"));
  } finally {
    cluster.shutdown();
  }
}
 
Example 8
Project: hadoop   File: TestProxyUsers.java   View Source Code Vote up 5 votes
/**
 * Authorize a user (superuser) to impersonate another user (user1) if the 
 * superuser belongs to the group "sudo_user1" .
 */

public void authorize(UserGroupInformation user, 
    String remoteAddress) throws AuthorizationException{
  UserGroupInformation superUser = user.getRealUser();

  String sudoGroupName = "sudo_" + user.getShortUserName();
  if (!Arrays.asList(superUser.getGroupNames()).contains(sudoGroupName)){
    throw new AuthorizationException("User: " + superUser.getUserName()
        + " is not allowed to impersonate " + user.getUserName());
  }
}
 
Example 9
Project: hadoop   File: RMServerUtils.java   View Source Code Vote up 5 votes
/**
 * Utility method to verify if the current user has access based on the
 * passed {@link AccessControlList}
 * @param authorizer the {@link AccessControlList} to check against
 * @param method the method name to be logged
 * @param module like AdminService or NodeLabelManager
 * @param LOG the logger to use
 * @return {@link UserGroupInformation} of the current user
 * @throws IOException
 */
public static UserGroupInformation verifyAdminAccess(
    YarnAuthorizationProvider authorizer, String method, String module,
    final Log LOG)
    throws IOException {
  UserGroupInformation user;
  try {
    user = UserGroupInformation.getCurrentUser();
  } catch (IOException ioe) {
    LOG.warn("Couldn't get current user", ioe);
    RMAuditLogger.logFailure("UNKNOWN", method, "",
        "AdminService", "Couldn't get current user");
    throw ioe;
  }

  if (!authorizer.isAdmin(user)) {
    LOG.warn("User " + user.getShortUserName() + " doesn't have permission" +
        " to call '" + method + "'");

    RMAuditLogger.logFailure(user.getShortUserName(), method, "", module,
      RMAuditLogger.AuditConstants.UNAUTHORIZED_USER);

    throw new AccessControlException("User " + user.getShortUserName() +
            " doesn't have permission" +
            " to call '" + method + "'");
  }
  if (LOG.isTraceEnabled()) {
    LOG.trace(method + " invoked by user " + user.getShortUserName());
  }
  return user;
}
 
Example 10
Project: hadoop   File: BlockTokenSecretManager.java   View Source Code Vote up 5 votes
/** Generate an block token for current user */
public Token<BlockTokenIdentifier> generateToken(ExtendedBlock block,
    EnumSet<AccessMode> modes) throws IOException {
  UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
  String userID = (ugi == null ? null : ugi.getShortUserName());
  return generateToken(userID, block, modes);
}
 
Example 11
Project: ditb   File: QuotaCache.java   View Source Code Vote up 5 votes
/**
 * Returns the QuotaState associated to the specified user.
 * @param ugi the user
 * @return the quota info associated to specified user
 */
public UserQuotaState getUserQuotaState(final UserGroupInformation ugi) {
  String key = ugi.getShortUserName();
  UserQuotaState quotaInfo = userQuotaCache.get(key);
  if (quotaInfo == null) {
    quotaInfo = new UserQuotaState();
    if (userQuotaCache.putIfAbsent(key, quotaInfo) == null) {
      triggerCacheRefresh();
    }
  }
  return quotaInfo;
}
 
Example 12
Project: hadoop   File: HSAdminServer.java   View Source Code Vote up 5 votes
private UserGroupInformation checkAcls(String method) throws IOException {
  UserGroupInformation user;
  try {
    user = UserGroupInformation.getCurrentUser();
  } catch (IOException ioe) {
    LOG.warn("Couldn't get current user", ioe);

    HSAuditLogger.logFailure("UNKNOWN", method, adminAcl.toString(),
        HISTORY_ADMIN_SERVER, "Couldn't get current user");

    throw ioe;
  }

  if (!adminAcl.isUserAllowed(user)) {
    LOG.warn("User " + user.getShortUserName() + " doesn't have permission"
        + " to call '" + method + "'");

    HSAuditLogger.logFailure(user.getShortUserName(), method,
        adminAcl.toString(), HISTORY_ADMIN_SERVER,
        AuditConstants.UNAUTHORIZED_USER);

    throw new AccessControlException("User " + user.getShortUserName()
        + " doesn't have permission" + " to call '" + method + "'");
  }
  LOG.info("HS Admin: " + method + " invoked by user "
      + user.getShortUserName());

  return user;
}
 
Example 13
Project: hadoop   File: NameNodeRpcServer.java   View Source Code Vote up 5 votes
@Override // ClientProtocol
public void createSymlink(String target, String link, FsPermission dirPerms,
    boolean createParent) throws IOException {
  checkNNStartup();
  CacheEntry cacheEntry = RetryCache.waitForCompletion(retryCache);
  if (cacheEntry != null && cacheEntry.isSuccess()) {
    return; // Return previous response
  }

  /* We enforce the MAX_PATH_LENGTH limit even though a symlink target
   * URI may refer to a non-HDFS file system. 
   */
  if (!checkPathLength(link)) {
    throw new IOException("Symlink path exceeds " + MAX_PATH_LENGTH +
                          " character limit");
                          
  }

  final UserGroupInformation ugi = getRemoteUser();

  boolean success = false;
  try {
    PermissionStatus perm = new PermissionStatus(ugi.getShortUserName(),
        null, dirPerms);
    namesystem.createSymlink(target, link, perm, createParent,
        cacheEntry != null);
    success = true;
  } finally {
    RetryCache.setState(cacheEntry, success);
  }
}
 
Example 14
Project: hadoop   File: MRClientService.java   View Source Code Vote up 5 votes
private Job verifyAndGetJob(JobId jobID, JobACL accessType,
    boolean exceptionThrow) throws IOException {
  Job job = appContext.getJob(jobID);
  if (job == null && exceptionThrow) {
    throw new IOException("Unknown Job " + jobID);
  }
  UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
  if (job != null && !job.checkAccess(ugi, accessType)) {
    throw new AccessControlException("User " + ugi.getShortUserName()
        + " cannot perform operation " + accessType.name() + " on "
        + jobID);
  }
  return job;
}
 
Example 15
Project: hadoop   File: TestMRAppMaster.java   View Source Code Vote up 5 votes
@Override
protected void serviceStart() throws Exception {
  if (overrideStart) {
    try {
      UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
      String user = ugi.getShortUserName();
      stagingDirPath = MRApps.getStagingAreaDir(conf, user);
    } catch (Exception e) {
      fail(e.getMessage());
    }
  } else {
    super.serviceStart();
  }
}
 
Example 16
Project: hadoop   File: LocalJobRunner.java   View Source Code Vote up 5 votes
/**
 * @see org.apache.hadoop.mapreduce.protocol.ClientProtocol#getStagingAreaDir()
 */
public String getStagingAreaDir() throws IOException {
  Path stagingRootDir = new Path(conf.get(JTConfig.JT_STAGING_AREA_ROOT, 
      "/tmp/hadoop/mapred/staging"));
  UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
  String user;
  randid = rand.nextInt(Integer.MAX_VALUE);
  if (ugi != null) {
    user = ugi.getShortUserName() + randid;
  } else {
    user = "dummy" + randid;
  }
  return fs.makeQualified(new Path(stagingRootDir, user+"/.staging")).toString();
}
 
Example 17
Project: hadoop   File: FSPermissionChecker.java   View Source Code Vote up 5 votes
FSPermissionChecker(String fsOwner, String supergroup,
    UserGroupInformation callerUgi,
    INodeAttributeProvider attributeProvider) {
  this.fsOwner = fsOwner;
  this.supergroup = supergroup;
  this.callerUgi = callerUgi;
  HashSet<String> s =
      new HashSet<String>(Arrays.asList(callerUgi.getGroupNames()));
  groups = Collections.unmodifiableSet(s);
  user = callerUgi.getShortUserName();
  isSuper = user.equals(fsOwner) || groups.contains(supergroup);
  this.attributeProvider = attributeProvider;
}
 
Example 18
Project: hadoop   File: HistoryClientService.java   View Source Code Vote up 5 votes
private void checkAccess(Job job, JobACL jobOperation)
    throws IOException {

  UserGroupInformation callerUGI;
  callerUGI = UserGroupInformation.getCurrentUser();

  if (!job.checkAccess(callerUGI, jobOperation)) {
    throw new IOException(new AccessControlException("User "
        + callerUGI.getShortUserName() + " cannot perform operation "
        + jobOperation.name() + " on " + job.getID()));
  }
}
 
Example 19
Project: hadoop   File: UserParam.java   View Source Code Vote up 4 votes
/**
 * Construct an object from a UGI.
 */
public UserParam(final UserGroupInformation ugi) {
  this(ugi.getShortUserName());
}
 
Example 20
Project: hadoop   File: WebHdfsFileSystem.java   View Source Code Vote up 4 votes
/** @return the home directory. */
public static String getHomeDirectoryString(final UserGroupInformation ugi) {
  return "/user/" + ugi.getShortUserName();
}