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

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

Introduction

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

Prototype

@InterfaceAudience.Public
@InterfaceStability.Evolving
public static UserGroupInformation getCurrentUser() throws IOException 

Source Link

Document

Return the current user, including any doAs in the current stack.

Usage

From source file:org.apache.accumulo.test.proxy.SimpleProxyBase.java

License:Apache License

@Test
public void userPermissions() throws Exception {
    String userName = getUniqueNames(1)[0];
    ClusterUser otherClient = null;/*from w  w  w .ja va2  s  . com*/
    ByteBuffer password = s2bb("password");
    ByteBuffer user;

    TestProxyClient origProxyClient = null;
    Client origClient = null;
    TestProxyClient userProxyClient = null;
    Client userClient = null;

    if (isKerberosEnabled()) {
        otherClient = getKdc().getClientPrincipal(1);
        userName = otherClient.getPrincipal();

        UserGroupInformation.loginUserFromKeytab(otherClient.getPrincipal(),
                otherClient.getKeytab().getAbsolutePath());
        final UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
        // Re-login in and make a new connection. Can't use the previous one

        userProxyClient = new TestProxyClient(hostname, proxyPort, factory, proxyPrimary, ugi);

        origProxyClient = proxyClient;
        origClient = client;
        userClient = client = userProxyClient.proxy();

        user = client.login(userName, Collections.<String, String>emptyMap());
    } else {
        userName = getUniqueNames(1)[0];
        // create a user
        client.createLocalUser(creds, userName, password);
        user = client.login(userName, s2pp(ByteBufferUtil.toString(password)));
    }

    // check permission failure
    try {
        client.createTable(user, "fail", true, TimeType.MILLIS);
        fail("should not create the table");
    } catch (AccumuloSecurityException ex) {
        if (isKerberosEnabled()) {
            // Switch back to original client
            UserGroupInformation.loginUserFromKeytab(clientPrincipal, clientKeytab.getAbsolutePath());
            client = origClient;
        }
        assertFalse(client.listTables(creds).contains("fail"));
    }
    // grant permissions and test
    assertFalse(client.hasSystemPermission(creds, userName, SystemPermission.CREATE_TABLE));
    client.grantSystemPermission(creds, userName, SystemPermission.CREATE_TABLE);
    assertTrue(client.hasSystemPermission(creds, userName, SystemPermission.CREATE_TABLE));
    if (isKerberosEnabled()) {
        // Switch back to the extra user
        UserGroupInformation.loginUserFromKeytab(otherClient.getPrincipal(),
                otherClient.getKeytab().getAbsolutePath());
        client = userClient;
    }
    client.createTable(user, "success", true, TimeType.MILLIS);
    if (isKerberosEnabled()) {
        // Switch back to original client
        UserGroupInformation.loginUserFromKeytab(clientPrincipal, clientKeytab.getAbsolutePath());
        client = origClient;
    }
    assertTrue(client.listTables(creds).contains("success"));

    // revoke permissions
    client.revokeSystemPermission(creds, userName, SystemPermission.CREATE_TABLE);
    assertFalse(client.hasSystemPermission(creds, userName, SystemPermission.CREATE_TABLE));
    try {
        if (isKerberosEnabled()) {
            // Switch back to the extra user
            UserGroupInformation.loginUserFromKeytab(otherClient.getPrincipal(),
                    otherClient.getKeytab().getAbsolutePath());
            client = userClient;
        }
        client.createTable(user, "fail", true, TimeType.MILLIS);
        fail("should not create the table");
    } catch (AccumuloSecurityException ex) {
        if (isKerberosEnabled()) {
            // Switch back to original client
            UserGroupInformation.loginUserFromKeytab(clientPrincipal, clientKeytab.getAbsolutePath());
            client = origClient;
        }
        assertFalse(client.listTables(creds).contains("fail"));
    }
    // denied!
    try {
        if (isKerberosEnabled()) {
            // Switch back to the extra user
            UserGroupInformation.loginUserFromKeytab(otherClient.getPrincipal(),
                    otherClient.getKeytab().getAbsolutePath());
            client = userClient;
        }
        String scanner = client.createScanner(user, tableName, null);
        client.nextK(scanner, 100);
        fail("stooge should not read table test");
    } catch (AccumuloSecurityException ex) {
    }

    if (isKerberosEnabled()) {
        // Switch back to original client
        UserGroupInformation.loginUserFromKeytab(clientPrincipal, clientKeytab.getAbsolutePath());
        client = origClient;
    }

    // grant
    assertFalse(client.hasTablePermission(creds, userName, tableName, TablePermission.READ));
    client.grantTablePermission(creds, userName, tableName, TablePermission.READ);
    assertTrue(client.hasTablePermission(creds, userName, tableName, TablePermission.READ));

    if (isKerberosEnabled()) {
        // Switch back to the extra user
        UserGroupInformation.loginUserFromKeytab(otherClient.getPrincipal(),
                otherClient.getKeytab().getAbsolutePath());
        client = userClient;
    }
    String scanner = client.createScanner(user, tableName, null);
    client.nextK(scanner, 10);
    client.closeScanner(scanner);

    if (isKerberosEnabled()) {
        // Switch back to original client
        UserGroupInformation.loginUserFromKeytab(clientPrincipal, clientKeytab.getAbsolutePath());
        client = origClient;
    }

    // revoke
    client.revokeTablePermission(creds, userName, tableName, TablePermission.READ);
    assertFalse(client.hasTablePermission(creds, userName, tableName, TablePermission.READ));
    try {
        if (isKerberosEnabled()) {
            // Switch back to the extra user
            UserGroupInformation.loginUserFromKeytab(otherClient.getPrincipal(),
                    otherClient.getKeytab().getAbsolutePath());
            client = userClient;
        }
        scanner = client.createScanner(user, tableName, null);
        client.nextK(scanner, 100);
        fail("stooge should not read table test");
    } catch (AccumuloSecurityException ex) {
    }

    if (isKerberosEnabled()) {
        // Switch back to original client
        UserGroupInformation.loginUserFromKeytab(clientPrincipal, clientKeytab.getAbsolutePath());
        client = origClient;
    }

    // delete user
    client.dropLocalUser(creds, userName);
    Set<String> users = client.listLocalUsers(creds);
    assertFalse("Should not see user after they are deleted", users.contains(userName));

    if (isKerberosEnabled()) {
        userProxyClient.close();
        proxyClient = origProxyClient;
        client = origClient;
    }
}

