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

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

Introduction

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

Prototype

public void checkTGTAndReloginFromKeytab() throws IOException 

Source Link

Document

Re-login a user from keytab if TGT is expired or is close to expiry.

Usage

From source file:azkaban.utils.AuthenticationUtils.java

License:Apache License

public static HttpURLConnection loginAuthenticatedURL(final URL url, final String keytabPrincipal,
        final String keytabPath) throws Exception {

    logger.info("Logging in URL: " + url.toString() + " using Principal: " + keytabPrincipal + ", Keytab: "
            + keytabPath);/*w w w.j av  a 2  s.  co m*/

    UserGroupInformation loginUser = UserGroupInformation.getLoginUser();

    if (loginUser == null) {
        UserGroupInformation.loginUserFromKeytab(keytabPrincipal, keytabPath);
        loginUser = UserGroupInformation.getLoginUser();
        logger.info("Logged in with user " + loginUser);
    } else {
        logger.info("Login user (" + loginUser + ") already created, refreshing tgt.");
        loginUser.checkTGTAndReloginFromKeytab();
    }

    final HttpURLConnection connection = loginUser.doAs((PrivilegedExceptionAction<HttpURLConnection>) () -> {
        final Token token = new Token();
        return new AuthenticatedURL().openConnection(url, token);
    });

    return connection;
}

From source file:com.thinkbiganalytics.nifi.v2.hdfs.AbstractHadoopProcessor.java

License:Apache License

protected void tryKerberosRelogin(UserGroupInformation ugi) {
    try {/*from ww w.  j a va  2  s . c om*/
        getLog().info(
                "Kerberos ticket age exceeds threshold [{} seconds] "
                        + "attempting to renew ticket for user {}",
                new Object[] { kerberosReloginThreshold, ugi.getUserName() });
        ugi.checkTGTAndReloginFromKeytab();
        lastKerberosReloginTime = System.currentTimeMillis() / 1000;
        getLog().info("Kerberos relogin successful or ticket still valid");
    } catch (IOException e) {
        // Most likely case of this happening is ticket is expired and error getting a new one,
        // meaning dfs operations would fail
        getLog().error("Kerberos relogin failed", e);
        throw new ProcessException("Unable to renew kerberos ticket", e);
    }
}

From source file:org.apache.accumulo.server.security.SecurityUtil.java

License:Apache License

/**
 * Start a thread that periodically attempts to renew the current Kerberos user's ticket.
 *
 * @param ugi/*from w w  w.  j  a  v a 2 s  .  com*/
 *          The current Kerberos user.
 * @param renewalPeriod
 *          The amount of time between attempting renewals.
 */
static void startTicketRenewalThread(final UserGroupInformation ugi, final long renewalPeriod) {
    Thread t = new Daemon(new LoggingRunnable(renewalLog, new Runnable() {
        @Override
        public void run() {
            while (true) {
                try {
                    renewalLog.debug("Invoking renewal attempt for Kerberos ticket");
                    // While we run this "frequently", the Hadoop implementation will only perform the login at 80% of ticket lifetime.
                    ugi.checkTGTAndReloginFromKeytab();
                } catch (IOException e) {
                    // Should failures to renew the ticket be retried more quickly?
                    renewalLog.error("Failed to renew Kerberos ticket", e);
                }

                // Wait for a bit before checking again.
                try {
                    Thread.sleep(renewalPeriod);
                } catch (InterruptedException e) {
                    renewalLog.error("Renewal thread interrupted", e);
                    Thread.currentThread().interrupt();
                    return;
                }
            }
        }
    }));
    t.setName("Kerberos Ticket Renewal");
    t.start();
}

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

License:Apache License

private void reloginUGI(UserGroupInformation ugi) {
    try {//w ww .  ja v  a 2 s .c  o m
        if (ugi.hasKerberosCredentials()) {
            long now = System.currentTimeMillis();
            if (now - lastReloginAttempt < MIN_TIME_BEFORE_RELOGIN) {
                return;
            }
            lastReloginAttempt = now;
            ugi.checkTGTAndReloginFromKeytab();
        }
    } catch (IOException e) {
        throw new SecurityException("Error trying to relogin from keytab for user " + ugi.getUserName(), e);
    }
}

From source file:org.apache.hawq.pxf.service.utilities.SecuredHDFS.java

License:Apache License

/**
 * The function will verify the token with NameNode if available and will
 * create a UserGroupInformation.//from ww  w. j a  va 2s  .c o  m
 *
 * Code in this function is copied from JspHelper.getTokenUGI
 *
 * @param identifier Delegation token identifier
 * @param password Delegation token password
 * @param kind the kind of token
 * @param service the service for this token
 * @param servletContext Jetty servlet context which contains the NN address
 *
 * @throws SecurityException Thrown when authentication fails
 */
