Search in sources :

Example 76 with ZooKeeper

use of org.apache.zookeeper.ZooKeeper in project bookkeeper by apache.

the class ZooKeeperClient method multi.

@Override
public void multi(final Iterable<Op> ops, final MultiCallback cb, final Object context) {
    final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, createStats) {

        final MultiCallback multiCb = new MultiCallback() {

            @Override
            public void processResult(int rc, String path, Object ctx, List<OpResult> results) {
                ZooWorker worker = (ZooWorker) ctx;
                if (allowRetry(worker, rc)) {
                    backOffAndRetry(that, worker.nextRetryWaitTime());
                } else {
                    cb.processResult(rc, path, context, results);
                }
            }
        };

        @Override
        void zkRun() {
            ZooKeeper zkHandle = zk.get();
            if (null == zkHandle) {
                ZooKeeperClient.super.multi(ops, multiCb, worker);
            } else {
                zkHandle.multi(ops, multiCb, worker);
            }
        }

        @Override
        public String toString() {
            return "multi";
        }
    };
    // execute it immediately
    proc.run();
}
Also used : ZooKeeper(org.apache.zookeeper.ZooKeeper) OpResult(org.apache.zookeeper.OpResult) MultiCallback(org.apache.zookeeper.AsyncCallback.MultiCallback)

Example 77 with ZooKeeper

use of org.apache.zookeeper.ZooKeeper in project tutorials by eugenp.

the class ZKConnection method connect.

public ZooKeeper connect(String host) throws IOException, InterruptedException {
    zoo = new ZooKeeper(host, 2000, new Watcher() {

        public void process(WatchedEvent we) {
            if (we.getState() == KeeperState.SyncConnected) {
                connectionLatch.countDown();
            }
        }
    });
    connectionLatch.await();
    return zoo;
}
Also used : WatchedEvent(org.apache.zookeeper.WatchedEvent) ZooKeeper(org.apache.zookeeper.ZooKeeper) Watcher(org.apache.zookeeper.Watcher)

Example 78 with ZooKeeper

use of org.apache.zookeeper.ZooKeeper in project incubator-pulsar by apache.

the class ManagedLedgerTest method testEmptyManagedLedgerContent.