From source file:org.apache.accumulo.test.proxy.SimpleProxyBase.java

License:Apache License

@Test
public void namespacePermissions() throws Exception {
    String userName;//from ww w  .ja v a 2  s  . co m
    ClusterUser otherClient = null;
    ByteBuffer password = s2bb("password");
    ByteBuffer user;

    TestProxyClient origProxyClient = null;
    Client origClient = null;
    TestProxyClient userProxyClient = null;
    Client userClient = null;

    if (isKerberosEnabled()) {
        otherClient = getKdc().getClientPrincipal(1);
        userName = otherClient.getPrincipal();

        UserGroupInformation.loginUserFromKeytab(otherClient.getPrincipal(),
                otherClient.getKeytab().getAbsolutePath());
        final UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
        // Re-login in and make a new connection. Can't use the previous one

        userProxyClient = new TestProxyClient(hostname, proxyPort, factory, proxyPrimary, ugi);

        origProxyClient = proxyClient;
        origClient = client;
        userClient = client = userProxyClient.proxy();

        user = client.login(userName, Collections.<String, String>emptyMap());
    } else {
        userName = getUniqueNames(1)[0];
        // create a user
        client.createLocalUser(creds, userName, password);
        user = client.login(userName, s2pp(ByteBufferUtil.toString(password)));
    }

    // check permission failure
    try {
        client.createTable(user, namespaceName + ".fail", true, TimeType.MILLIS);
        fail("should not create the table");
    } catch (AccumuloSecurityException ex) {
        if (isKerberosEnabled()) {
            // Switch back to original client
            UserGroupInformation.loginUserFromKeytab(clientPrincipal, clientKeytab.getAbsolutePath());
            client = origClient;
        }
        assertFalse(client.listTables(creds).contains(namespaceName + ".fail"));
    }

    // grant permissions and test
    assertFalse(
            client.hasNamespacePermission(creds, userName, namespaceName, NamespacePermission.CREATE_TABLE));
    client.grantNamespacePermission(creds, userName, namespaceName, NamespacePermission.CREATE_TABLE);
    assertTrue(client.hasNamespacePermission(creds, userName, namespaceName, NamespacePermission.CREATE_TABLE));
    if (isKerberosEnabled()) {
        // Switch back to the extra user
        UserGroupInformation.loginUserFromKeytab(otherClient.getPrincipal(),
                otherClient.getKeytab().getAbsolutePath());
        client = userClient;
    }
    client.createTable(user, namespaceName + ".success", true, TimeType.MILLIS);
    if (isKerberosEnabled()) {
        // Switch back to original client
        UserGroupInformation.loginUserFromKeytab(clientPrincipal, clientKeytab.getAbsolutePath());
        client = origClient;
    }
    assertTrue(client.listTables(creds).contains(namespaceName + ".success"));

    // revoke permissions
    client.revokeNamespacePermission(creds, userName, namespaceName, NamespacePermission.CREATE_TABLE);
    assertFalse(
            client.hasNamespacePermission(creds, userName, namespaceName, NamespacePermission.CREATE_TABLE));
    try {
        if (isKerberosEnabled()) {
            // Switch back to the extra user
            UserGroupInformation.loginUserFromKeytab(otherClient.getPrincipal(),
                    otherClient.getKeytab().getAbsolutePath());
            client = userClient;
        }
        client.createTable(user, namespaceName + ".fail", true, TimeType.MILLIS);
        fail("should not create the table");
    } catch (AccumuloSecurityException ex) {
        if (isKerberosEnabled()) {
            // Switch back to original client
            UserGroupInformation.loginUserFromKeytab(clientPrincipal, clientKeytab.getAbsolutePath());
            client = origClient;
        }
        assertFalse(client.listTables(creds).contains(namespaceName + ".fail"));
    }

    // delete user
    client.dropLocalUser(creds, userName);
    Set<String> users = client.listLocalUsers(creds);
    assertFalse("Should not see user after they are deleted", users.contains(userName));

    if (isKerberosEnabled()) {
        userProxyClient.close();
        proxyClient = origProxyClient;
        client = origClient;
    }

    // delete table from namespace otherwise we can't delete namespace during teardown
    client.deleteTable(creds, namespaceName + ".success");
}

From source file:org.apache.accumulo.test.proxy.SimpleProxyBase.java

License:Apache License

