Search in sources :

Example 21 with CuratorEvent

use of org.apache.curator.framework.api.CuratorEvent in project xian by happyyangyuan.

the class LeaderLatch method reset.

@VisibleForTesting
void reset() throws Exception {
    setLeadership(false);
    setNode(null);
    BackgroundCallback callback = new BackgroundCallback() {

        @Override
        public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
            if (debugResetWaitLatch != null) {
                debugResetWaitLatch.await();
                debugResetWaitLatch = null;
            }
            if (event.getResultCode() == KeeperException.Code.OK.intValue()) {
                setNode(event.getName());
                if (state.get() == State.CLOSED) {
                    setNode(null);
                } else {
                    getChildren();
                }
            } else {
                log.error("getChildren() failed. rc = " + event.getResultCode());
            }
        }
    };
    client.create().creatingParentContainersIfNeeded().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).inBackground(callback).forPath(ZKPaths.makePath(latchPath, LOCK_NAME), LeaderSelector.getIdBytes(id));
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) BackgroundCallback(org.apache.curator.framework.api.BackgroundCallback) CuratorEvent(org.apache.curator.framework.api.CuratorEvent) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 22 with CuratorEvent

use of org.apache.curator.framework.api.CuratorEvent in project xian by happyyangyuan.

the class LeaderLatch method checkLeadership.

private void checkLeadership(List<String> children) throws Exception {
    final String localOurPath = ourPath.get();
    List<String> sortedChildren = LockInternals.getSortedChildren(LOCK_NAME, sorter, children);
    int ourIndex = (localOurPath != null) ? sortedChildren.indexOf(ZKPaths.getNodeFromPath(localOurPath)) : -1;
    if (ourIndex < 0) {
        log.error("Can't find our node. Resetting. Index: " + ourIndex);
        reset();
    } else if (ourIndex == 0) {
        setLeadership(true);
    } else {
        String watchPath = sortedChildren.get(ourIndex - 1);
        Watcher watcher = new Watcher() {

            @Override
            public void process(WatchedEvent event) {
                if ((state.get() == State.STARTED) && (event.getType() == Event.EventType.NodeDeleted) && (localOurPath != null)) {
                    try {
                        getChildren();
                    } catch (Exception ex) {
                        ThreadUtils.checkInterrupted(ex);
                        log.error("An error occurred checking the leadership.", ex);
                    }
                }
            }
        };
        BackgroundCallback callback = new BackgroundCallback() {

            @Override
            public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                if (event.getResultCode() == KeeperException.Code.NONODE.intValue()) {
                    // previous node is gone - reset
                    reset();
                }
            }
        };
        // use getData() instead of exists() to avoid leaving unneeded watchers which is a type of resource leak
        client.getData().usingWatcher(watcher).inBackground(callback).forPath(ZKPaths.makePath(latchPath, watchPath));
    }
}
Also used : WatchedEvent(org.apache.zookeeper.WatchedEvent) CuratorFramework(org.apache.curator.framework.CuratorFramework) Watcher(org.apache.zookeeper.Watcher) BackgroundCallback(org.apache.curator.framework.api.BackgroundCallback) CuratorEvent(org.apache.curator.framework.api.CuratorEvent) KeeperException(org.apache.zookeeper.KeeperException) IOException(java.io.IOException) EOFException(java.io.EOFException)

Example 23 with CuratorEvent

use of org.apache.curator.framework.api.CuratorEvent in project xian by happyyangyuan.

the class PathChildrenCache method refresh.

void refresh(final RefreshMode mode) throws Exception {
    ensurePath();
    final BackgroundCallback callback = new BackgroundCallback() {

        @Override
        public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
            if (PathChildrenCache.this.state.get().equals(State.CLOSED)) {
                // This ship is closed, don't handle the callback
                return;
            }
            if (event.getResultCode() == KeeperException.Code.OK.intValue()) {
                processChildren(event.getChildren(), mode);
            }
        }
    };
    client.getChildren().usingWatcher(childrenWatcher).inBackground(callback).forPath(path);
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) BackgroundCallback(org.apache.curator.framework.api.BackgroundCallback) CuratorEvent(org.apache.curator.framework.api.CuratorEvent)

