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

The following examples show how to use org.apache.hadoop.security.UserGroupInformation#getLoginUser() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Bats   File: SecureExecutor.java    License: Apache License 2.0 6 votes vote down vote up
public static <T> T execute(final SecureExecutor.WorkLoad<T> workLoad) throws IOException
{
  if (UserGroupInformation.isSecurityEnabled()) {
    UserGroupInformation loginUser = UserGroupInformation.getLoginUser();
    return loginUser.doAs(new PrivilegedAction<T>()
    {
      @Override
      public T run()
      {
        return workLoad.run();
      }
    });
  } else {
    return workLoad.run();
  }
}
 
Example 2
Source Project: hadoop   File: HttpFSFileSystem.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Called after a new FileSystem instance is constructed.
 *
 * @param name a uri whose authority section names the host, port, etc. for this FileSystem
 * @param conf the configuration
 */
@Override
public void initialize(URI name, Configuration conf) throws IOException {
  UserGroupInformation ugi = UserGroupInformation.getCurrentUser();

  //the real use is the one that has the Kerberos credentials needed for
  //SPNEGO to work
  realUser = ugi.getRealUser();
  if (realUser == null) {
    realUser = UserGroupInformation.getLoginUser();
  }
  super.initialize(name, conf);
  try {
    uri = new URI(name.getScheme() + "://" + name.getAuthority());
  } catch (URISyntaxException ex) {
    throw new IOException(ex);
  }

  Class<? extends DelegationTokenAuthenticator> klass =
      getConf().getClass("httpfs.authenticator.class",
          KerberosDelegationTokenAuthenticator.class,
          DelegationTokenAuthenticator.class);
  DelegationTokenAuthenticator authenticator =
      ReflectionUtils.newInstance(klass, getConf());
  authURL = new DelegationTokenAuthenticatedURL(authenticator);
}
 
Example 3
Source Project: big-c   File: DataNode.java    License: Apache License 2.0 6 votes vote down vote up
public static InterDatanodeProtocol createInterDataNodeProtocolProxy(
    DatanodeID datanodeid, final Configuration conf, final int socketTimeout,
    final boolean connectToDnViaHostname) throws IOException {
  final String dnAddr = datanodeid.getIpcAddr(connectToDnViaHostname);
  final InetSocketAddress addr = NetUtils.createSocketAddr(dnAddr);
  if (LOG.isDebugEnabled()) {
    LOG.debug("Connecting to datanode " + dnAddr + " addr=" + addr);
  }
  final UserGroupInformation loginUgi = UserGroupInformation.getLoginUser();
  try {
    return loginUgi
        .doAs(new PrivilegedExceptionAction<InterDatanodeProtocol>() {
          @Override
          public InterDatanodeProtocol run() throws IOException {
            return new InterDatanodeProtocolTranslatorPB(addr, loginUgi,
                conf, NetUtils.getDefaultSocketFactory(conf), socketTimeout);
          }
        });
  } catch (InterruptedException ie) {
    throw new IOException(ie.getMessage());
  }
}
 
Example 4
Source Project: dk-fitting   File: HdfsUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static FileSystem getFs(String krb5_conf, String principal, String keytab) throws Exception {
    if (fs != null) {
        return fs;
    } else {
        System.out.println("hdfs_site:" + Prop.getProperty("datasource.hdfs_xml_path"));
        System.out.println("core_site:" + Prop.getProperty("datasource.core_xml_path"));
        conf.addResource(new Path(Prop.getProperty("datasource.hdfs_xml_path")));
        conf.addResource(new Path(Prop.getProperty("datasource.core_xml_path")));
        conf.set("dfs.client.block.write.replace-datanode-on-failure.policy", "NEVER");
        conf.set("dfs.client.block.write.replace-datanode-on-failure.enable", "true");
        //conf.setBoolean("fs.hdfs.impl.disable.cache", true);
        if (StringUtils.isNotBlank(krb5_conf) && StringUtils.isNotBlank(principal) && StringUtils.isNotBlank(keytab)) {
            System.setProperty("java.security.krb5.conf", krb5_conf);
            UserGroupInformation.setConfiguration(conf);
            UserGroupInformation.loginUserFromKeytab(principal, keytab);
            UserGroupInformation.getLoginUser();
        }
        fs = FileSystem.get(conf);
        return fs;
    }
}
 
