Example usage for org.apache.zookeeper ZooKeeper addAuthInfo

List of usage examples for org.apache.zookeeper ZooKeeper addAuthInfo

Introduction

In this page you can find the example usage for org.apache.zookeeper ZooKeeper addAuthInfo.

Prototype

public void addAuthInfo(String scheme, byte[] auth) 

Source Link

Document

Add the specified scheme:auth information to this connection.

Usage

From source file:co.cask.tephra.zookeeper.TephraZKClientService.java

License:Apache License

/**
 * Creates a new ZooKeeper connection.//from  www . j a  va 2s.  co  m
 */
private ZooKeeper createZooKeeper() throws IOException {
    ZooKeeper zk = new ZooKeeper(zkStr, sessionTimeout, wrapWatcher(this));
    for (Map.Entry<String, byte[]> authInfo : authInfos.entries()) {
        zk.addAuthInfo(authInfo.getKey(), authInfo.getValue());
    }
    return zk;
}

From source file:com.cloudera.llama.am.LlamaHAFencer.java

License:Apache License

/**
 * Helper method to add the configured (shared) ZKAuths in case Curator's
 * underlying ZK Client is updated. This needs to be called before creating
 * the {@link #fencingPath} and in the call to {@link #fenceOthers}.
 *///from   w ww .  j  av a 2  s  . c o m
private void updateZKAuthsIfRequired() throws Exception {
    long latestZkClientIndex = client.getZookeeperClient().getInstanceIndex();
    assert (latestZkClientIndex >= zkClientIndex);

    while (latestZkClientIndex > zkClientIndex) {
        zkClientIndex = latestZkClientIndex;
        ZooKeeper zkClient = client.getZookeeperClient().getZooKeeper();
        for (ZKUtil.ZKAuthInfo zkAuth : conf.getZkAuths()) {
            zkClient.addAuthInfo(zkAuth.getScheme(), zkAuth.getAuth());
        }
    }
}

From source file:com.github.mosuka.zookeeper.nicli.command.AddAuthCommand.java

License:Apache License

@Override
public void run(Map<String, Object> parameters) {
    try {/*from  w ww  . j a v  a 2 s.co  m*/
        String scheme = (String) parameters.get("scheme");
        String auth = (String) parameters.get("auth");

        ZooKeeper zk = getZookeeperConnection().getZooKeeper();

        byte[] authByte = auth.getBytes();

        zk.addAuthInfo(scheme, authByte);

        setStatus(Command.STATUS_SUCCESS);
        setMessage(Command.SUCCESS_MESSAGE);
    } catch (ClassCastException e) {
        setStatus(Command.STATUS_ERROR);
        setMessage(e.getMessage());
    } catch (NullPointerException e) {
        setStatus(Command.STATUS_ERROR);
        setMessage(e.getMessage());
    }
}

From source file:com.sonian.elasticsearch.zookeeper.client.ZooKeeperFactory.java

License:Apache License

public ZooKeeper newZooKeeper(Watcher watcher) {
    try {//from   ww  w  . jav  a  2  s .  co m
        ZooKeeper zookeeper = new ZooKeeper(host, (int) sessionTimeout.millis(), watcher);
        if (username != null && password != null) {
            zookeeper.addAuthInfo("digest", String.format("%s:%s", username, password).getBytes());
        }
        return zookeeper;
    } catch (IOException e) {
        throw new ElasticsearchException("Cannot start ZooKeeper", e);
    }
}

From source file:com.twitter.common.zookeeper.ZooKeeperClient.java

License:Apache License

/**
 * Creates a set of credentials for the given authentication {@code scheme}.
 *
 * @param scheme the scheme to authenticate with
 * @param authToken the authentication token
 * @return a set of credentials that can be used to authenticate the zoo keeper client
 *//*from  www.  ja v  a 2s. co m*/
public static Credentials credentials(final String scheme, final byte[] authToken) {
    MorePreconditions.checkNotBlank(scheme);
    Preconditions.checkNotNull(authToken);

    return new Credentials() {
        @Override
        public void authenticate(ZooKeeper zooKeeper) {
            zooKeeper.addAuthInfo(scheme, authToken);
        }

        @Override
        public String scheme() {
            return scheme;
        }

        @Override
        public byte[] authToken() {
            return authToken;
        }

        @Override
        public boolean equals(Object o) {
            if (!(o instanceof Credentials)) {
                return false;
            }

            Credentials other = (Credentials) o;
            return new EqualsBuilder().append(scheme, other.scheme()).append(authToken, other.authToken())
                    .isEquals();
        }

        @Override
        public int hashCode() {
            return Objects.hashCode(scheme, authToken);
        }
    };
}

