org.apache.curator.framework.api.CuratorEventType Java Examples

The following examples show how to use org.apache.curator.framework.api.CuratorEventType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BackgroundSyncImpl.java    From xian with Apache License 2.0 6 votes vote down vote up
@Override
public void performBackgroundOperation(final OperationAndData<String> operationAndData) throws Exception
{
    final OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("BackgroundSyncImpl");
    final String data = operationAndData.getData();
    client.getZooKeeper().sync
    (
        data,
        new AsyncCallback.VoidCallback()
        {
            @Override
            public void processResult(int rc, String path, Object ctx)
            {
                trace.setReturnCode(rc).setRequestBytesLength(data).commit();
                CuratorEventImpl event = new CuratorEventImpl(client, CuratorEventType.SYNC, rc, path, null, ctx, null, null, null, null, null);
                client.processBackgroundOperation(operationAndData, event);
            }
        },
        context
    );
}
 
Example #2
Source File: GetACLBuilderImpl.java    From curator with Apache License 2.0 6 votes vote down vote up
@Override
public void performBackgroundOperation(final OperationAndData<String> operationAndData) throws Exception
{
    try
    {
        final OperationTrace             trace = client.getZookeeperClient().startAdvancedTracer("GetACLBuilderImpl-Background");
        AsyncCallback.ACLCallback   callback = new AsyncCallback.ACLCallback()
        {
            @Override
            public void processResult(int rc, String path, Object ctx, List<ACL> acl, Stat stat)
            {
                trace.setReturnCode(rc).setPath(path).setStat(stat).commit();
                CuratorEventImpl event = new CuratorEventImpl(client, CuratorEventType.GET_ACL, rc, path, null, ctx, stat, null, null, null, acl, null);
                client.processBackgroundOperation(operationAndData, event);
            }
        };
        client.getZooKeeper().getACL(operationAndData.getData(), responseStat, callback, backgrounding.getContext());
    }
    catch ( Throwable e )
    {
        backgrounding.checkError(e, null);
    }
}
 
Example #3
Source File: GetACLBuilderImpl.java    From xian with Apache License 2.0 6 votes vote down vote up
@Override
public void performBackgroundOperation(final OperationAndData<String> operationAndData) throws Exception
{
    try
    {
        final OperationTrace             trace = client.getZookeeperClient().startAdvancedTracer("GetACLBuilderImpl-Background");
        AsyncCallback.ACLCallback   callback = new AsyncCallback.ACLCallback()
        {
            @Override
            public void processResult(int rc, String path, Object ctx, List<ACL> acl, Stat stat)
            {
                trace.setReturnCode(rc).setPath(path).setStat(stat).commit();
                CuratorEventImpl event = new CuratorEventImpl(client, CuratorEventType.GET_ACL, rc, path, null, ctx, stat, null, null, null, acl);
                client.processBackgroundOperation(operationAndData, event);
            }
        };
        client.getZooKeeper().getACL(operationAndData.getData(), responseStat, callback, backgrounding.getContext());
    }
    catch ( Throwable e )
    {
        backgrounding.checkError(e);
    }
}
 
Example #4
Source File: CuratorMultiTransactionImpl.java    From curator with Apache License 2.0 6 votes vote down vote up
@Override
public void performBackgroundOperation(final OperationAndData<CuratorMultiTransactionRecord> operationAndData) throws Exception
{
    try
    {
        final TimeTrace trace = client.getZookeeperClient().startTracer("CuratorMultiTransactionImpl-Background");
        AsyncCallback.MultiCallback callback = new AsyncCallback.MultiCallback()
        {
            @Override
            public void processResult(int rc, String path, Object ctx, List<OpResult> opResults)
            {
                trace.commit();
                List<CuratorTransactionResult> curatorResults = (opResults != null) ? CuratorTransactionImpl.wrapResults(client, opResults, operationAndData.getData()) : null;
                CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.TRANSACTION, rc, path, null, ctx, null, null, null, null, null, curatorResults);
                client.processBackgroundOperation(operationAndData, event);
            }
        };
        client.getZooKeeper().multi(operationAndData.getData(), callback, backgrounding.getContext());
    }
    catch ( Throwable e )
    {
        backgrounding.checkError(e, null);
    }
}
 
