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

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

Introduction

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

Prototype

@InterfaceAudience.Public
@InterfaceStability.Evolving
public static UserGroupInformation createProxyUser(String user, UserGroupInformation realUser) 

Source Link

Document

Create a proxy user using username of the effective user and the ugi of the real user.

Usage

From source file:org.apache.apex.engine.security.TokenRenewer.java

License:Apache License

private long renewTokens(final boolean refresh, boolean checkOnly) throws IOException {
    logger.info("{}", checkOnly ? "Checking renewal" : (refresh ? "Refreshing tokens" : "Renewing tokens"));
    long expiryTime = System.currentTimeMillis() + (refresh ? tokenLifeTime : tokenRenewalInterval);

    final String tokenRenewer = UserGroupInformation.getCurrentUser().getUserName();
    logger.debug("Token renewer {}", tokenRenewer);

    File keyTabFile = null;//from   www  . j a  v a2 s . c o m
    try (FileSystem fs = FileSystem.newInstance(conf)) {
        String destinationDir = FileUtils.getTempDirectoryPath();
        keyTabFile = FSUtil.copyToLocalFileSystem(fs, destinationDir, destinationFile, hdfsKeyTabFile, conf);

        if (principal == null) {
            //principal = UserGroupInformation.getCurrentUser().getUserName();
            principal = UserGroupInformation.getLoginUser().getUserName();
        }
        logger.debug("Principal {}", principal);
        UserGroupInformation ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(principal,
                keyTabFile.getAbsolutePath());
        if (!checkOnly) {
            try {
                UserGroupInformation currUGI = UserGroupInformation.createProxyUser(tokenRenewer, ugi);
                currUGI.doAs(new PrivilegedExceptionAction<Object>() {
                    @Override
                    public Object run() throws Exception {

                        if (refresh) {
                            Credentials creds = new Credentials();
                            try (FileSystem fs1 = FileSystem.newInstance(conf)) {
                                logger.info("Refreshing fs tokens");
                                fs1.addDelegationTokens(tokenRenewer, creds);
                                logger.info("Refreshed tokens");
                            }
                            if (renewRMToken) {
                                try (YarnClient yarnClient = StramClientUtils.createYarnClient(conf)) {
                                    logger.info("Refreshing rm tokens");
                                    new StramClientUtils.ClientRMHelper(yarnClient, conf)
                                            .addRMDelegationToken(tokenRenewer, creds);
                                    logger.info("Refreshed tokens");
                                }
                            }
                            credentials.addAll(creds);
                        } else {
                            Collection<Token<? extends TokenIdentifier>> tokens = credentials.getAllTokens();
                            for (Token<? extends TokenIdentifier> token : tokens) {
                                logger.debug("Token {}", token);
                                if (token.getKind().equals(HDFS_TOKEN_KIND) || (renewRMToken
                                        && token.getKind().equals(RMDelegationTokenIdentifier.KIND_NAME))) {
                                    logger.info("Renewing token {}", token.getKind());
                                    token.renew(conf);
                                    logger.info("Renewed token");
                                }
                            }
                        }

                        return null;
                    }
                });
                UserGroupInformation.getCurrentUser().addCredentials(credentials);
            } catch (InterruptedException e) {
                logger.error("Error while renewing tokens ", e);
                expiryTime = System.currentTimeMillis();
            } catch (IOException e) {
                logger.error("Error while renewing tokens ", e);
                expiryTime = System.currentTimeMillis();
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("number of tokens: {}", credentials.getAllTokens().size());
            Iterator<Token<?>> iter = credentials.getAllTokens().iterator();
            while (iter.hasNext()) {
                Token<?> token = iter.next();
                logger.debug("updated token: {}", token);
            }
        }
    } finally {
        if (keyTabFile != null) {
            keyTabFile.delete();
        }
    }
    return expiryTime;
}

From source file:org.apache.atlas.web.security.SSLAndKerberosTest.java

License:Apache License

@BeforeClass
public void setUp() throws Exception {
    jksPath = new Path(Files.createTempDirectory("tempproviders").toString(), "test.jks");
    providerUrl = JavaKeyStoreProvider.SCHEME_NAME + "://file/" + jksPath.toUri();

    String persistDir = TestUtils.getTempDirectory();

    setupKDCAndPrincipals();/*from  www.j a  va 2  s. c o  m*/
    setupCredentials();

    // client will actually only leverage subset of these properties
    final PropertiesConfiguration configuration = getSSLConfiguration(providerUrl);

    TestUtils.writeConfiguration(configuration,
            persistDir + File.separator + ApplicationProperties.APPLICATION_PROPERTIES);

    String confLocation = System.getProperty("atlas.conf");
    URL url;
    if (confLocation == null) {
        url = SSLAndKerberosTest.class.getResource("/" + ApplicationProperties.APPLICATION_PROPERTIES);
    } else {
        url = new File(confLocation, ApplicationProperties.APPLICATION_PROPERTIES).toURI().toURL();
    }
    configuration.load(url);
    configuration.setProperty(TLS_ENABLED, true);
    configuration.setProperty("atlas.http.authentication.enabled", "true");
    configuration.setProperty("atlas.http.authentication.type", "kerberos");
    configuration.setProperty("atlas.http.authentication.kerberos.principal",
            "HTTP/localhost@" + kdc.getRealm());
    configuration.setProperty("atlas.http.authentication.kerberos.keytab", httpKeytabFile.getAbsolutePath());
    configuration.setProperty("atlas.http.authentication.kerberos.name.rules",
            "RULE:[1:$1@$0](.*@EXAMPLE.COM)s/@.*//\nDEFAULT");

    TestUtils.writeConfiguration(configuration, persistDir + File.separator + "atlas-application.properties");

    subject = loginTestUser();
    UserGroupInformation.loginUserFromSubject(subject);
    UserGroupInformation proxyUser = UserGroupInformation.createProxyUser("testUser",
            UserGroupInformation.getLoginUser());

    dgiCLient = proxyUser.doAs(new PrivilegedExceptionAction<AtlasClient>() {
        @Override
        public AtlasClient run() throws Exception {
            return new AtlasClient(DGI_URL) {
                @Override
                protected PropertiesConfiguration getClientProperties() {
                    return configuration;
                }
            };
        }
    });

    // save original setting
    originalConf = System.getProperty("atlas.conf");
    System.setProperty("atlas.conf", persistDir);
    secureEmbeddedServer = new TestSecureEmbeddedServer(21443, getWarPath()) {
        @Override
        public PropertiesConfiguration getConfiguration() {
            return configuration;
        }
    };
    secureEmbeddedServer.getServer().start();
}

From source file:org.apache.blur.hive.BlurHiveOutputFormat.java

License:Apache License

public static UserGroupInformation getUGI(final Configuration configuration) throws IOException {
    String user = getBlurUser(configuration);
    UserGroupInformation userGroupInformation;
    UserGroupInformation currentUser = UserGroupInformation.getCurrentUser();
    if (user.equals(currentUser.getUserName())) {
        userGroupInformation = currentUser;
    } else {/*from w ww .  j av a 2  s .c o m*/
        if (BlurHiveOutputFormat.isBlurUserAsProxy(configuration)) {
            userGroupInformation = UserGroupInformation.createProxyUser(user, currentUser);
        } else {
            userGroupInformation = UserGroupInformation.createRemoteUser(user);
        }
    }
    return userGroupInformation;
}

From source file:org.apache.drill.exec.rpc.user.DrillUser.java

License:Apache License

public DrillUser(String userName) throws IOException {
    this.hadoopUser = UserGroupInformation.createProxyUser(userName, UserGroupInformation.getCurrentUser());
}

From source file:org.apache.falcon.entity.parser.EntityParser.java

License:Apache License

/**
 * Checks if the acl owner is a valid user by fetching the groups for the owner.
 * Also checks if the acl group is one of the fetched groups for membership.
 * The only limitation is that a user cannot add a group in ACL that he does not belong to.
 *
 * @param acl  entity ACL//  ww w.  j a v a  2s . c  om
 * @throws org.apache.falcon.entity.parser.ValidationException
 */
protected void validateACLOwnerAndGroup(AccessControlList acl) throws ValidationException {
    String aclOwner = acl.getOwner();
    String aclGroup = acl.getGroup();

    try {
        UserGroupInformation proxyACLUser = UserGroupInformation.createProxyUser(aclOwner,
                UserGroupInformation.getLoginUser());
        Set<String> groups = new HashSet<String>(Arrays.asList(proxyACLUser.getGroupNames()));
        if (!groups.contains(aclGroup)) {
            throw new AuthorizationException("Invalid group: " + aclGroup + " for user: " + aclOwner);
        }
    } catch (IOException e) {
        throw new ValidationException(
                "Invalid acl owner " + aclOwner + ", does not exist or does not belong to group: " + aclGroup);
    }
}

From source file:org.apache.falcon.security.CurrentUser.java

License:Apache License

/**
 * Create a proxy UGI object for the proxy user.
 *
 * @param proxyUser logged in user// ww w .j  a  v  a  2 s . co m
 * @return UGI object
 * @throws IOException
 */
public static UserGroupInformation createProxyUGI(String proxyUser) throws IOException {
    UserGroupInformation proxyUgi = userUgiMap.get(proxyUser);
    if (proxyUgi == null) {
        // taking care of a race condition, the latest UGI will be discarded
        proxyUgi = UserGroupInformation.createProxyUser(proxyUser, UserGroupInformation.getLoginUser());
        userUgiMap.putIfAbsent(proxyUser, proxyUgi);
    }

    return proxyUgi;
}

From source file:org.apache.flume.auth.KerberosAuthenticator.java

License:Apache License

@Override
public synchronized PrivilegedExecutor proxyAs(String proxyUserName) {
    if (proxyUserName == null || proxyUserName.isEmpty()) {
        return this;
    }/*w w  w . java 2 s .c  o  m*/
    if (proxyCache.get(proxyUserName) == null) {
        UserGroupInformation proxyUgi;
        proxyUgi = UserGroupInformation.createProxyUser(proxyUserName, ugi);
        printUGI(proxyUgi);
        proxyCache.put(proxyUserName, new UGIExecutor(proxyUgi));
    }
    return proxyCache.get(proxyUserName);
}

From source file:org.apache.flume.auth.SimpleAuthenticator.java

License:Apache License

@Override
public synchronized PrivilegedExecutor proxyAs(String proxyUserName) {
    if (proxyUserName == null || proxyUserName.isEmpty()) {
        return this;
    }//from   w  w w . j a v  a  2 s.c o  m
    if (proxyCache.get(proxyUserName) == null) {
        UserGroupInformation proxyUgi;
        try {
            proxyUgi = UserGroupInformation.createProxyUser(proxyUserName,
                    UserGroupInformation.getCurrentUser());
        } catch (IOException e) {
            throw new SecurityException("Unable to create proxy User", e);
        }
        proxyCache.put(proxyUserName, new UGIExecutor(proxyUgi));
    }
    return proxyCache.get(proxyUserName);
}

From source file:org.apache.flume.sink.kite.KerberosUtil.java

License:Apache License

public static UserGroupInformation proxyAs(String username, UserGroupInformation login) {
    Preconditions.checkArgument(username != null && !username.isEmpty(),
            "Invalid username: " + String.valueOf(username));
    Preconditions.checkArgument(login != null, "Cannot proxy without an authenticated user");

    // hadoop impersonation works with or without kerberos security
    return UserGroupInformation.createProxyUser(username, login);
}

From source file:org.apache.hama.ipc.ConnectionHeader.java

License:Apache License

@Override
public void readFields(DataInput in) throws IOException {
    protocol = Text.readString(in);
    if (protocol.isEmpty()) {
        protocol = null;/*from   w  w  w  .  j  av a  2s.  c o  m*/
    }

    boolean ugiUsernamePresent = in.readBoolean();
    if (ugiUsernamePresent) {
        String username = in.readUTF();
        boolean realUserNamePresent = in.readBoolean();
        if (realUserNamePresent) {
            String realUserName = in.readUTF();
            UserGroupInformation realUserUgi = UserGroupInformation.createRemoteUser(realUserName);
            ugi = UserGroupInformation.createProxyUser(username, realUserUgi);
        } else {
            ugi = UserGroupInformation.createRemoteUser(username);
        }
    } else {
        ugi = null;
    }
}