Example 5
Source Project: big-c   File: Gridmix.java    License: Apache License 2.0 6 votes vote down vote up
public int run(final String[] argv) throws IOException, InterruptedException {
  int val = -1;
  final Configuration conf = getConf();
  UserGroupInformation.setConfiguration(conf);
  UserGroupInformation ugi = UserGroupInformation.getLoginUser();

  val = ugi.doAs(new PrivilegedExceptionAction<Integer>() {
    public Integer run() throws Exception {
      return runJob(conf, argv);
    }
  });
  
  // print the gridmix summary if the run was successful
  if (val == 0) {
      // print the run summary
      System.out.print("\n\n");
      System.out.println(summarizer.toString());
  }
  
  return val; 
}
 
Example 6
Source Project: pxf   File: UGICacheMultiThreadTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws IOException {
    provider = new FakeUgiProvider();

    Configuration configuration = new Configuration();

    int l = 0;
    for (int i = 0; i < numberOfSegments; i++) {
        for (int j = 0; j < numberOfUsers; j++) {
            for (int k = 0; k < numberOfTxns; k++) {
                sessions[l++] = new SessionId(i, "txn-id-" + k, "the-user-" + j, "default", configuration, UserGroupInformation.getLoginUser());
            }
        }
    }
    fakeTicker = new FakeTicker();
    cache = new UGICache(provider, fakeTicker);
}
 
Example 7
public void initHiveMetastoreClient() throws Exception {
  if (this.state.contains(ConfigurationKeys.SUPER_USER_KEY_TAB_LOCATION)) {
    String superUser = this.state.getProp(ComplianceConfigurationKeys.GOBBLIN_COMPLIANCE_SUPER_USER);
    String realm = this.state.getProp(ConfigurationKeys.KERBEROS_REALM);
    String keytabLocation = this.state.getProp(ConfigurationKeys.SUPER_USER_KEY_TAB_LOCATION);
    log.info("Establishing MetastoreClient connection using " + keytabLocation);

    UserGroupInformation.loginUserFromKeytab(HostUtils.getPrincipalUsingHostname(superUser, realm), keytabLocation);
    UserGroupInformation loginUser = UserGroupInformation.getLoginUser();
    loginUser.doAs(new PrivilegedExceptionAction<Void>() {
      @Override
      public Void run() throws TException {
        HivePurgerPublisher.this.client = new HiveMetaStoreClient(new HiveConf());
        return null;
      }
    });
  } else {
    HivePurgerPublisher.this.client = new HiveMetaStoreClient(new HiveConf());
  }
}
 
Example 8
Source Project: hadoop   File: GenerateData.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Job call() throws IOException, InterruptedException,
                         ClassNotFoundException {
  UserGroupInformation ugi = UserGroupInformation.getLoginUser();
  ugi.doAs( new PrivilegedExceptionAction <Job>() {
     public Job run() throws IOException, ClassNotFoundException,
                             InterruptedException {
       // check if compression emulation is enabled
       if (CompressionEmulationUtil
           .isCompressionEmulationEnabled(job.getConfiguration())) {
         CompressionEmulationUtil.configure(job);
       } else {
         configureRandomBytesDataGenerator();
       }
       job.submit();
       return job;
     }
     
     private void configureRandomBytesDataGenerator() {
      job.setMapperClass(GenDataMapper.class);
      job.setNumReduceTasks(0);
      job.setMapOutputKeyClass(NullWritable.class);
      job.setMapOutputValueClass(BytesWritable.class);
      job.setInputFormatClass(GenDataFormat.class);
      job.setOutputFormatClass(RawBytesOutputFormat.class);
      job.setJarByClass(GenerateData.class);
      try {
        FileInputFormat.addInputPath(job, new Path("ignored"));
      } catch (IOException e) {
        LOG.error("Error while adding input path ", e);
      }
    }
  });
  return job;
}
 
Example 9
Source Project: Bats   File: LaunchContainerRunnable.java    License: Apache License 2.0 5 votes vote down vote up
public static ByteBuffer getTokens(StramDelegationTokenManager delegationTokenManager, InetSocketAddress heartbeatAddress) throws IOException
{
  if (UserGroupInformation.isSecurityEnabled()) {
    UserGroupInformation ugi = UserGroupInformation.getLoginUser();
    StramDelegationTokenIdentifier identifier = new StramDelegationTokenIdentifier(new Text(ugi.getUserName()), new Text(""), new Text(""));
    String service = heartbeatAddress.getAddress().getHostAddress() + ":" + heartbeatAddress.getPort();
    Token<StramDelegationTokenIdentifier> stramToken = new Token<>(identifier, delegationTokenManager);
    stramToken.setService(new Text(service));
    return getTokens(ugi, stramToken);
  }
  return null;
}
 