Example #5
Source File: BackgroundSyncImpl.java    From curator with Apache License 2.0 6 votes vote down vote up
@Override
public void performBackgroundOperation(final OperationAndData<String> operationAndData) throws Exception
{
    final OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("BackgroundSyncImpl");
    final String data = operationAndData.getData();
    client.getZooKeeper().sync
    (
        data,
        new AsyncCallback.VoidCallback()
        {
            @Override
            public void processResult(int rc, String path, Object ctx)
            {
                trace.setReturnCode(rc).setRequestBytesLength(data).commit();
                CuratorEventImpl event = new CuratorEventImpl(client, CuratorEventType.SYNC, rc, path, null, ctx, null, null, null, null, null, null);
                client.processBackgroundOperation(operationAndData, event);
            }
        },
        context
    );
}
 
Example #6
Source File: Zookeeper.java    From jstorm with Apache License 2.0 5 votes vote down vote up
/**
 * connect ZK, register watchers
 */
public CuratorFramework mkClient(Map conf, List<String> servers, Object port,
                                 String root, final WatcherCallBack watcher) {

    CuratorFramework fk = Utils.newCurator(conf, servers, port, root);

    fk.getCuratorListenable().addListener(new CuratorListener() {
        @Override
        public void eventReceived(CuratorFramework _fk, CuratorEvent e) throws Exception {
            if (e.getType().equals(CuratorEventType.WATCHED)) {
                WatchedEvent event = e.getWatchedEvent();

                watcher.execute(event.getState(), event.getType(), event.getPath());
            }

        }
    });

    fk.getUnhandledErrorListenable().addListener(new UnhandledErrorListener() {
        @Override
        public void unhandledError(String msg, Throwable error) {
            String errmsg = "Unrecoverable zookeeper error, halting process: " + msg;
            LOG.error(errmsg, error);
            JStormUtils.halt_process(1, "Unrecoverable zookeeper error");

        }
    });
    fk.start();
    return fk;
}
 
Example #7
Source File: DistributedQueue.java    From curator with Apache License 2.0 5 votes vote down vote up
private void doPutInBackground(final T item, String path, final MultiItem<T> givenMultiItem, byte[] bytes) throws Exception
{
    BackgroundCallback callback = new BackgroundCallback()
    {
        @Override
        public void processResult(CuratorFramework client, CuratorEvent event) throws Exception
        {
            if ( event.getResultCode() != KeeperException.Code.OK.intValue() )
            {
                return;
            }

            if ( event.getType() == CuratorEventType.CREATE )
            {
                synchronized(putCount)
                {
                    putCount.decrementAndGet();
                    putCount.notifyAll();
                }
            }

            putListenerContainer.forEach(listener -> {
                if ( item != null )
                {
                    listener.putCompleted(item);
                }
                else
                {
                    listener.putMultiCompleted(givenMultiItem);
                }
            });
        }
    };
    internalCreateNode(path, bytes, callback);
}
 
