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

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

Introduction

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

Prototype

@InterfaceAudience.Public
@InterfaceStability.Evolving
public <T> T doAs(PrivilegedExceptionAction<T> action) throws IOException, InterruptedException 

Source Link

Document

Run the given action as the user, potentially throwing an exception.

Usage

From source file:org.apache.ranger.audit.provider.kafka.KafkaAuditProvider.java

License:Apache License

@Override
public boolean log(AuditEventBase event) {
    if (event instanceof AuthzAuditEvent) {
        AuthzAuditEvent authzEvent = (AuthzAuditEvent) event;

        if (authzEvent.getAgentHostname() == null) {
            authzEvent.setAgentHostname(MiscUtil.getHostname());
        }//w ww. j  a  va  2  s . c  o  m

        if (authzEvent.getLogType() == null) {
            authzEvent.setLogType("RangerAudit");
        }

        if (authzEvent.getEventId() == null) {
            authzEvent.setEventId(MiscUtil.generateUniqueId());
        }
    }

    String message = MiscUtil.stringify(event);
    try {

        if (producer != null) {
            // TODO: Add partition key
            final ProducerRecord<String, String> keyedMessage = new ProducerRecord<String, String>(topic,
                    message);
            PrivilegedAction<Void> action = new PrivilegedAction<Void>() {
                @Override
                public Void run() {
                    producer.send(keyedMessage);
                    return null;
                };
            };

            UserGroupInformation ugi = MiscUtil.getUGILoginUser();
            if (ugi != null) {
                ugi.doAs(action);
            } else {
                action.run();
            }
        } else {
            LOG.info("AUDIT LOG (Kafka Down):" + message);
        }
    } catch (Throwable t) {
        LOG.error("Error sending message to Kafka topic. topic=" + topic + ", message=" + message, t);
        return false;
    }
    return true;
}

From source file:org.apache.ranger.audit.provider.kafka.KafkaAuditProvider.java

License:Apache License

@Override
public void stop() {
    LOG.info("stop() called");
    if (producer != null) {
        try {/* w  w  w  . ja va  2  s  . c om*/
            PrivilegedExceptionAction<Void> action = new PrivilegedExceptionAction<Void>() {
                @Override
                public Void run() throws Exception {
                    producer.close();
                    return null;
                };
            };
            MiscUtil.getUGILoginUser().doAs(action);
            UserGroupInformation ugi = MiscUtil.getUGILoginUser();
            if (ugi != null) {
                ugi.doAs(action);
            } else {
                action.run();
            }
        } catch (Throwable t) {
            LOG.error("Error closing Kafka producer");
        }
    }
}

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

License:Apache License

@Override
public void run() {
    UserGroupInformation loginUser = null;

    try {/*w ww . ja  v  a  2 s .c  om*/
        loginUser = UserGroupInformation.getLoginUser();
    } catch (IOException excp) {
        mLogger.error(
                "DestinationDispatcherThread.run(): failed to get login user details. Audit files will not be sent to HDFS destination",
                excp);
    }

    if (loginUser == null) {
        mLogger.error(
                "DestinationDispatcherThread.run(): failed to get login user. Audit files will not be sent to HDFS destination");

        return;
    }

    loginUser.doAs(new PrivilegedAction<Integer>() {
        @Override
        public Integer run() {
            doRun();

            return 0;
        }
    });
}

From source file:org.apache.ranger.audit.provider.solr.SolrAuditProvider.java

License:Apache License

void connect() {
    SolrClient me = solrClient;/*from   w ww . j  a v a  2 s.  c  o  m*/
    if (me == null) {
        synchronized (lock) {
            me = solrClient;
            if (me == null) {
                final String solrURL = MiscUtil.getStringProperty(props, "xasecure.audit.solr.solr_url");

                if (lastConnectTime != null) {
                    // Let's wait for enough time before retrying
                    long diff = System.currentTimeMillis() - lastConnectTime.getTime();
                    if (diff < retryWaitTime) {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Ignore connecting to solr url=" + solrURL + ", lastConnect=" + diff
                                    + "ms");
                        }
                        return;
                    }
                }
                lastConnectTime = new Date();

                if (solrURL == null || solrURL.isEmpty()) {
                    LOG.fatal("Solr URL for Audit is empty");
                    return;
                }

                try {
                    // TODO: Need to support SolrCloud also
                    PrivilegedExceptionAction<SolrClient> action = new PrivilegedExceptionAction<SolrClient>() {
                        @Override
                        public SolrClient run() throws Exception {
                            SolrClient solrClient = new HttpSolrClient(solrURL);
                            return solrClient;
                        };
                    };
                    UserGroupInformation ugi = MiscUtil.getUGILoginUser();
                    if (ugi != null) {
                        solrClient = ugi.doAs(action);
                    } else {
                        solrClient = action.run();
                    }
                    me = solrClient;
                    if (solrClient instanceof HttpSolrClient) {
                        HttpSolrClient httpSolrClient = (HttpSolrClient) solrClient;
                        httpSolrClient.setAllowCompression(true);
                        httpSolrClient.setConnectionTimeout(1000);
                        // solrClient.setSoTimeout(10000);
                        httpSolrClient.setMaxRetries(1);
                    }
                } catch (Throwable t) {
                    LOG.fatal("Can't connect to Solr server. URL=" + solrURL, t);
                }
            }
        }
    }
}