@Test
public void testConditionalWriter() throws Exception {
    log.debug("Adding constraint {} to {}", tableName, NumericValueConstraint.class.getName());
    client.addConstraint(creds, tableName, NumericValueConstraint.class.getName());
    sleepUninterruptibly(ZOOKEEPER_PROPAGATION_TIME, TimeUnit.MILLISECONDS);

    // Take the table offline and online to force a config update
    client.offlineTable(creds, tableName, true);
    client.onlineTable(creds, tableName, true);

    while (!client.listConstraints(creds, tableName).containsKey(NumericValueConstraint.class.getName())) {
        log.info("Failed to see constraint");
        Thread.sleep(1000);//  w  w w.j  a  v  a 2  s  .  c o m
    }

    String cwid = client.createConditionalWriter(creds, tableName, new ConditionalWriterOptions());

    Map<ByteBuffer, ConditionalUpdates> updates = new HashMap<>();

    updates.put(s2bb("00345"), new ConditionalUpdates(Arrays.asList(newCondition("meta", "seq")),
            Arrays.asList(newColUpdate("meta", "seq", 10, "1"), newColUpdate("data", "img", "73435435"))));

    Map<ByteBuffer, ConditionalStatus> results = client.updateRowsConditionally(cwid, updates);

    assertEquals(1, results.size());
    assertEquals(ConditionalStatus.ACCEPTED, results.get(s2bb("00345")));

    assertScan(new String[][] { { "00345", "data", "img", "73435435" }, { "00345", "meta", "seq", "1" } },
            tableName);

    // test not setting values on conditions
    updates.clear();

    updates.put(s2bb("00345"), new ConditionalUpdates(Arrays.asList(newCondition("meta", "seq")),
            Arrays.asList(newColUpdate("meta", "seq", "2"))));
    updates.put(s2bb("00346"), new ConditionalUpdates(Arrays.asList(newCondition("meta", "seq")),
            Arrays.asList(newColUpdate("meta", "seq", "1"))));

    results = client.updateRowsConditionally(cwid, updates);

    assertEquals(2, results.size());
    assertEquals(ConditionalStatus.REJECTED, results.get(s2bb("00345")));
    assertEquals(ConditionalStatus.ACCEPTED, results.get(s2bb("00346")));

    assertScan(new String[][] { { "00345", "data", "img", "73435435" }, { "00345", "meta", "seq", "1" },
            { "00346", "meta", "seq", "1" } }, tableName);

    // test setting values on conditions
    updates.clear();

    updates.put(s2bb("00345"), new ConditionalUpdates(Arrays.asList(newCondition("meta", "seq", "1")),
            Arrays.asList(newColUpdate("meta", "seq", 20, "2"), newColUpdate("data", "img", "567890"))));

    updates.put(s2bb("00346"), new ConditionalUpdates(Arrays.asList(newCondition("meta", "seq", "2")),
            Arrays.asList(newColUpdate("meta", "seq", "3"))));

    results = client.updateRowsConditionally(cwid, updates);

    assertEquals(2, results.size());
    assertEquals(ConditionalStatus.ACCEPTED, results.get(s2bb("00345")));
    assertEquals(ConditionalStatus.REJECTED, results.get(s2bb("00346")));

    assertScan(new String[][] { { "00345", "data", "img", "567890" }, { "00345", "meta", "seq", "2" },
            { "00346", "meta", "seq", "1" } }, tableName);

    // test setting timestamp on condition to a non-existant version
    updates.clear();

    updates.put(s2bb("00345"), new ConditionalUpdates(Arrays.asList(newCondition("meta", "seq", 10, "2")),
            Arrays.asList(newColUpdate("meta", "seq", 30, "3"), newColUpdate("data", "img", "1234567890"))));

    results = client.updateRowsConditionally(cwid, updates);

    assertEquals(1, results.size());
    assertEquals(ConditionalStatus.REJECTED, results.get(s2bb("00345")));

    assertScan(new String[][] { { "00345", "data", "img", "567890" }, { "00345", "meta", "seq", "2" },
            { "00346", "meta", "seq", "1" } }, tableName);

    // test setting timestamp to an existing version

    updates.clear();

    updates.put(s2bb("00345"), new ConditionalUpdates(Arrays.asList(newCondition("meta", "seq", 20, "2")),
            Arrays.asList(newColUpdate("meta", "seq", 30, "3"), newColUpdate("data", "img", "1234567890"))));

    results = client.updateRowsConditionally(cwid, updates);

    assertEquals(1, results.size());
    assertEquals(ConditionalStatus.ACCEPTED, results.get(s2bb("00345")));

    assertScan(new String[][] { { "00345", "data", "img", "1234567890" }, { "00345", "meta", "seq", "3" },
            { "00346", "meta", "seq", "1" } }, tableName);

    // run test w/ condition that has iterators
    // following should fail w/o iterator
    client.updateAndFlush(creds, tableName,
            Collections.singletonMap(s2bb("00347"), Arrays.asList(newColUpdate("data", "count", "1"))));
    client.updateAndFlush(creds, tableName,
            Collections.singletonMap(s2bb("00347"), Arrays.asList(newColUpdate("data", "count", "1"))));
    client.updateAndFlush(creds, tableName,
            Collections.singletonMap(s2bb("00347"), Arrays.asList(newColUpdate("data", "count", "1"))));

    updates.clear();
    updates.put(s2bb("00347"), new ConditionalUpdates(Arrays.asList(newCondition("data", "count", "3")),
            Arrays.asList(newColUpdate("data", "img", "1234567890"))));

    results = client.updateRowsConditionally(cwid, updates);

    assertEquals(1, results.size());
    assertEquals(ConditionalStatus.REJECTED, results.get(s2bb("00347")));

    assertScan(new String[][] { { "00345", "data", "img", "1234567890" }, { "00345", "meta", "seq", "3" },
            { "00346", "meta", "seq", "1" }, { "00347", "data", "count", "1" } }, tableName);

    // following test w/ iterator setup should succeed
    Condition iterCond = newCondition("data", "count", "3");
    Map<String, String> props = new HashMap<>();
    props.put("type", "STRING");
    props.put("columns", "data:count");
    IteratorSetting is = new IteratorSetting(1, "sumc", SummingCombiner.class.getName(), props);
    iterCond.setIterators(Arrays.asList(is));

    updates.clear();
    updates.put(s2bb("00347"), new ConditionalUpdates(Arrays.asList(iterCond),
            Arrays.asList(newColUpdate("data", "img", "1234567890"))));

    results = client.updateRowsConditionally(cwid, updates);

    assertEquals(1, results.size());
    assertEquals(ConditionalStatus.ACCEPTED, results.get(s2bb("00347")));

    assertScan(new String[][] { { "00345", "data", "img", "1234567890" }, { "00345", "meta", "seq", "3" },
            { "00346", "meta", "seq", "1" }, { "00347", "data", "count", "1" },
            { "00347", "data", "img", "1234567890" } }, tableName);

    ConditionalStatus status = null;
    for (int i = 0; i < 30; i++) {
        // test a mutation that violated a constraint
        updates.clear();
        updates.put(s2bb("00347"),
                new ConditionalUpdates(Arrays.asList(newCondition("data", "img", "1234567890")),
                        Arrays.asList(newColUpdate("data", "count", "A"))));

        results = client.updateRowsConditionally(cwid, updates);

        assertEquals(1, results.size());
        status = results.get(s2bb("00347"));
        if (ConditionalStatus.VIOLATED != status) {
            log.info(
                    "ConditionalUpdate was not rejected by server due to table constraint. Sleeping and retrying");
            Thread.sleep(5000);
            continue;
        }

        assertEquals(ConditionalStatus.VIOLATED, status);
        break;
    }

    // Final check to make sure we succeeded and didn't exceed the retries
    assertEquals(ConditionalStatus.VIOLATED, status);

    assertScan(new String[][] { { "00345", "data", "img", "1234567890" }, { "00345", "meta", "seq", "3" },
            { "00346", "meta", "seq", "1" }, { "00347", "data", "count", "1" },
            { "00347", "data", "img", "1234567890" } }, tableName);

    // run test with two conditions
    // both conditions should fail
    updates.clear();
    updates.put(s2bb("00347"), new ConditionalUpdates(
            Arrays.asList(newCondition("data", "img", "565"), newCondition("data", "count", "2")),
            Arrays.asList(newColUpdate("data", "count", "3"), newColUpdate("data", "img", "0987654321"))));

    results = client.updateRowsConditionally(cwid, updates);

    assertEquals(1, results.size());
    assertEquals(ConditionalStatus.REJECTED, results.get(s2bb("00347")));

    assertScan(new String[][] { { "00345", "data", "img", "1234567890" }, { "00345", "meta", "seq", "3" },
            { "00346", "meta", "seq", "1" }, { "00347", "data", "count", "1" },
            { "00347", "data", "img", "1234567890" } }, tableName);

    // one condition should fail
    updates.clear();
    updates.put(s2bb("00347"), new ConditionalUpdates(
            Arrays.asList(newCondition("data", "img", "1234567890"), newCondition("data", "count", "2")),
            Arrays.asList(newColUpdate("data", "count", "3"), newColUpdate("data", "img", "0987654321"))));

    results = client.updateRowsConditionally(cwid, updates);

    assertEquals(1, results.size());
    assertEquals(ConditionalStatus.REJECTED, results.get(s2bb("00347")));

    assertScan(new String[][] { { "00345", "data", "img", "1234567890" }, { "00345", "meta", "seq", "3" },
            { "00346", "meta", "seq", "1" }, { "00347", "data", "count", "1" },
            { "00347", "data", "img", "1234567890" } }, tableName);

    // one condition should fail
    updates.clear();
    updates.put(s2bb("00347"), new ConditionalUpdates(
            Arrays.asList(newCondition("data", "img", "565"), newCondition("data", "count", "1")),
            Arrays.asList(newColUpdate("data", "count", "3"), newColUpdate("data", "img", "0987654321"))));

    results = client.updateRowsConditionally(cwid, updates);

    assertEquals(1, results.size());
    assertEquals(ConditionalStatus.REJECTED, results.get(s2bb("00347")));

    assertScan(new String[][] { { "00345", "data", "img", "1234567890" }, { "00345", "meta", "seq", "3" },
            { "00346", "meta", "seq", "1" }, { "00347", "data", "count", "1" },
            { "00347", "data", "img", "1234567890" } }, tableName);

    // both conditions should succeed

    ConditionalStatus result = client.updateRowConditionally(creds, tableName, s2bb("00347"),
            new ConditionalUpdates(
                    Arrays.asList(newCondition("data", "img", "1234567890"),
                            newCondition("data", "count", "1")),
                    Arrays.asList(newColUpdate("data", "count", "3"),
                            newColUpdate("data", "img", "0987654321"))));

    assertEquals(ConditionalStatus.ACCEPTED, result);

    assertScan(new String[][] { { "00345", "data", "img", "1234567890" }, { "00345", "meta", "seq", "3" },
            { "00346", "meta", "seq", "1" }, { "00347", "data", "count", "3" },
            { "00347", "data", "img", "0987654321" } }, tableName);

    client.closeConditionalWriter(cwid);
    try {
        client.updateRowsConditionally(cwid, updates);
        fail("conditional writer not closed");
    } catch (UnknownWriter uk) {
    }

    String principal;
    ClusterUser cwuser = null;
    if (isKerberosEnabled()) {
        cwuser = getKdc().getClientPrincipal(1);
        principal = cwuser.getPrincipal();
        client.createLocalUser(creds, principal, s2bb("unused"));

    } else {
        principal = "cwuser";
        // run test with colvis
        client.createLocalUser(creds, principal, s2bb("bestpasswordever"));
    }

    client.changeUserAuthorizations(creds, principal, Collections.singleton(s2bb("A")));
    client.grantTablePermission(creds, principal, tableName, TablePermission.WRITE);
    client.grantTablePermission(creds, principal, tableName, TablePermission.READ);

    TestProxyClient cwuserProxyClient = null;
    Client origClient = null;
    Map<String, String> cwProperties;
    if (isKerberosEnabled()) {
        UserGroupInformation.loginUserFromKeytab(cwuser.getPrincipal(), cwuser.getKeytab().getAbsolutePath());
        final UserGroupInformation cwuserUgi = UserGroupInformation.getCurrentUser();
        // Re-login in and make a new connection. Can't use the previous one
        cwuserProxyClient = new TestProxyClient(hostname, proxyPort, factory, proxyPrimary, cwuserUgi);
        origClient = client;
        client = cwuserProxyClient.proxy();
        cwProperties = Collections.emptyMap();
    } else {
        cwProperties = Collections.singletonMap("password", "bestpasswordever");
    }

    try {
        ByteBuffer cwCreds = client.login(principal, cwProperties);

        cwid = client.createConditionalWriter(cwCreds, tableName,
                new ConditionalWriterOptions().setAuthorizations(Collections.singleton(s2bb("A"))));

        updates.clear();
        updates.put(s2bb("00348"),
                new ConditionalUpdates(
                        Arrays.asList(new Condition(new Column(s2bb("data"), s2bb("c"), s2bb("A")))),
                        Arrays.asList(newColUpdate("data", "seq", "1"),
                                newColUpdate("data", "c", "1").setColVisibility(s2bb("A")))));
        updates.put(s2bb("00349"),
                new ConditionalUpdates(
                        Arrays.asList(new Condition(new Column(s2bb("data"), s2bb("c"), s2bb("B")))),
                        Arrays.asList(newColUpdate("data", "seq", "1"))));

        results = client.updateRowsConditionally(cwid, updates);

        assertEquals(2, results.size());
        assertEquals(ConditionalStatus.ACCEPTED, results.get(s2bb("00348")));
        assertEquals(ConditionalStatus.INVISIBLE_VISIBILITY, results.get(s2bb("00349")));

        if (isKerberosEnabled()) {
            UserGroupInformation.loginUserFromKeytab(clientPrincipal, clientKeytab.getAbsolutePath());
            client = origClient;
        }
        // Verify that the original user can't see the updates with visibilities set
        assertScan(new String[][] { { "00345", "data", "img", "1234567890" }, { "00345", "meta", "seq", "3" },
                { "00346", "meta", "seq", "1" }, { "00347", "data", "count", "3" },
                { "00347", "data", "img", "0987654321" }, { "00348", "data", "seq", "1" } }, tableName);

        if (isKerberosEnabled()) {
            UserGroupInformation.loginUserFromKeytab(cwuser.getPrincipal(),
                    cwuser.getKeytab().getAbsolutePath());
            client = cwuserProxyClient.proxy();
        }

        updates.clear();

        updates.clear();
        updates.put(s2bb("00348"), new ConditionalUpdates(
                Arrays.asList(
                        new Condition(new Column(s2bb("data"), s2bb("c"), s2bb("A"))).setValue(s2bb("0"))),
                Arrays.asList(newColUpdate("data", "seq", "2"),
                        newColUpdate("data", "c", "2").setColVisibility(s2bb("A")))));

        results = client.updateRowsConditionally(cwid, updates);

        assertEquals(1, results.size());
        assertEquals(ConditionalStatus.REJECTED, results.get(s2bb("00348")));

        if (isKerberosEnabled()) {
            UserGroupInformation.loginUserFromKeytab(clientPrincipal, clientKeytab.getAbsolutePath());
            client = origClient;
        }

        // Same results as the original user
        assertScan(new String[][] { { "00345", "data", "img", "1234567890" }, { "00345", "meta", "seq", "3" },
                { "00346", "meta", "seq", "1" }, { "00347", "data", "count", "3" },
                { "00347", "data", "img", "0987654321" }, { "00348", "data", "seq", "1" } }, tableName);

        if (isKerberosEnabled()) {
            UserGroupInformation.loginUserFromKeytab(cwuser.getPrincipal(),
                    cwuser.getKeytab().getAbsolutePath());
            client = cwuserProxyClient.proxy();
        }

        updates.clear();
        updates.put(s2bb("00348"), new ConditionalUpdates(
                Arrays.asList(
                        new Condition(new Column(s2bb("data"), s2bb("c"), s2bb("A"))).setValue(s2bb("1"))),
                Arrays.asList(newColUpdate("data", "seq", "2"),
                        newColUpdate("data", "c", "2").setColVisibility(s2bb("A")))));

        results = client.updateRowsConditionally(cwid, updates);

        assertEquals(1, results.size());
        assertEquals(ConditionalStatus.ACCEPTED, results.get(s2bb("00348")));

        if (isKerberosEnabled()) {
            UserGroupInformation.loginUserFromKeytab(clientPrincipal, clientKeytab.getAbsolutePath());
            client = origClient;
        }

        assertScan(new String[][] { { "00345", "data", "img", "1234567890" }, { "00345", "meta", "seq", "3" },
                { "00346", "meta", "seq", "1" }, { "00347", "data", "count", "3" },
                { "00347", "data", "img", "0987654321" }, { "00348", "data", "seq", "2" } }, tableName);

        if (isKerberosEnabled()) {
            UserGroupInformation.loginUserFromKeytab(cwuser.getPrincipal(),
                    cwuser.getKeytab().getAbsolutePath());
            client = cwuserProxyClient.proxy();
        }

        client.closeConditionalWriter(cwid);
        try {
            client.updateRowsConditionally(cwid, updates);
            fail("conditional writer not closed");
        } catch (UnknownWriter uk) {
        }
    } finally {
        if (isKerberosEnabled()) {
            // Close the other client
            if (null != cwuserProxyClient) {
                cwuserProxyClient.close();
            }

            UserGroupInformation.loginUserFromKeytab(clientPrincipal, clientKeytab.getAbsolutePath());
            // Re-login and restore the original client
            client = origClient;
        }
        client.dropLocalUser(creds, principal);
    }
}