Example 10
Source Project: pxf   File: UGICacheTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void getTwoUGIsWithDifferentUsers() throws Exception {
    SessionId otherSession = new SessionId(0, "txn-id", "different-user", "default", new Configuration(), UserGroupInformation.getLoginUser());
    UserGroupInformation ugi1 = cache.getUserGroupInformation(session, false);
    UserGroupInformation ugi2 = cache.getUserGroupInformation(otherSession, false);
    assertNotEquals(ugi1, ugi2);
    verify(provider, times(1)).createRemoteUser(eq("the-user"), any(SessionId.class));
    verify(provider, times(1)).createRemoteUser(eq("different-user"), any(SessionId.class));
    assertCacheSize(2);
    assertStillInCache(session, ugi1);
    assertStillInCache(otherSession, ugi2);
}
 
Example 11
Source Project: big-c   File: HSAdminServer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void serviceStart() throws Exception {
  if (UserGroupInformation.isSecurityEnabled()) {
    loginUGI = UserGroupInformation.getLoginUser();
  } else {
    loginUGI = UserGroupInformation.getCurrentUser();
  }
  clientRpcServer.start();
}
 
Example 12
Source Project: big-c   File: ClientRMService.java    License: Apache License 2.0 5 votes vote down vote up
private String getRenewerForToken(Token<RMDelegationTokenIdentifier> token)
    throws IOException {
  UserGroupInformation user = UserGroupInformation.getCurrentUser();
  UserGroupInformation loginUser = UserGroupInformation.getLoginUser();
  // we can always renew our own tokens
  return loginUser.getUserName().equals(user.getUserName())
      ? token.decodeIdentifier().getRenewer().toString()
      : user.getShortUserName();
}
 
Example 13
Source Project: hbase   File: TestSecureIPC.java    License: Apache License 2.0 5 votes vote down vote up
private UserGroupInformation loginKerberosPrincipal(String krbKeytab, String krbPrincipal)
    throws Exception {
  Configuration cnf = new Configuration();
  cnf.set(CommonConfigurationKeys.HADOOP_SECURITY_AUTHENTICATION, "kerberos");
  UserGroupInformation.setConfiguration(cnf);
  UserGroupInformation.loginUserFromKeytab(krbPrincipal, krbKeytab);
  return UserGroupInformation.getLoginUser();
}
 
Example 14
@Override
public void cancel(Token<?> t, Configuration config) throws IOException {
    Token<BrokerTokenIdentifier> token = (Token<BrokerTokenIdentifier>) t;
    BrokerTokenIdentifier tokenIdentifier = (BrokerTokenIdentifier) GcsDelegationTokens.extractIdentifier(token);
    UserGroupInformation loginUser = UserGroupInformation.getLoginUser();
    BrokerServerInfo serverInfo = Utils.getBrokerDetailsFromConfig(config);
    loginUser.doAs((PrivilegedAction<Void>) () -> {
        CancelSessionToken.submit(serverInfo, tokenIdentifier.getSessionToken());
        return null;
    });
}
 
Example 15
/**
 * Return the {@link UserGroupInformation} of user who is running the SabotNode.
 *
 * @return SabotNode process user {@link UserGroupInformation}.
 */
public static UserGroupInformation getProcessUserUGI() {
  try {
    return UserGroupInformation.getLoginUser();
  } catch (IOException e) {
    final String errMsg = "Failed to get process user UserGroupInformation object.";
    logger.error(errMsg, e);
    throw new RuntimeException(errMsg, e);
  }
}
 
Example 16
Source Project: dremio-oss   File: HiveClientImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void reloginExpiringKeytabUser() throws MetaException {
  if(UserGroupInformation.isSecurityEnabled()) {
    // renew the TGT if required
    try {
      UserGroupInformation ugi = UserGroupInformation.getLoginUser();
      if (ugi.isFromKeytab()) {
        ugi.checkTGTAndReloginFromKeytab();
      }
    } catch (IOException e) {
      final String msg = "Error doing relogin using keytab " + e.getMessage();
      logger.error(msg, e);
      throw new MetaException(msg);
    }
  }
}
 