From source file:org.apache.ranger.audit.provider.solr.SolrAuditProvider.java

License:Apache License

@Override
public boolean log(AuditEventBase event) {
    if (!(event instanceof AuthzAuditEvent)) {
        LOG.error(event.getClass().getName() + " audit event class type is not supported");
        return false;
    }//from w w  w  .  ja  v  a 2s .c om
    AuthzAuditEvent authzEvent = (AuthzAuditEvent) event;
    // TODO: This should be done at a higher level

    if (authzEvent.getAgentHostname() == null) {
        authzEvent.setAgentHostname(MiscUtil.getHostname());
    }

    if (authzEvent.getLogType() == null) {
        authzEvent.setLogType("RangerAudit");
    }

    if (authzEvent.getEventId() == null) {
        authzEvent.setEventId(MiscUtil.generateUniqueId());
    }

    try {
        if (solrClient == null) {
            connect();
            if (solrClient == null) {
                // Solr is still not initialized. So need to throw error
                return false;
            }
        }

        if (lastFailTime > 0) {
            long diff = System.currentTimeMillis() - lastFailTime;
            if (diff < retryWaitTime) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Ignore sending audit. lastConnect=" + diff + " ms");
                }
                return false;
            }
        }
        // Convert AuditEventBase to Solr document
        final SolrInputDocument document = toSolrDoc(authzEvent);
        UpdateResponse response = null;
        PrivilegedExceptionAction<UpdateResponse> action = new PrivilegedExceptionAction<UpdateResponse>() {
            @Override
            public UpdateResponse run() throws Exception {
                UpdateResponse response = solrClient.add(document);
                return response;
            };
        };
        UserGroupInformation ugi = MiscUtil.getUGILoginUser();
        if (ugi != null) {
            response = ugi.doAs(action);
        } else {
            response = action.run();
        }
        if (response.getStatus() != 0) {
            lastFailTime = System.currentTimeMillis();

            // System.out.println("Response=" + response.toString()
            // + ", status= " + response.getStatus() + ", event="
            // + event);
            // throw new Exception("Aborting. event=" + event +
            // ", response="
            // + response.toString());
        } else {
            lastFailTime = 0;
        }

    } catch (Throwable t) {
        LOG.error("Error sending message to Solr", t);
        return false;
    }
    return true;
}

From source file:org.apache.ranger.authorization.hbase.HBaseRangerAuthorizationTest.java

License:Apache License

@Test
public void testReadTablesAsGroupIT() throws Exception {
    final Configuration conf = HBaseConfiguration.create();
    conf.set("hbase.zookeeper.quorum", "localhost");
    conf.set("hbase.zookeeper.property.clientPort", "" + port);
    conf.set("zookeeper.znode.parent", "/hbase-unsecure");

    String user = "IT";

    UserGroupInformation ugi = UserGroupInformation.createUserForTesting(user, new String[] { "IT" });
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        public Void run() throws Exception {
            Connection conn = ConnectionFactory.createConnection(conf);
            Admin admin = conn.getAdmin();

            HTableDescriptor[] tableDescriptors = admin.listTables();
            for (HTableDescriptor desc : tableDescriptors) {
                LOG.info("Found table:[" + desc.getTableName().getNameAsString() + "]");
            }/* w ww  .  ja  v  a2 s  .c o  m*/
            Assert.assertEquals(0, tableDescriptors.length);

            conn.close();
            return null;
        }
    });
}

From source file:org.apache.ranger.authorization.hbase.HBaseRangerAuthorizationTest.java

License:Apache License