From source file:org.apache.accumulo.test.randomwalk.multitable.CopyTool.java

License:Apache License

@Override
public int run(String[] args) throws Exception {
    Job job = Job.getInstance(getConf(), this.getClass().getSimpleName());
    job.setJarByClass(this.getClass());

    if (job.getJar() == null) {
        log.error("M/R requires a jar file!  Run mvn package.");
        return 1;
    }//from  w  w w  .  j a  va 2  s  . c om

    ClientConfiguration clientConf = new ClientConfiguration().withInstance(args[3]).withZkHosts(args[4]);

    job.setInputFormatClass(AccumuloInputFormat.class);
    AccumuloInputFormat.setInputTableName(job, args[2]);
    AccumuloInputFormat.setScanAuthorizations(job, Authorizations.EMPTY);
    AccumuloInputFormat.setZooKeeperInstance(job, clientConf);

    final String principal;
    final AuthenticationToken token;
    if (clientConf.getBoolean(ClientProperty.INSTANCE_RPC_SASL_ENABLED.getKey(), false)) {
        // Use the Kerberos creds to request a DelegationToken for MapReduce to use
        // We could use the specified keytab (args[1]), but we're already logged in and don't need to, so we can just use the current user
        KerberosToken kt = new KerberosToken();
        try {
            UserGroupInformation user = UserGroupInformation.getCurrentUser();
            if (!user.hasKerberosCredentials()) {
                throw new IllegalStateException("Expected current user to have Kerberos credentials");
            }

            // Get the principal via UGI
            principal = user.getUserName();

            // Connector w/ the Kerberos creds
            ZooKeeperInstance inst = new ZooKeeperInstance(clientConf);
            Connector conn = inst.getConnector(principal, kt);

            // Do the explicit check to see if the user has the permission to get a delegation token
            if (!conn.securityOperations().hasSystemPermission(conn.whoami(),
                    SystemPermission.OBTAIN_DELEGATION_TOKEN)) {
                log.error(principal + " doesn't have the " + SystemPermission.OBTAIN_DELEGATION_TOKEN.name()
                        + " SystemPermission neccesary to obtain a delegation token. MapReduce tasks cannot automatically use the client's"
                        + " credentials on remote servers. Delegation tokens provide a means to run MapReduce without distributing the user's credentials.");
                throw new IllegalStateException(
                        conn.whoami() + " does not have permission to obtain a delegation token");
            }

            // Fetch a delegation token from Accumulo
            token = conn.securityOperations().getDelegationToken(new DelegationTokenConfig());

        } catch (Exception e) {
            final String msg = "Failed to acquire DelegationToken for use with MapReduce";
            log.error(msg, e);
            throw new RuntimeException(msg, e);
        }
    } else {
        // Simple principal + password
        principal = args[0];
        token = new PasswordToken(args[1]);
    }

    AccumuloInputFormat.setConnectorInfo(job, principal, token);
    AccumuloOutputFormat.setConnectorInfo(job, principal, token);

    job.setMapperClass(SeqMapClass.class);
    job.setMapOutputKeyClass(Text.class);
    job.setMapOutputValueClass(Mutation.class);

    job.setNumReduceTasks(0);

    job.setOutputFormatClass(AccumuloOutputFormat.class);
    AccumuloOutputFormat.setCreateTables(job, true);
    AccumuloOutputFormat.setDefaultTableName(job, args[5]);
    AccumuloOutputFormat.setZooKeeperInstance(job, clientConf);

    job.waitForCompletion(true);
    return job.isSuccessful() ? 0 : 1;
}