From source file:org.apache.accumulo.core.zookeeper.ZooSession.java

License:Apache License

public static ZooKeeper connect(String host, int timeout, String auth, Watcher watcher) {
    final int TIME_BETWEEN_CONNECT_CHECKS_MS = 100;
    final int TOTAL_CONNECT_TIME_WAIT_MS = 10 * 1000;
    boolean tryAgain = true;
    int sleepTime = 100;
    ZooKeeper zooKeeper = null;

    while (tryAgain) {
        try {//  w  ww . j  av  a  2 s .c om
            zooKeeper = new ZooKeeper(host, timeout, watcher);
            // it may take some time to get connected to zookeeper if some of the servers are down
            for (int i = 0; i < TOTAL_CONNECT_TIME_WAIT_MS / TIME_BETWEEN_CONNECT_CHECKS_MS && tryAgain; i++) {
                if (zooKeeper.getState().equals(States.CONNECTED)) {
                    if (auth != null)
                        zooKeeper.addAuthInfo("digest", auth.getBytes());
                    tryAgain = false;
                } else
                    UtilWaitThread.sleep(TIME_BETWEEN_CONNECT_CHECKS_MS);
            }
        } catch (UnknownHostException uhe) {
            // do not expect to recover from this
            log.warn(uhe.getClass().getName() + " : " + uhe.getMessage());
            throw new RuntimeException(uhe);
        } catch (IOException e) {
            log.warn("Connection to zooKeeper failed, will try again in "
                    + String.format("%.2f secs", sleepTime / 1000.0), e);
        } finally {
            if (tryAgain && zooKeeper != null)
                try {
                    zooKeeper.close();
                    zooKeeper = null;
                } catch (InterruptedException e) {
                    log.warn("interrupted", e);
                }
        }

        if (tryAgain) {
            UtilWaitThread.sleep(sleepTime);
            if (sleepTime < 10000)
                sleepTime = (int) (sleepTime + sleepTime * Math.random());
        }
    }

    return zooKeeper;
}

From source file:org.apache.accumulo.fate.zookeeper.ZooLockTest.java

License:Apache License