Example 17
Source Project: big-c   File: GenerateData.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Job call() throws IOException, InterruptedException,
                         ClassNotFoundException {
  UserGroupInformation ugi = UserGroupInformation.getLoginUser();
  ugi.doAs( new PrivilegedExceptionAction <Job>() {
     public Job run() throws IOException, ClassNotFoundException,
                             InterruptedException {
       // check if compression emulation is enabled
       if (CompressionEmulationUtil
           .isCompressionEmulationEnabled(job.getConfiguration())) {
         CompressionEmulationUtil.configure(job);
       } else {
         configureRandomBytesDataGenerator();
       }
       job.submit();
       return job;
     }
     
     private void configureRandomBytesDataGenerator() {
      job.setMapperClass(GenDataMapper.class);
      job.setNumReduceTasks(0);
      job.setMapOutputKeyClass(NullWritable.class);
      job.setMapOutputValueClass(BytesWritable.class);
      job.setInputFormatClass(GenDataFormat.class);
      job.setOutputFormatClass(RawBytesOutputFormat.class);
      job.setJarByClass(GenerateData.class);
      try {
        FileInputFormat.addInputPath(job, new Path("ignored"));
      } catch (IOException e) {
        LOG.error("Error while adding input path ", e);
      }
    }
  });
  return job;
}
 
Example 18
Source Project: big-c   File: DFSZKFailoverController.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void checkRpcAdminAccess() throws IOException, AccessControlException {
  UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
  UserGroupInformation zkfcUgi = UserGroupInformation.getLoginUser();
  if (adminAcl.isUserAllowed(ugi) ||
      ugi.getShortUserName().equals(zkfcUgi.getShortUserName())) {
    LOG.info("Allowed RPC access from " + ugi + " at " + Server.getRemoteAddress());
    return;
  }
  String msg = "Disallowed RPC access from " + ugi + " at " +
      Server.getRemoteAddress() + ". Not listed in " + DFSConfigKeys.DFS_ADMIN; 
  LOG.warn(msg);
  throw new AccessControlException(msg);
}
 
Example 19
Source Project: ranger   File: MiscUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static void setUGIFromJAASConfig(String jaasConfigAppName) throws Exception {
	String keytabFile 			= null;
	String principal  			= null;
	UserGroupInformation ugi 	= null;
	if (logger.isDebugEnabled()){
		logger.debug("===> MiscUtil.setUGIFromJAASConfig() jaasConfigAppName: " + jaasConfigAppName);
	}
	try {
		AppConfigurationEntry entries[] = Configuration.getConfiguration().getAppConfigurationEntry(jaasConfigAppName);
		if(!ArrayUtils.isEmpty(entries)) {
			for (AppConfigurationEntry entry : entries) {
				if (entry.getOptions().get("keyTab") != null) {
					keytabFile = (String) entry.getOptions().get("keyTab");
				}
				if (entry.getOptions().get("principal") != null) {
					principal = (String) entry.getOptions().get("principal");
				}
				if (!StringUtils.isEmpty(principal) && !StringUtils.isEmpty(keytabFile)) {
					break;
				}
			}
			if (!StringUtils.isEmpty(principal) && !StringUtils.isEmpty(keytabFile)) {
				// This will login and set the UGI
				UserGroupInformation.loginUserFromKeytab(principal, keytabFile);
				ugi = UserGroupInformation.getLoginUser();
			} else {
				String error_mesage = "Unable to get the principal/keytab from jaasConfigAppName: " + jaasConfigAppName;
				logger.error(error_mesage);
				throw new Exception(error_mesage);
			}
			logger.info("MiscUtil.setUGIFromJAASConfig() UGI: " + ugi + " principal: " + principal + " keytab: " + keytabFile);
		} else {
			logger.warn("JAASConfig file not found! Ranger Plugin will not working in a Secure Cluster...");
		}
	} catch ( Exception e) {
		logger.error("Unable to set UGI for Principal: " + principal + " keytab: " + keytabFile );
		throw e;
	}
	if (logger.isDebugEnabled()) {
		logger.debug("<=== MiscUtil.setUGIFromJAASConfig() jaasConfigAppName: " + jaasConfigAppName + " UGI: " + ugi + " principal: " + principal + " keytab: " + keytabFile);
	}
}
 
Example 20
Source Project: nifi   File: SecurityUtil.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Initializes UserGroupInformation with the given Configuration and returns UserGroupInformation.getLoginUser().
 * All logins should happen through this class to ensure other threads are not concurrently modifying
 * UserGroupInformation.
 *
 * @param config the configuration instance
 *
 * @return the UGI for the given principal
 *
 * @throws IOException if login failed
 */
public static synchronized UserGroupInformation loginSimple(final Configuration config) throws IOException {
    Validate.notNull(config);
    UserGroupInformation.setConfiguration(config);
    return UserGroupInformation.getLoginUser();
}