From source file:org.apache.accumulo.test.randomwalk.sequential.MapRedVerifyTool.java

License:Apache License

@Override
public int run(String[] args) throws Exception {
    Job job = Job.getInstance(getConf(), this.getClass().getSimpleName());
    job.setJarByClass(this.getClass());

    if (job.getJar() == null) {
        log.error("M/R requires a jar file!  Run mvn package.");
        return 1;
    }//from   w  w  w .  ja v  a2s .c  o  m

    ClientConfiguration clientConf = ClientConfiguration.loadDefault().withInstance(args[3])
            .withZkHosts(args[4]);

    AccumuloInputFormat.setInputTableName(job, args[2]);
    AccumuloInputFormat.setZooKeeperInstance(job, clientConf);
    AccumuloOutputFormat.setDefaultTableName(job, args[5]);
    AccumuloOutputFormat.setZooKeeperInstance(job, clientConf);

    job.setInputFormatClass(AccumuloInputFormat.class);
    if (clientConf.getBoolean(ClientProperty.INSTANCE_RPC_SASL_ENABLED.getKey(), false)) {
        // Better be logged in
        KerberosToken token = new KerberosToken();
        try {
            UserGroupInformation user = UserGroupInformation.getCurrentUser();
            if (!user.hasKerberosCredentials()) {
                throw new IllegalStateException("Expected current user to have Kerberos credentials");
            }

            String newPrincipal = user.getUserName();

            ZooKeeperInstance inst = new ZooKeeperInstance(clientConf);
            Connector conn = inst.getConnector(newPrincipal, token);

            // Do the explicit check to see if the user has the permission to get a delegation token
            if (!conn.securityOperations().hasSystemPermission(conn.whoami(),
                    SystemPermission.OBTAIN_DELEGATION_TOKEN)) {
                log.error(newPrincipal + " doesn't have the " + SystemPermission.OBTAIN_DELEGATION_TOKEN.name()
                        + " SystemPermission neccesary to obtain a delegation token. MapReduce tasks cannot automatically use the client's"
                        + " credentials on remote servers. Delegation tokens provide a means to run MapReduce without distributing the user's credentials.");
                throw new IllegalStateException(
                        conn.whoami() + " does not have permission to obtain a delegation token");
            }

            // Fetch a delegation token from Accumulo
            AuthenticationToken dt = conn.securityOperations().getDelegationToken(new DelegationTokenConfig());

            // Set the delegation token instead of the kerberos token
            AccumuloInputFormat.setConnectorInfo(job, newPrincipal, dt);
            AccumuloOutputFormat.setConnectorInfo(job, newPrincipal, dt);
        } catch (Exception e) {
            final String msg = "Failed to acquire DelegationToken for use with MapReduce";
            log.error(msg, e);
            throw new RuntimeException(msg, e);
        }
    } else {
        AccumuloInputFormat.setConnectorInfo(job, args[0], new PasswordToken(args[1]));
        AccumuloOutputFormat.setConnectorInfo(job, args[0], new PasswordToken(args[1]));
    }

    job.setMapperClass(SeqMapClass.class);
    job.setMapOutputKeyClass(NullWritable.class);
    job.setMapOutputValueClass(IntWritable.class);

    job.setReducerClass(SeqReduceClass.class);
    job.setNumReduceTasks(1);

    job.setOutputFormatClass(AccumuloOutputFormat.class);
    AccumuloOutputFormat.setCreateTables(job, true);

    job.waitForCompletion(true);
    return job.isSuccessful() ? 0 : 1;
}