private static void verifyToken(byte[] identifier, byte[] password, Text kind, Text service,
        ServletContext servletContext) {
    try {
        Token<DelegationTokenIdentifier> token = new Token<DelegationTokenIdentifier>(identifier, password,
                kind, service);

        ByteArrayInputStream buf = new ByteArrayInputStream(token.getIdentifier());
        DataInputStream in = new DataInputStream(buf);
        DelegationTokenIdentifier id = new DelegationTokenIdentifier();
        id.readFields(in);

        final NameNode nn = NameNodeHttpServer.getNameNodeFromContext(servletContext);
        if (nn != null) {
            nn.getNamesystem().verifyToken(id, token.getPassword());
        }

        UserGroupInformation userGroupInformation = id.getUser();
        userGroupInformation.addToken(token);
        LOG.debug("user " + userGroupInformation.getUserName() + " (" + userGroupInformation.getShortUserName()
                + ") authenticated");

        // re-login if necessary
        userGroupInformation.checkTGTAndReloginFromKeytab();
    } catch (IOException e) {
        throw new SecurityException("Failed to verify delegation token " + e, e);
    }
}

From source file:org.apache.ranger.audit.provider.MiscUtil.java

License:Apache License

public static UserGroupInformation getUGILoginUser() {
    UserGroupInformation ret = ugiLoginUser;

    if (ret == null) {
        try {// ww  w.  j a  v  a  2  s.  com
            // Do not cache ugiLoginUser if it is not explicitly set with
            // setUGILoginUser.
            // It appears that the user represented by
            // the returned object is periodically logged out and logged back
            // in when the token is scheduled to expire. So it is better
            // to get the user object every time from UserGroupInformation class and
            // not cache it
            ret = getLoginUser();
        } catch (IOException e) {
            logger.error("Error getting UGI.", e);
        }
    }

    if (ret != null) {
        try {
            ret.checkTGTAndReloginFromKeytab();
        } catch (IOException excp) {
            // ignore
        }
    }

    return ret;
}

From source file:ruciotools.WebRucioGrep.java

License:Apache License

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//*from   w ww . j av a  2  s .  com*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final PrintWriter out = response.getWriter();

    Enumeration<String> parameterNames = request.getParameterNames();
    List<String> params = new ArrayList<String>();
    while (parameterNames.hasMoreElements()) {
        String paramName = parameterNames.nextElement();
        for (String v : request.getParameterValues(paramName)) {
            params.add("-" + paramName);
            params.add(v);
        }

    }
    final String[] args = new String[params.size()];
    params.toArray(args);

    FileSystem fs = DistributedFileSystem.get(new Configuration());
    FSDataOutputStream of1 = fs.create(new Path("/user/rucio01/log/test-MR-before.ralph"));
    of1.write(new String("ralph").getBytes());
    of1.close();

    System.out.println("--------------status---:" + UserGroupInformation.isLoginKeytabBased());
    System.out.println("--------------current user---:" + UserGroupInformation.getCurrentUser());
    UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
    boolean isKeyTab = false; //ugi.isFromKeytab();
    if (isKeyTab) {
        ugi.checkTGTAndReloginFromKeytab();
    } else {
        UserGroupInformation.loginUserFromKeytab("rucio01", "/etc/hadoop/conf/rucio01.keytab");
        isKeyTab = UserGroupInformation.isLoginKeytabBased();
        if (isKeyTab) {
            ugi = UserGroupInformation.getCurrentUser();
        }
    }
    System.out.println("---------AFTER LOGIN-----:");
    System.out.println("--------------status---:" + UserGroupInformation.isLoginKeytabBased());
    System.out.println("--------------current user---:" + UserGroupInformation.getCurrentUser());

    //FileSystem fs = DistributedFileSystem.get(new Configuration());
    FSDataOutputStream of = fs.create(new Path("/user/rucio01/log/test-MR-outer.ralph"));
    of.write(new String("ralph").getBytes());
    of.close();

    try {
        ugi.doAs(new PrivilegedExceptionAction<Void>() {
            public Void run() throws Exception {

                FileSystem fs = DistributedFileSystem.get(new Configuration());
                FSDataOutputStream of = fs.create(new Path("/user/rucio01/log/test-MR-inner.ralph"));
                of.write(new String("ralph").getBytes());
                of.close();

                // Verify input parameters
                Map<String, Object> settings = Grep.parseCommandLineArguments(args);
                if ((Boolean) settings.get("printUsage")) {
                    out.println((String) settings.get("errorMessage"));
                    out.println(Grep.printUsage());
                    return null;
                }

                // Derive tmp dir for job output
                settings.put("tempDir",
                        new Path("rucio-grep-" + Integer.toString(new Random().nextInt(Integer.MAX_VALUE))));

                // Execute MR job
                try {
                    if (!Grep.runJob(settings)) {
                        out.println("Something went wrong :-(\n");
                        out.println(
                                "Hints: (1) do not redirect stderr to /dev/null (2)  consider setting -excludeTmpFiles in case of IOExceptions\n");
                    }
                } catch (Exception e) {
                    out.println(e);
                    return null;
                }
                try {
                    out.println(Grep.getResults(settings));
                } catch (Exception e) {
                    out.println("No job output found in " + settings.get("tempDir").toString());
                    out.println(e);
                }
                return null;
            }
        });
    } catch (Exception e) {
        System.out.println(e);
    }
}