Example 24 with CuratorEvent

use of org.apache.curator.framework.api.CuratorEvent in project xian by happyyangyuan.

the class SyncBuilderImpl method performBackgroundOperation.

@Override
public void performBackgroundOperation(final OperationAndData<String> operationAndData) throws Exception {
    try {
        final OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("SyncBuilderImpl-Background");
        final String path = operationAndData.getData();
        String adjustedPath = client.fixForNamespace(path);
        AsyncCallback.VoidCallback voidCallback = new AsyncCallback.VoidCallback() {

            @Override
            public void processResult(int rc, String path, Object ctx) {
                trace.setReturnCode(rc).setPath(path).commit();
                CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.SYNC, rc, path, path, ctx, null, null, null, null, null);
                client.processBackgroundOperation(operationAndData, event);
            }
        };
        client.getZooKeeper().sync(adjustedPath, voidCallback, backgrounding.getContext());
    } catch (Throwable e) {
        backgrounding.checkError(e);
    }
}
Also used : AsyncCallback(org.apache.zookeeper.AsyncCallback) CuratorEvent(org.apache.curator.framework.api.CuratorEvent) OperationTrace(org.apache.curator.drivers.OperationTrace)

Example 25 with CuratorEvent

use of org.apache.curator.framework.api.CuratorEvent in project xian by happyyangyuan.

the class TestLeaderSelectorEdges method createProtectedNodeInBackgroundTestNoRetry.

/**
 * Same test as above but without a retry policy
 */
@Test
public void createProtectedNodeInBackgroundTestNoRetry() throws Exception {
    final CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryNTimes(0, 0)).connectionTimeoutMs(100).sessionTimeoutMs(60000).build();
    final CountDownLatch latch = new CountDownLatch(1);
    client.start();
    try {
        client.create().forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE);
        client.create().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).inBackground(new BackgroundCallback() {

            public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                log.info("Receive event {}", event.toString());
                if (event.getResultCode() == KeeperException.Code.CONNECTIONLOSS.intValue()) {
                    latch.countDown();
                }
            }
        }).forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE_PREFIX + "foo-");
        Assert.assertTrue(latch.await(30, TimeUnit.SECONDS), "Callback has not been called");
        // Wait for the znode to be deleted
        Thread.sleep(ChaosMonkeyCnxnFactory.LOCKOUT_DURATION_MS * 2);
        // Check that there is no znode
        final int children = client.getChildren().forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE).size();
        Assert.assertEquals(children, 0, "Still " + children + " znodes under " + ChaosMonkeyCnxnFactory.CHAOS_ZNODE + " lock");
    } finally {
        client.close();
    }
}
Also used : RetryNTimes(org.apache.curator.retry.RetryNTimes) CuratorFramework(org.apache.curator.framework.CuratorFramework) BackgroundCallback(org.apache.curator.framework.api.BackgroundCallback) CuratorEvent(org.apache.curator.framework.api.CuratorEvent) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.testng.annotations.Test)

Aggregations

CuratorEvent (org.apache.curator.framework.api.CuratorEvent)60 CuratorFramework (org.apache.curator.framework.CuratorFramework)57 BackgroundCallback (org.apache.curator.framework.api.BackgroundCallback)36 CountDownLatch (java.util.concurrent.CountDownLatch)34 CuratorListener (org.apache.curator.framework.api.CuratorListener)23 Test (org.testng.annotations.Test)21 RetryOneTime (org.apache.curator.retry.RetryOneTime)18 KeeperException (org.apache.zookeeper.KeeperException)14 Test (org.junit.Test)11 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)8 Watcher (org.apache.zookeeper.Watcher)8 ArrayList (java.util.ArrayList)4 Timing (org.apache.curator.test.Timing)4 WatchedEvent (org.apache.zookeeper.WatchedEvent)4 InvocationOnMock (org.mockito.invocation.InvocationOnMock)4 Message (com.google.protobuf.Message)3 IOException (java.io.IOException)3 Map (java.util.Map)3 ExecutionException (java.util.concurrent.ExecutionException)3 TimeUnit (java.util.concurrent.TimeUnit)3