From source file:org.apache.accumulo.test.security.KerberosClientOptsTest.java

License:Apache License

@Test
public void testParseArgsPerformsLogin() throws Exception {
    String user = testName.getMethodName();
    File userKeytab = new File(kdc.getKeytabDir(), user + ".keytab");
    if (userKeytab.exists() && !userKeytab.delete()) {
        log.warn("Unable to delete {}", userKeytab);
    }//from  ww  w . j  a va 2  s. c  o m

    kdc.createPrincipal(userKeytab, user);

    user = kdc.qualifyUser(user);

    ClientOpts opts = new ClientOpts();
    String[] args = new String[] { "--sasl", "--keytab", userKeytab.getAbsolutePath(), "-u", user };
    opts.parseArgs(testName.getMethodName(), args);

    UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
    assertEquals(user, ugi.getUserName());
    assertEquals(AuthenticationMethod.KERBEROS, ugi.getAuthenticationMethod());
}

From source file:org.apache.accumulo.testing.core.randomwalk.multitable.CopyTool.java

License:Apache License

@Override
public int run(String[] args) throws Exception {
    Job job = Job.getInstance(getConf(), this.getClass().getSimpleName());
    job.setJarByClass(this.getClass());

    if (job.getJar() == null) {
        log.error("M/R requires a jar file!  Run mvn package.");
        return 1;
    }//from www .j a va  2  s . c  o  m

    ClientConfiguration clientConf = new ClientConfiguration().withInstance(args[3]).withZkHosts(args[4]);

    job.setInputFormatClass(AccumuloInputFormat.class);
    AccumuloInputFormat.setInputTableName(job, args[2]);
    AccumuloInputFormat.setScanAuthorizations(job, Authorizations.EMPTY);
    AccumuloInputFormat.setZooKeeperInstance(job, clientConf);

    final String principal;
    final AuthenticationToken token;
    if (clientConf.getBoolean(ClientProperty.INSTANCE_RPC_SASL_ENABLED.getKey(), false)) {
        // Use the Kerberos creds to request a DelegationToken for MapReduce
        // to use
        // We could use the specified keytab (args[1]), but we're already
        // logged in and don't need to, so we can just use the current user
        KerberosToken kt = new KerberosToken();
        try {
            UserGroupInformation user = UserGroupInformation.getCurrentUser();
            if (!user.hasKerberosCredentials()) {
                throw new IllegalStateException("Expected current user to have Kerberos credentials");
            }

            // Get the principal via UGI
            principal = user.getUserName();

            // Connector w/ the Kerberos creds
            ZooKeeperInstance inst = new ZooKeeperInstance(clientConf);
            Connector conn = inst.getConnector(principal, kt);

            // Do the explicit check to see if the user has the permission
            // to get a delegation token
            if (!conn.securityOperations().hasSystemPermission(conn.whoami(),
                    SystemPermission.OBTAIN_DELEGATION_TOKEN)) {
                log.error(principal + " doesn't have the " + SystemPermission.OBTAIN_DELEGATION_TOKEN.name()
                        + " SystemPermission neccesary to obtain a delegation token. MapReduce tasks cannot automatically use the client's"
                        + " credentials on remote servers. Delegation tokens provide a means to run MapReduce without distributing the user's credentials.");
                throw new IllegalStateException(
                        conn.whoami() + " does not have permission to obtain a delegation token");
            }

            // Fetch a delegation token from Accumulo
            token = conn.securityOperations().getDelegationToken(new DelegationTokenConfig());

        } catch (Exception e) {
            final String msg = "Failed to acquire DelegationToken for use with MapReduce";
            log.error(msg, e);
            throw new RuntimeException(msg, e);
        }
    } else {
        // Simple principal + password
        principal = args[0];
        token = new PasswordToken(args[1]);
    }

    AccumuloInputFormat.setConnectorInfo(job, principal, token);
    AccumuloOutputFormat.setConnectorInfo(job, principal, token);

    job.setMapperClass(SeqMapClass.class);
    job.setMapOutputKeyClass(Text.class);
    job.setMapOutputValueClass(Mutation.class);

    job.setNumReduceTasks(0);

    job.setOutputFormatClass(AccumuloOutputFormat.class);
    AccumuloOutputFormat.setCreateTables(job, true);
    AccumuloOutputFormat.setDefaultTableName(job, args[5]);
    AccumuloOutputFormat.setZooKeeperInstance(job, clientConf);

    job.waitForCompletion(true);
    return job.isSuccessful() ? 0 : 1;
}