@Test(timeOut = 20000)
public void testEmptyManagedLedgerContent() throws Exception {
    ZooKeeper zk = bkc.getZkHandle();
    zk.create("/managed-ledger", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    zk.create("/managed-ledger/my_test_ledger", " ".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    ManagedLedger ledger = factory.open("my_test_ledger");
    ledger.openCursor("test");
    ledger.addEntry("entry-1".getBytes(Encoding));
    assertEquals(ledger.getNumberOfEntries(), 1);
}
Also used : ZooKeeper(org.apache.zookeeper.ZooKeeper) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) Test(org.testng.annotations.Test)

Example 79 with ZooKeeper

use of org.apache.zookeeper.ZooKeeper in project incubator-pulsar by apache.

the class LocalZooKeeperCacheService method createPolicies.

/**
 * Create LocalPolicies with bundle-data in LocalZookeeper by fetching it from GlobalZookeeper
 *
 * @param path
 *            znode path
 * @param readFromGlobal
 *            if true copy policies from global zk to local zk else create a new znode with empty {@link Policies}
 * @throws Exception
 */
@SuppressWarnings("deprecation")
public CompletableFuture<Optional<LocalPolicies>> createPolicies(String path, boolean readFromGlobal) {
    CompletableFuture<Optional<LocalPolicies>> future = new CompletableFuture<>();
    if (path == null || !path.startsWith(LOCAL_POLICIES_ROOT)) {
        future.completeExceptionally(new IllegalArgumentException("Invalid path of local policies " + path));
        return future;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating local namespace policies for {} - readFromGlobal: {}", path, readFromGlobal);
    }
    CompletableFuture<Optional<LocalPolicies>> readFromGlobalFuture = new CompletableFuture<>();
    if (readFromGlobal) {
        String globalPath = joinPath(POLICIES_ROOT, path.substring(path.indexOf(LOCAL_POLICIES_ROOT) + LOCAL_POLICIES_ROOT.length() + 1));
        checkNotNull(configurationCacheService);
        checkNotNull(configurationCacheService.policiesCache());
        checkNotNull(configurationCacheService.policiesCache().getAsync(globalPath));
        configurationCacheService.policiesCache().getAsync(globalPath).thenAccept(policies -> {
            if (policies.isPresent()) {
                // Copying global bundles information to local policies
                LocalPolicies localPolicies = new LocalPolicies();
                localPolicies.bundles = policies.get().bundles;
                readFromGlobalFuture.complete(Optional.of(localPolicies));
            } else {
                // Policies are not present in global zk
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Global policies not found at {}", globalPath);
                }
                readFromGlobalFuture.complete(Optional.empty());
            }
        }).exceptionally(ex -> {
            future.completeExceptionally(ex);
            return null;
        });
    } else {
        // Use default local policies
        readFromGlobalFuture.complete(Optional.of(new LocalPolicies()));
    }
    readFromGlobalFuture.thenAccept(localPolicies -> {
        if (!localPolicies.isPresent()) {
            future.complete(Optional.empty());
        }
        // When we have the updated localPolicies, we can write them back in local ZK
        byte[] content;
        try {
            content = ObjectMapperFactory.getThreadLocal().writeValueAsBytes(localPolicies.get());
        } catch (Throwable t) {
            // Failed to serialize to json
            future.completeExceptionally(t);
            return;
        }
        ZkUtils.asyncCreateFullPathOptimistic(cache.getZooKeeper(), path, content, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, (rc, path1, ctx, name) -> {
            if (rc == KeeperException.Code.OK.intValue() || rc == KeeperException.Code.NODEEXISTS.intValue()) {
                LOG.info("Successfully copyied bundles data to local zk at {}", path);
                future.complete(localPolicies);
            } else {
                LOG.error("Failed to create policies for {} in local zookeeper: {}", path, KeeperException.Code.get(rc));
                future.completeExceptionally(new PulsarServerException(KeeperException.create(rc)));
            }
        }, null);
    }).exceptionally(ex -> {
        future.completeExceptionally(ex);
        return null;
    });
    return future;
}
Also used : CreateMode(org.apache.zookeeper.CreateMode) ZooKeeper(org.apache.zookeeper.ZooKeeper) Logger(org.slf4j.Logger) KeeperException(org.apache.zookeeper.KeeperException) Ids(org.apache.zookeeper.ZooDefs.Ids) ObjectMapperFactory(org.apache.pulsar.common.util.ObjectMapperFactory) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) LoggerFactory(org.slf4j.LoggerFactory) NamespaceEphemeralData(org.apache.pulsar.broker.namespace.NamespaceEphemeralData) LocalPolicies(org.apache.pulsar.common.policies.data.LocalPolicies) ZooKeeperChildrenCache(org.apache.pulsar.zookeeper.ZooKeeperChildrenCache) CompletableFuture(java.util.concurrent.CompletableFuture) Stat(org.apache.zookeeper.data.Stat) PulsarWebResource.joinPath(org.apache.pulsar.broker.web.PulsarWebResource.joinPath) Maps(com.google.common.collect.Maps) ZkUtils(org.apache.bookkeeper.util.ZkUtils) Policies(org.apache.pulsar.common.policies.data.Policies) PulsarServerException(org.apache.pulsar.broker.PulsarServerException) ZooKeeperCache(org.apache.pulsar.zookeeper.ZooKeeperCache) ZooKeeperDataCache(org.apache.pulsar.zookeeper.ZooKeeperDataCache) Entry(java.util.Map.Entry) Optional(java.util.Optional) POLICIES_ROOT(org.apache.pulsar.broker.cache.ConfigurationCacheService.POLICIES_ROOT) PulsarServerException(org.apache.pulsar.broker.PulsarServerException) CompletableFuture(java.util.concurrent.CompletableFuture) Optional(java.util.Optional) LocalPolicies(org.apache.pulsar.common.policies.data.LocalPolicies)

Example 80 with ZooKeeper

use of org.apache.zookeeper.ZooKeeper in project incubator-pulsar by apache.

the class ResourceQuotaCache method saveQuotaToZnode.

private void saveQuotaToZnode(String zpath, ResourceQuota quota) throws Exception {
    ZooKeeper zk = this.localZkCache.getZooKeeper();
    if (zk.exists(zpath, false) == null) {
        try {
            ZkUtils.createFullPathOptimistic(zk, zpath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        } catch (KeeperException.NodeExistsException e) {
        }
    }
    zk.setData(zpath, this.jsonMapper.writeValueAsBytes(quota), -1);
}
Also used : ZooKeeper(org.apache.zookeeper.ZooKeeper) KeeperException(org.apache.zookeeper.KeeperException)

Aggregations

ZooKeeper (org.apache.zookeeper.ZooKeeper)605 Test (org.junit.jupiter.api.Test)190 KeeperException (org.apache.zookeeper.KeeperException)153 Test (org.junit.Test)100 Stat (org.apache.zookeeper.data.Stat)86 IOException (java.io.IOException)83 CountDownLatch (java.util.concurrent.CountDownLatch)80 WatchedEvent (org.apache.zookeeper.WatchedEvent)70 Watcher (org.apache.zookeeper.Watcher)59 ArrayList (java.util.ArrayList)47 CountdownWatcher (org.apache.zookeeper.test.ClientBase.CountdownWatcher)41 TestableZooKeeper (org.apache.zookeeper.TestableZooKeeper)38 Timeout (org.junit.jupiter.api.Timeout)32 ZooKeeperServer (org.apache.zookeeper.server.ZooKeeperServer)31 File (java.io.File)28 HashMap (java.util.HashMap)26 CompletableFuture (java.util.concurrent.CompletableFuture)22 Test (org.testng.annotations.Test)21 AsyncCallback (org.apache.zookeeper.AsyncCallback)19 ACL (org.apache.zookeeper.data.ACL)19