Example #8
Source File: TestFramework.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testBackgroundDeleteWithChildren() throws Exception
{
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();
    try
    {
        client.getCuratorListenable().addListener
            ((client1, event) ->
            {
                if ( event.getType() == CuratorEventType.DELETE )
                {
                    Assert.assertEquals(event.getPath(), "/one/two");
                    ((CountDownLatch)event.getContext()).countDown();
                }
            });

        CountDownLatch latch = new CountDownLatch(1);
        AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
        async.create().withOptions(EnumSet.of(CreateOption.createParentsIfNeeded)).forPath("/one/two/three/four").thenRun(() ->
            async.delete().withOptions(EnumSet.of(DeleteOption.deletingChildrenIfNeeded)).forPath("/one/two").handle((v, e) -> {
                Assert.assertNull(v);
                Assert.assertNull(e);
                latch.countDown();
                return null;
            })
        );
        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
        Assert.assertNull(client.checkExists().forPath("/one/two"));
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #9
Source File: GetChildrenBuilderImpl.java    From curator with Apache License 2.0 5 votes vote down vote up
@Override
public void performBackgroundOperation(final OperationAndData<String> operationAndData) throws Exception
{
    try
    {
        final OperationTrace       trace = client.getZookeeperClient().startAdvancedTracer("GetChildrenBuilderImpl-Background");
        AsyncCallback.Children2Callback callback = new AsyncCallback.Children2Callback()
        {
            @Override
            public void processResult(int rc, String path, Object o, List<String> strings, Stat stat)
            {
                watching.commitWatcher(rc, false);
                trace.setReturnCode(rc).setPath(path).setWithWatcher(watching.hasWatcher()).setStat(stat).commit();
                if ( strings == null )
                {
                    strings = Lists.newArrayList();
                }
                CuratorEventImpl event = new CuratorEventImpl(client, CuratorEventType.CHILDREN, rc, path, null, o, stat, null, strings, null, null, null);
                client.processBackgroundOperation(operationAndData, event);
            }
        };
        if ( watching.isWatched() )
        {
            client.getZooKeeper().getChildren(operationAndData.getData(), true, callback, backgrounding.getContext());
        }
        else
        {
            client.getZooKeeper().getChildren(operationAndData.getData(), watching.getWatcher(operationAndData.getData()), callback, backgrounding.getContext());
        }
    }
    catch ( Throwable e )
    {
        backgrounding.checkError(e, watching);
    }
}
 
Example #10
Source File: CuratorEventImpl.java    From curator with Apache License 2.0 5 votes vote down vote up
CuratorEventImpl(CuratorFrameworkImpl client, CuratorEventType type, int resultCode, String path, String name, Object context, Stat stat, byte[] data, List<String> children, WatchedEvent watchedEvent, List<ACL> aclList, List<CuratorTransactionResult> opResults)
{
    this.type = type;
    this.resultCode = resultCode;
    this.opResults = (opResults != null) ? ImmutableList.copyOf(opResults) : null;
    this.path = client.unfixForNamespace(path);
    this.name = name;
    this.context = context;
    this.stat = stat;
    this.data = data;
    this.children = children;
    this.watchedEvent = (watchedEvent != null) ? new NamespaceWatchedEvent(client, watchedEvent) : null;
    this.aclList = (aclList != null) ? ImmutableList.copyOf(aclList) : null;
}
 
Example #11
Source File: GetChildrenBuilderImpl.java    From xian with Apache License 2.0 5 votes vote down vote up
@Override
public void performBackgroundOperation(final OperationAndData<String> operationAndData) throws Exception
{
    try
    {
        final OperationTrace       trace = client.getZookeeperClient().startAdvancedTracer("GetChildrenBuilderImpl-Background");
        AsyncCallback.Children2Callback callback = new AsyncCallback.Children2Callback()
        {
            @Override
            public void processResult(int rc, String path, Object o, List<String> strings, Stat stat)
            {
                trace.setReturnCode(rc).setPath(path).setWithWatcher(watching.getWatcher() != null).setStat(stat).commit();
                if ( strings == null )
                {
                    strings = Lists.newArrayList();
                }
                CuratorEventImpl event = new CuratorEventImpl(client, CuratorEventType.CHILDREN, rc, path, null, o, stat, null, strings, null, null);
                client.processBackgroundOperation(operationAndData, event);
            }
        };
        if ( watching.isWatched() )
        {
            client.getZooKeeper().getChildren(operationAndData.getData(), true, callback, backgrounding.getContext());
        }
        else
        {
            client.getZooKeeper().getChildren(operationAndData.getData(), watching.getWatcher(), callback, backgrounding.getContext());
        }
    }
    catch ( Throwable e )
    {
        backgrounding.checkError(e);
    }
}
 
Example #12
Source File: CuratorEventImpl.java    From xian with Apache License 2.0 5 votes vote down vote up
CuratorEventImpl(CuratorFrameworkImpl client, CuratorEventType type, int resultCode, String path, String name, Object context, Stat stat, byte[] data, List<String> children, WatchedEvent watchedEvent, List<ACL> aclList)
{
    this.type = type;
    this.resultCode = resultCode;
    this.path = client.unfixForNamespace(path);
    this.name = name;
    this.context = context;
    this.stat = stat;
    this.data = data;
    this.children = children;
    this.watchedEvent = (watchedEvent != null) ? new NamespaceWatchedEvent(client, watchedEvent) : watchedEvent;
    this.aclList = (aclList != null) ? ImmutableList.copyOf(aclList) : null;
}
 
Example #13
Source File: CuratorEventImpl.java    From curator with Apache License 2.0 4 votes vote down vote up
@Override
public CuratorEventType getType()
{
    return type;
}
 
Example #14
Source File: FindAndDeleteProtectedNodeInBackground.java    From curator with Apache License 2.0 4 votes vote down vote up
@Override
public void performBackgroundOperation(final OperationAndData<Void> operationAndData) throws Exception
{
    final OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("FindAndDeleteProtectedNodeInBackground");
    AsyncCallback.Children2Callback callback = new AsyncCallback.Children2Callback()
    {
        @Override
        public void processResult(int rc, String path, Object o, List<String> strings, Stat stat)
        {
            trace.setReturnCode(rc).setPath(path).setStat(stat).commit();

            if ( debugInsertError.compareAndSet(true, false) )
            {
                rc = KeeperException.Code.CONNECTIONLOSS.intValue();
            }

            if ( rc == KeeperException.Code.OK.intValue() )
            {
                final String node = CreateBuilderImpl.findNode(strings, "/", protectedId);  // due to namespacing, don't let CreateBuilderImpl.findNode adjust the path
                if ( node != null )
                {
                    try
                    {
                        String deletePath = client.unfixForNamespace(ZKPaths.makePath(namespaceAdjustedParentPath, node));
                        client.delete().guaranteed().inBackground().forPath(deletePath);
                    }
                    catch ( Exception e )
                    {
                        ThreadUtils.checkInterrupted(e);
                        log.error("Could not start guaranteed delete for node: " + node);
                        rc = KeeperException.Code.CONNECTIONLOSS.intValue();
                    }
                }
            }

            if ( rc != KeeperException.Code.OK.intValue() )
            {
                CuratorEventImpl event = new CuratorEventImpl(client, CuratorEventType.CHILDREN, rc, path, null, o, stat, null, strings, null, null, null);
                client.processBackgroundOperation(operationAndData, event);
            }
        }
    };
    client.getZooKeeper().getChildren(namespaceAdjustedParentPath, false, callback, null);
}
 
Example #15
Source File: TestFrameworkEdges.java    From curator with Apache License 2.0 4 votes vote down vote up
@Test
public void testProtectionWithKilledSession() throws Exception
{
    server.stop();  // not needed

    // see CURATOR-498
    // attempt to re-create the state described in the bug report: create a 3 Instance ensemble;
    // have Curator connect to only 1 one of those instances; set failNextCreateForTesting to
    // simulate protection mode searching; kill the connected server when this happens;
    // wait for session timeout to elapse and then restart the instance. In most cases
    // this will cause the scenario as Curator will send the session cancel and do protection mode
    // search around the same time. The protection mode search should return first as it can be resolved
    // by the Instance Curator is connected to but the session kill needs a quorum vote (it's a
    // transaction)

    try (TestingCluster cluster = createAndStartCluster(3))
    {
        InstanceSpec instanceSpec0 = cluster.getServers().get(0).getInstanceSpec();

        CountDownLatch serverStoppedLatch = new CountDownLatch(1);
        RetryPolicy retryPolicy = new RetryForever(100)
        {
            @Override
            public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper)
            {
                if ( serverStoppedLatch.getCount() > 0 )
                {
                    try
                    {
                        cluster.killServer(instanceSpec0);
                    }
                    catch ( Exception e )
                    {
                        // ignore
                    }
                    serverStoppedLatch.countDown();
                }
                return super.allowRetry(retryCount, elapsedTimeMs, sleeper);
            }
        };

        try (CuratorFramework client = CuratorFrameworkFactory.newClient(instanceSpec0.getConnectString(), timing.session(), timing.connection(), retryPolicy))
        {
            BlockingQueue<String> createdNode = new LinkedBlockingQueue<>();
            BackgroundCallback callback = (__, event) -> {
                if ( event.getType() == CuratorEventType.CREATE )
                {
                    createdNode.offer(event.getPath());
                }
            };

            client.start();
            client.create().forPath("/test");

            ErrorListenerPathAndBytesable<String> builder = client.create().withProtection().withMode(CreateMode.EPHEMERAL).inBackground(callback);
            ((CreateBuilderImpl)builder).failNextCreateForTesting = true;

            builder.forPath("/test/hey");

            Assert.assertTrue(timing.awaitLatch(serverStoppedLatch));
            timing.forSessionSleep().sleep();   // wait for session to expire
            cluster.restartServer(instanceSpec0);

            String path = timing.takeFromQueue(createdNode);
            List<String> children = client.getChildren().forPath("/test");
            Assert.assertEquals(Collections.singletonList(ZKPaths.getNodeFromPath(path)), children);
        }
    }
}
 
Example #16
Source File: CuratorEventImpl.java    From xian with Apache License 2.0 4 votes vote down vote up
@Override
public CuratorEventType getType()
{
    return type;
}
 
Example #17
Source File: FindAndDeleteProtectedNodeInBackground.java    From xian with Apache License 2.0 4 votes vote down vote up
@Override
public void performBackgroundOperation(final OperationAndData<Void> operationAndData) throws Exception
{
    final OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("FindAndDeleteProtectedNodeInBackground");
    AsyncCallback.Children2Callback callback = new AsyncCallback.Children2Callback()
    {
        @Override
        public void processResult(int rc, String path, Object o, List<String> strings, Stat stat)
        {
            trace.setReturnCode(rc).setPath(path).setStat(stat).commit();

            if ( debugInsertError.compareAndSet(true, false) )
            {
                rc = KeeperException.Code.CONNECTIONLOSS.intValue();
            }

            if ( rc == KeeperException.Code.OK.intValue() )
            {
                final String node = CreateBuilderImpl.findNode(strings, "/", protectedId);  // due to namespacing, don't let CreateBuilderImpl.findNode adjust the path
                if ( node != null )
                {
                    try
                    {
                        String deletePath = client.unfixForNamespace(ZKPaths.makePath(namespaceAdjustedParentPath, node));
                        client.delete().guaranteed().inBackground().forPath(deletePath);
                    }
                    catch ( Exception e )
                    {
                        ThreadUtils.checkInterrupted(e);
                        log.error("Could not start guaranteed delete for node: " + node);
                        rc = KeeperException.Code.CONNECTIONLOSS.intValue();
                    }
                }
            }

            if ( rc != KeeperException.Code.OK.intValue() )
            {
                CuratorEventImpl event = new CuratorEventImpl(client, CuratorEventType.CHILDREN, rc, path, null, o, stat, null, strings, null, null);
                client.processBackgroundOperation(operationAndData, event);
            }
        }
    };
    client.getZooKeeper().getChildren(namespaceAdjustedParentPath, false, callback, null);
}
 
Example #18
Source File: DistributedQueue.java    From xian with Apache License 2.0 4 votes vote down vote up
private void doPutInBackground(final T item, String path, final MultiItem<T> givenMultiItem, byte[] bytes) throws Exception
{
    BackgroundCallback callback = new BackgroundCallback()
    {
        @Override
        public void processResult(CuratorFramework client, CuratorEvent event) throws Exception
        {
            if ( event.getResultCode() != KeeperException.Code.OK.intValue() )
            {
                return;
            }

            if ( event.getType() == CuratorEventType.CREATE )
            {
                synchronized(putCount)
                {
                    putCount.decrementAndGet();
                    putCount.notifyAll();
                }
            }

            putListenerContainer.forEach
            (
                new Function<QueuePutListener<T>, Void>()
                {
                    @Override
                    public Void apply(QueuePutListener<T> listener)
                    {
                        if ( item != null )
                        {
                            listener.putCompleted(item);
                        }
                        else
                        {
                            listener.putMultiCompleted(givenMultiItem);
                        }
                        return null;
                    }
                }
            );
        }
    };
    internalCreateNode(path, bytes, callback);
}