From source file:org.apache.accumulo.testing.core.randomwalk.sequential.MapRedVerifyTool.java

License:Apache License

@Override
public int run(String[] args) throws Exception {
    Job job = Job.getInstance(getConf(), this.getClass().getSimpleName());
    job.setJarByClass(this.getClass());

    if (job.getJar() == null) {
        log.error("M/R requires a jar file!  Run mvn package.");
        return 1;
    }/*w  w  w .j  a v a  2 s  .c o m*/

    ClientConfiguration clientConf = ClientConfiguration.loadDefault().withInstance(args[3])
            .withZkHosts(args[4]);

    AccumuloInputFormat.setInputTableName(job, args[2]);
    AccumuloInputFormat.setZooKeeperInstance(job, clientConf);
    AccumuloOutputFormat.setDefaultTableName(job, args[5]);
    AccumuloOutputFormat.setZooKeeperInstance(job, clientConf);

    job.setInputFormatClass(AccumuloInputFormat.class);
    if (clientConf.getBoolean(ClientProperty.INSTANCE_RPC_SASL_ENABLED.getKey(), false)) {
        // Better be logged in
        KerberosToken token = new KerberosToken();
        try {
            UserGroupInformation user = UserGroupInformation.getCurrentUser();
            if (!user.hasKerberosCredentials()) {
                throw new IllegalStateException("Expected current user to have Kerberos credentials");
            }

            String newPrincipal = user.getUserName();

            ZooKeeperInstance inst = new ZooKeeperInstance(clientConf);
            Connector conn = inst.getConnector(newPrincipal, token);

            // Do the explicit check to see if the user has the permission
            // to get a delegation token
            if (!conn.securityOperations().hasSystemPermission(conn.whoami(),
                    SystemPermission.OBTAIN_DELEGATION_TOKEN)) {
                log.error(newPrincipal + " doesn't have the " + SystemPermission.OBTAIN_DELEGATION_TOKEN.name()
                        + " SystemPermission neccesary to obtain a delegation token. MapReduce tasks cannot automatically use the client's"
                        + " credentials on remote servers. Delegation tokens provide a means to run MapReduce without distributing the user's credentials.");
                throw new IllegalStateException(
                        conn.whoami() + " does not have permission to obtain a delegation token");
            }

            // Fetch a delegation token from Accumulo
            AuthenticationToken dt = conn.securityOperations().getDelegationToken(new DelegationTokenConfig());

            // Set the delegation token instead of the kerberos token
            AccumuloInputFormat.setConnectorInfo(job, newPrincipal, dt);
            AccumuloOutputFormat.setConnectorInfo(job, newPrincipal, dt);
        } catch (Exception e) {
            final String msg = "Failed to acquire DelegationToken for use with MapReduce";
            log.error(msg, e);
            throw new RuntimeException(msg, e);
        }
    } else {
        AccumuloInputFormat.setConnectorInfo(job, args[0], new PasswordToken(args[1]));
        AccumuloOutputFormat.setConnectorInfo(job, args[0], new PasswordToken(args[1]));
    }

    job.setMapperClass(SeqMapClass.class);
    job.setMapOutputKeyClass(NullWritable.class);
    job.setMapOutputValueClass(IntWritable.class);

    job.setReducerClass(SeqReduceClass.class);
    job.setNumReduceTasks(1);

    job.setOutputFormatClass(AccumuloOutputFormat.class);
    AccumuloOutputFormat.setCreateTables(job, true);

    job.waitForCompletion(true);
    return job.isSuccessful() ? 0 : 1;
}