@Test
public void testCreateAndDropTables() throws Exception {
    final Configuration conf = HBaseConfiguration.create();
    conf.set("hbase.zookeeper.quorum", "localhost");
    conf.set("hbase.zookeeper.property.clientPort", "" + port);
    conf.set("zookeeper.znode.parent", "/hbase-unsecure");

    Connection conn = ConnectionFactory.createConnection(conf);
    Admin admin = conn.getAdmin();//from w ww  . java  2 s. co m

    // Create a new table as process owner
    HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf("temp2"));

    // Adding column families to table descriptor
    tableDescriptor.addFamily(new HColumnDescriptor("colfam1"));
    tableDescriptor.addFamily(new HColumnDescriptor("colfam2"));

    admin.createTable(tableDescriptor);

    conn.close();

    // Try to disable + delete the table as the "IT" group
    String user = "IT";

    UserGroupInformation ugi = UserGroupInformation.createUserForTesting(user, new String[] { "IT" });
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        public Void run() throws Exception {
            Connection conn = ConnectionFactory.createConnection(conf);
            Admin admin = conn.getAdmin();

            try {
                admin.disableTable(TableName.valueOf("temp2"));
                admin.deleteTable(TableName.valueOf("temp2"));
                Assert.fail("Failure expected on an unauthorized user");
            } catch (IOException ex) {
                // expected
            }

            conn.close();
            return null;
        }
    });

    // Now disable and delete as process owner
    conn = ConnectionFactory.createConnection(conf);
    admin = conn.getAdmin();
    admin.disableTable(TableName.valueOf("temp2"));
    admin.deleteTable(TableName.valueOf("temp2"));

    conn.close();
}

From source file:org.apache.ranger.authorization.hbase.HBaseRangerAuthorizationTest.java

License:Apache License

@Test
public void testReadRowAsGroupIT() throws Exception {
    final Configuration conf = HBaseConfiguration.create();
    conf.set("hbase.zookeeper.quorum", "localhost");
    conf.set("hbase.zookeeper.property.clientPort", "" + port);
    conf.set("zookeeper.znode.parent", "/hbase-unsecure");

    String user = "IT";

    UserGroupInformation ugi = UserGroupInformation.createUserForTesting(user, new String[] { "IT" });
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        public Void run() throws Exception {
            Connection conn = ConnectionFactory.createConnection(conf);
            Table table = conn.getTable(TableName.valueOf("temp"));

            // Read a row
            Get get = new Get(Bytes.toBytes("row1"));
            Result result = table.get(get);
            byte[] valResult = result.getValue(Bytes.toBytes("colfam1"), Bytes.toBytes("col1"));
            Assert.assertTrue(Arrays.equals(valResult, Bytes.toBytes("val1")));

            conn.close();/* w  ww  .  j a  v a 2s . co m*/
            return null;
        }
    });
}

From source file:org.apache.ranger.authorization.hbase.HBaseRangerAuthorizationTest.java

License:Apache License

@Test
public void testReadRowAsGroupPublic() throws Exception {
    final Configuration conf = HBaseConfiguration.create();
    conf.set("hbase.zookeeper.quorum", "localhost");
    conf.set("hbase.zookeeper.property.clientPort", "" + port);
    conf.set("zookeeper.znode.parent", "/hbase-unsecure");

    String user = "public";

    UserGroupInformation ugi = UserGroupInformation.createUserForTesting(user, new String[] { "public" });
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        public Void run() throws Exception {
            Connection conn = ConnectionFactory.createConnection(conf);
            Table table = conn.getTable(TableName.valueOf("temp"));

            // Read a row
            try {
                Get get = new Get(Bytes.toBytes("row1"));
                table.get(get);/*from w w w.j  a va2 s. c o  m*/
                Assert.fail("Failure expected on an unauthorized user");
            } catch (IOException ex) {
                // expected
            }

            conn.close();
            return null;
        }
    });
}

From source file:org.apache.ranger.authorization.hbase.HBaseRangerAuthorizationTest.java

License:Apache License

@Test
public void testReadRowFromColFam2AsGroupIT() throws Exception {
    final Configuration conf = HBaseConfiguration.create();
    conf.set("hbase.zookeeper.quorum", "localhost");
    conf.set("hbase.zookeeper.property.clientPort", "" + port);
    conf.set("zookeeper.znode.parent", "/hbase-unsecure");

    String user = "public";

    UserGroupInformation ugi = UserGroupInformation.createUserForTesting(user, new String[] { "IT" });
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        public Void run() throws Exception {
            Connection conn = ConnectionFactory.createConnection(conf);
            Table table = conn.getTable(TableName.valueOf("temp"));

            // Read a row
            Get get = new Get(Bytes.toBytes("row1"));
            Result result = table.get(get);
            byte[] valResult = result.getValue(Bytes.toBytes("colfam2"), Bytes.toBytes("col1"));
            Assert.assertNull(valResult);

            conn.close();/*ww  w . j  a v  a2 s.  c  om*/
            return null;
        }
    });
}