@Test(timeout = 10000)
public void testUnexpectedEvent() throws Exception {
    String parent = "/zltest-" + this.hashCode() + "-l" + pdCount++;

    ConnectedWatcher watcher = new ConnectedWatcher();
    ZooKeeper zk = new ZooKeeper(accumulo.getZooKeepers(), 30000, watcher);
    zk.addAuthInfo("digest", "secret".getBytes());

    while (!watcher.isConnected()) {
        Thread.sleep(200);/*from   w  w  w.j  av  a2 s  .  co m*/
    }

    zk.create(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

    ZooLock zl = new ZooLock(accumulo.getZooKeepers(), 30000, "digest", "secret".getBytes(), parent);

    Assert.assertFalse(zl.isLocked());

    // would not expect data to be set on this node, but it should not cause problems.....
    zk.setData(parent, "foo".getBytes(), -1);

    TestALW lw = new TestALW();

    zl.lockAsync(lw, "test1".getBytes());

    lw.waitForChanges(1);

    Assert.assertTrue(lw.locked);
    Assert.assertTrue(zl.isLocked());
    Assert.assertNull(lw.exception);
    Assert.assertNull(lw.reason);

    // would not expect data to be set on this node either
    zk.setData(zl.getLockPath(), "bar".getBytes(), -1);

    zk.delete(zl.getLockPath(), -1);

    lw.waitForChanges(2);

    Assert.assertEquals(LockLossReason.LOCK_DELETED, lw.reason);
    Assert.assertNull(lw.exception);

}

From source file:org.apache.accumulo.fate.zookeeper.ZooLockTest.java

License:Apache License

@Test(timeout = 10000)
public void testTryLock() throws Exception {
    String parent = "/zltest-" + this.hashCode() + "-l" + pdCount++;

    ZooLock zl = new ZooLock(accumulo.getZooKeepers(), 1000, "digest", "secret".getBytes(), parent);

    ConnectedWatcher watcher = new ConnectedWatcher();
    ZooKeeper zk = new ZooKeeper(accumulo.getZooKeepers(), 1000, watcher);
    zk.addAuthInfo("digest", "secret".getBytes());

    while (!watcher.isConnected()) {
        Thread.sleep(200);//from  w  w  w .  j ava2  s  . c  om
    }

    for (int i = 0; i < 10; i++) {
        zk.create(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        zk.delete(parent, -1);
    }

    zk.create(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

    TestALW lw = new TestALW();

    boolean ret = zl.tryLock(lw, "test1".getBytes());

    Assert.assertTrue(ret);

    // make sure still watching parent even though a lot of events occurred for the parent
    synchronized (zl) {
        Field field = zl.getClass().getDeclaredField("watchingParent");
        field.setAccessible(true);
        Assert.assertTrue((Boolean) field.get(zl));
    }

    zl.unlock();
}

From source file:org.apache.accumulo.fate.zookeeper.ZooLockTest.java

License:Apache License

@Test(timeout = 10000)
public void testChangeData() throws Exception {
    String parent = "/zltest-" + this.hashCode() + "-l" + pdCount++;
    ConnectedWatcher watcher = new ConnectedWatcher();
    ZooKeeper zk = new ZooKeeper(accumulo.getZooKeepers(), 1000, watcher);
    zk.addAuthInfo("digest", "secret".getBytes());

    while (!watcher.isConnected()) {
        Thread.sleep(200);/*from ww  w .  ja  v  a2  s .  c om*/
    }

    zk.create(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

    ZooLock zl = new ZooLock(accumulo.getZooKeepers(), 1000, "digest", "secret".getBytes(), parent);

    TestALW lw = new TestALW();

    zl.lockAsync(lw, "test1".getBytes());
    Assert.assertEquals("test1", new String(zk.getData(zl.getLockPath(), null, null)));

    zl.replaceLockData("test2".getBytes());
    Assert.assertEquals("test2", new String(zk.getData(zl.getLockPath(), null, null)));
}

From source file:org.apache.accumulo.fate.zookeeper.ZooSession.java

License:Apache License

/**
 * @param host/*from www. ja  v a2 s. co m*/
 *          comma separated list of zk servers
 * @param timeout
 *          in milliseconds
 * @param scheme
 *          authentication type, e.g. 'digest', may be null
 * @param auth
 *          authentication-scheme-specific token, may be null
 * @param watcher
 *          ZK notifications, may be null
 */
public static ZooKeeper connect(String host, int timeout, String scheme, byte[] auth, Watcher watcher) {
    final int TIME_BETWEEN_CONNECT_CHECKS_MS = 100;
    int connectTimeWait = Math.min(10 * 1000, timeout);
    boolean tryAgain = true;
    long sleepTime = 100;
    ZooKeeper zooKeeper = null;

    long startTime = System.currentTimeMillis();

    while (tryAgain) {
        try {
            zooKeeper = new ZooKeeper(host, timeout, watcher);
            // it may take some time to get connected to zookeeper if some of the servers are down
            for (int i = 0; i < connectTimeWait / TIME_BETWEEN_CONNECT_CHECKS_MS && tryAgain; i++) {
                if (zooKeeper.getState().equals(States.CONNECTED)) {
                    if (auth != null)
                        zooKeeper.addAuthInfo(scheme, auth);
                    tryAgain = false;
                } else
                    UtilWaitThread.sleep(TIME_BETWEEN_CONNECT_CHECKS_MS);
            }

        } catch (IOException e) {
            if (e instanceof UnknownHostException) {
                /*
                 * Make sure we wait atleast as long as the JVM TTL for negative DNS responses
                 */
                sleepTime = Math.max(sleepTime,
                        (AddressUtil.getAddressCacheNegativeTtl((UnknownHostException) e) + 1) * 1000);
            }
            log.warn("Connection to zooKeeper failed, will try again in "
                    + String.format("%.2f secs", sleepTime / 1000.0), e);
        } finally {
            if (tryAgain && zooKeeper != null)
                try {
                    zooKeeper.close();
                    zooKeeper = null;
                } catch (InterruptedException e) {
                    log.warn("interrupted", e);
                }
        }

        if (System.currentTimeMillis() - startTime > 2 * timeout) {
            throw new RuntimeException("Failed to connect to zookeeper (" + host
                    + ") within 2x zookeeper timeout period " + timeout);
        }

        if (tryAgain) {
            if (startTime + 2 * timeout < System.currentTimeMillis() + sleepTime + connectTimeWait)
                sleepTime = startTime + 2 * timeout - System.currentTimeMillis() - connectTimeWait;
            if (sleepTime < 0) {
                connectTimeWait -= sleepTime;
                sleepTime = 0;
            }
            UtilWaitThread.sleep(sleepTime);
            if (sleepTime < 10000)
                sleepTime = sleepTime + (long) (sleepTime * Math.random());
        }
    }

    return zooKeeper;
}