From source file:org.apache.accumulo.tserver.replication.AccumuloReplicaSystem.java

License:Apache License

@Override
public Status replicate(final Path p, final Status status, final ReplicationTarget target,
        final ReplicaSystemHelper helper) {
    final Instance localInstance = HdfsZooInstance.getInstance();
    final AccumuloConfiguration localConf = new ServerConfigurationFactory(localInstance).getConfiguration();

    final String principal = getPrincipal(localConf, target);
    final File keytab;
    final String password;
    if (localConf.getBoolean(Property.INSTANCE_RPC_SASL_ENABLED)) {
        String keytabPath = getKeytab(localConf, target);
        keytab = new File(keytabPath);
        if (!keytab.exists() || !keytab.isFile()) {
            log.error("{} is not a regular file. Cannot login to replicate", keytabPath);
            return status;
        }//ww  w.j  av  a  2s. c o m
        password = null;
    } else {
        keytab = null;
        password = getPassword(localConf, target);
    }

    if (null != keytab) {
        try {
            final UserGroupInformation accumuloUgi = UserGroupInformation.getCurrentUser();
            // Get a UGI with the principal + keytab
            UserGroupInformation ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(principal,
                    keytab.getAbsolutePath());

            // Run inside a doAs to avoid nuking the Tserver's user
            return ugi.doAs(new PrivilegedAction<Status>() {
                @Override
                public Status run() {
                    KerberosToken token;
                    try {
                        // Do *not* replace the current user
                        token = new KerberosToken(principal, keytab);
                    } catch (IOException e) {
                        log.error("Failed to create KerberosToken", e);
                        return status;
                    }
                    ClientContext peerContext = getContextForPeer(localConf, target, principal, token);
                    return _replicate(p, status, target, helper, localConf, peerContext, accumuloUgi);
                }
            });
        } catch (IOException e) {
            // Can't log in, can't replicate
            log.error("Failed to perform local login", e);
            return status;
        }
    } else {
        // Simple case: make a password token, context and then replicate
        PasswordToken token = new PasswordToken(password);
        ClientContext peerContext = getContextForPeer(localConf, target, principal, token);
        return _replicate(p, status, target, helper, localConf, peerContext, null);
    }
}

From source file:org.apache.ambari.servicemonitor.utils.MonitorUtils.java

License:Apache License

public static AdminOperationsProtocol createJTAdminProxy(InetSocketAddress addr, Configuration conf)
        throws IOException {
    return (AdminOperationsProtocol) RPC.getProxy(AdminOperationsProtocol.class,
            AdminOperationsProtocol.versionID, addr, UserGroupInformation.getCurrentUser(), conf,
            NetUtils.getSocketFactory(conf, AdminOperationsProtocol.class));
}