org.apache.curator.framework.CuratorFramework Java Examples

The following examples show how to use org.apache.curator.framework.CuratorFramework. 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: ParserFunctions.java    From metron with Apache License 2.0 6 votes vote down vote up
private SensorParserConfig readFromZookeeper(Context context, String sensorType) throws ParseException {
  SensorParserConfig config;
  try {
    CuratorFramework zkClient = getZookeeperClient(context);
    config = readSensorParserConfigFromZookeeper(sensorType, zkClient);

  } catch(Exception e) {
    throw new ParseException(ExceptionUtils.getRootCauseMessage(e), e);
  }

  if(config == null) {
    throw new ParseException("Unable to read configuration from Zookeeper; sensorType = " + sensorType);
  }

  return config;
}
 
Example #2
Source File: AsyncExamples.java    From curator with Apache License 2.0 6 votes vote down vote up
public static void create(CuratorFramework client, String path, byte[] payload)
{
    AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);   // normally you'd wrap early in your app and reuse the instance

    // create a node at the given path with the given payload asynchronously
    async.create().forPath(path, payload).whenComplete((name, exception) -> {
        if ( exception != null )
        {
            // there was a problem
            exception.printStackTrace();
        }
        else
        {
            System.out.println("Created node name is: " + name);
        }
    });
}
 
Example #3
Source File: TestCompressionInTransactionOld.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetData() throws Exception
{
    final String path = "/a";
    final byte[]            data = "here's a string".getBytes();

    CuratorFramework        client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try
    {
        client.start();

        //Create uncompressed data in a transaction
        client.inTransaction().create().forPath(path, data).and().commit();
        Assert.assertEquals(data, client.getData().forPath(path));

        //Create compressed data in transaction
        client.inTransaction().setData().compressed().forPath(path, data).and().commit();
        Assert.assertEquals(data, client.getData().decompressed().forPath(path));
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #4
Source File: TestFrameworkEdges.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testMissedResponseOnESCreate() throws Exception
{
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    client.start();
    try
    {
        CreateBuilderImpl createBuilder = (CreateBuilderImpl)client.create();
        createBuilder.failNextCreateForTesting = true;
        String ourPath = createBuilder.withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/");
        Assert.assertTrue(ourPath.startsWith(ZKPaths.makePath("/", ProtectedUtils.PROTECTED_PREFIX)));
        Assert.assertFalse(createBuilder.failNextCreateForTesting);
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #5
Source File: DataStoreCache.java    From timely with Apache License 2.0 6 votes vote down vote up
private void testIPRWLock(CuratorFramework curatorFramework, InterProcessReadWriteLock lock, String path) {
    try {
        lock.writeLock().acquire(10, TimeUnit.SECONDS);
    } catch (Exception e1) {
        try {
            curatorFramework.delete().deletingChildrenIfNeeded().forPath(path);
            curatorFramework.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT)
                    .forPath(path);
        } catch (Exception e2) {
            LOG.info(e2.getMessage(), e2);
        }
    } finally {
        try {
            lock.writeLock().release();
        } catch (Exception e3) {
            LOG.error(e3.getMessage());
        }
    }
}
 
Example #6
Source File: PersistentEphemeralNode.java    From curator-extensions with Apache License 2.0 6 votes vote down vote up
/**
 * Create the ephemeral node in ZooKeeper.  If the node cannot be created in a timely fashion then an exception will
 * be thrown.
 *
 * @param curator Client to manage ZooKeeper nodes with.
 * @param basePath Path to parent node this node should be created in.
 * @param data Data to store in the node.
 * @param mode Node creation mode.
 */
public PersistentEphemeralNode(CuratorFramework curator, String basePath, byte[] data, CreateMode mode) {
    Objects.requireNonNull(curator);
    checkArgument(curator.getState() == CuratorFrameworkState.STARTED);
    Objects.requireNonNull(basePath);
    Objects.requireNonNull(data);
    Objects.requireNonNull(mode);
    checkArgument(mode == CreateMode.EPHEMERAL || mode == CreateMode.EPHEMERAL_SEQUENTIAL);

    // TODO: Share this executor across multiple persistent ephemeral nodes in a way that guarantees that it is a
    // TODO: single thread executor.
    _executor = Executors.newSingleThreadScheduledExecutor(THREAD_FACTORY);
    _async = new Async(_executor, new Sync(curator, basePath, data, mode));

    CountDownLatch latch = new CountDownLatch(1);
    _async.createNode(latch);
    await(latch, CREATION_WAIT_IN_SECONDS, TimeUnit.SECONDS);
}
 
Example #7
Source File: CreateKeyspacesCommand.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Override
protected void run(Bootstrap<EmoConfiguration> bootstrap, Namespace namespace, EmoConfiguration emoConfiguration)
        throws Exception {
    _outputOnly = namespace.getBoolean("output_only");

    DdlConfiguration ddlConfiguration = parseDdlConfiguration(toFile(namespace.getString("config-ddl")));
    CuratorFramework curator = null;
    if (!_outputOnly) {
        curator = emoConfiguration.getZooKeeperConfiguration().newCurator();
        curator.start();
    }
    try {
        createKeyspacesIfNecessary(emoConfiguration, ddlConfiguration, curator, bootstrap.getMetricRegistry());

    } finally {
        Closeables.close(curator, true);
    }
}
 
Example #8
Source File: ZookeeperRegistryCenterModifyTest.java    From shardingsphere-elasticjob-lite with Apache License 2.0 6 votes vote down vote up
@Test
public void assertPersistSequential() throws Exception {
    assertThat(zkRegCenter.persistSequential("/sequential/test_sequential", "test_value"), startsWith("/sequential/test_sequential"));
    assertThat(zkRegCenter.persistSequential("/sequential/test_sequential", "test_value"), startsWith("/sequential/test_sequential"));
    CuratorFramework client = CuratorFrameworkFactory.newClient(EmbedTestingServer.getConnectionString(), new RetryOneTime(2000));
    client.start();
    client.blockUntilConnected();
    List<String> actual = client.getChildren().forPath("/" + ZookeeperRegistryCenterModifyTest.class.getName() + "/sequential");
    assertThat(actual.size(), is(2));
    for (String each : actual) {
        assertThat(each, startsWith("test_sequential"));
        assertThat(zkRegCenter.get("/sequential/" + each), startsWith("test_value"));
    }
    zkRegCenter.remove("/sequential");
    assertFalse(zkRegCenter.isExisted("/sequential"));
}
 
Example #9
Source File: BookKeeperLog.java    From pravega with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new instance of the BookKeeper log class.
 *
 * @param containerId     The Id of the Container whose BookKeeperLog to open.
 * @param zkClient        A reference to the CuratorFramework client to use.
 * @param bookKeeper      A reference to the BookKeeper client to use.
 * @param config          Configuration to use.
 * @param executorService An Executor to use for async operations.
 */
BookKeeperLog(int containerId, CuratorFramework zkClient, BookKeeper bookKeeper, BookKeeperConfig config, ScheduledExecutorService executorService) {
    Preconditions.checkArgument(containerId >= 0, "containerId must be a non-negative integer.");
    this.logId = containerId;
    this.zkClient = Preconditions.checkNotNull(zkClient, "zkClient");
    this.bookKeeper = Preconditions.checkNotNull(bookKeeper, "bookKeeper");
    this.config = Preconditions.checkNotNull(config, "config");
    this.executorService = Preconditions.checkNotNull(executorService, "executorService");
    this.closed = new AtomicBoolean();
    this.logNodePath = HierarchyUtils.getPath(containerId, this.config.getZkHierarchyDepth());
    this.traceObjectId = String.format("Log[%d]", containerId);
    this.writes = new WriteQueue();
    val retry = createRetryPolicy(this.config.getMaxWriteAttempts(), this.config.getBkWriteTimeoutMillis());
    this.writeProcessor = new SequentialAsyncProcessor(this::processWritesSync, retry, this::handleWriteProcessorFailures, this.executorService);
    this.rolloverProcessor = new SequentialAsyncProcessor(this::rollover, retry, this::handleRolloverFailure, this.executorService);
    this.metrics = new BookKeeperMetrics.BookKeeperLog(containerId);
    this.metricReporter = this.executorService.scheduleWithFixedDelay(this::reportMetrics, REPORT_INTERVAL, REPORT_INTERVAL, TimeUnit.MILLISECONDS);
    this.queueStateChangeListeners = new HashSet<>();
}
 
Example #10
Source File: TestBlockUntilConnected.java    From curator with Apache License 2.0 6 votes vote down vote up
/**
 * Test the case where we are not currently connected and never have been
 */
@Test
public void testBlockUntilConnectedCurrentlyNeverConnected()
{
    CuratorFramework client = CuratorFrameworkFactory.builder().
        connectString(server.getConnectString()).
        retryPolicy(new RetryOneTime(1)).
        build();

    try
    {
        client.start();
        Assert.assertTrue(client.blockUntilConnected(5, TimeUnit.SECONDS), "Not connected");
    }
    catch ( InterruptedException e )
    {
        Assert.fail("Unexpected interruption");
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #11
Source File: ClusterPathChildrenCacheListener.java    From Decision with Apache License 2.0 6 votes vote down vote up
@Override
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception
{
    String node;
    String nodeId;

    try {
        node = ZKPaths.getNodeFromPath(event.getData().getPath());
        nodeId = node.substring(node.indexOf("_") + 1);

        clusterSyncManagerInstance.updateNodeStatus(nodeId, event.getType());

    }catch (Exception e){
        logger.error("Exception receiving event {}: {}", event, e.getMessage());
    }

}
 
Example #12
Source File: ExampleClient.java    From curator with Apache License 2.0 6 votes vote down vote up
@Override
public void takeLeadership(CuratorFramework client) throws Exception
{
    // we are now the leader. This method should not return until we want to relinquish leadership

    final int         waitSeconds = (int)(5 * Math.random()) + 1;

    System.out.println(name + " is now the leader. Waiting " + waitSeconds + " seconds...");
    System.out.println(name + " has been leader " + leaderCount.getAndIncrement() + " time(s) before.");
    try
    {
        Thread.sleep(TimeUnit.SECONDS.toMillis(waitSeconds));
    }
    catch ( InterruptedException e )
    {
        System.err.println(name + " was interrupted.");
        Thread.currentThread().interrupt();
    }
    finally
    {
        System.out.println(name + " relinquishing leadership.\n");
    }
}
 
Example #13
Source File: ServiceCacheLeakTester.java    From curator with Apache License 2.0 6 votes vote down vote up
private static void doWork(CuratorFramework curatorFramework) throws Exception
{
    ServiceInstance<Void> thisInstance = ServiceInstance.<Void>builder().name("myservice").build();
    final ServiceDiscovery<Void> serviceDiscovery = ServiceDiscoveryBuilder.builder(Void.class).client(curatorFramework.usingNamespace("dev")).basePath("/instances").thisInstance(thisInstance).build();
    serviceDiscovery.start();

    for ( int i = 0; i < 100000; i++ )
    {
        final ServiceProvider<Void> s = serviceProvider(serviceDiscovery, "myservice");
        s.start();
        try
        {
            s.getInstance().buildUriSpec();
        }
        finally
        {
            s.close();
        }
    }
}
 
Example #14
Source File: TestPersistentEphemeralNode.java    From xian with Apache License 2.0 6 votes vote down vote up
/**
 * Test that if a persistent ephemeral node is created and the node already exists
 * that if data is present in the PersistentEphermalNode that it is still set. 
 * @throws Exception
 */
@Test
public void testSetDataWhenNodeExists() throws Exception
{
    CuratorFramework curator = newCurator();
    curator.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(PATH, "InitialData".getBytes());
    
    byte[] data = "Hello World".getBytes();
         
    PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, data);
    node.start();
    try
    {
        node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS);
        assertTrue(Arrays.equals(curator.getData().forPath(node.getActualPath()), data));
    }
    finally
    {
        node.close();
    }
}
 
Example #15
Source File: BalancedMetricResolver.java    From timely with Apache License 2.0 6 votes vote down vote up
private void startLeaderLatch(CuratorFramework curatorFramework) {
    try {

        this.leaderLatch = new LeaderLatch(curatorFramework, LEADER_LATCH_PATH);
        this.leaderLatch.start();
        this.leaderLatch.addListener(new LeaderLatchListener() {

            @Override
            public void isLeader() {
                LOG.info("this balancer is the leader");
                isLeader.set(true);
                writeAssignmentsToHdfs();
            }

            @Override
            public void notLeader() {
                LOG.info("this balancer is not the leader");
                isLeader.set(false);
            }
        });
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }
}
 
Example #16
Source File: TestSimpleDistributedQueue.java    From curator with Apache License 2.0 5 votes vote down vote up
public void createNremoveMtest(String dir, int n, int m) throws Exception
{
    CuratorFramework clients[] = null;
    try
    {
        String testString = "Hello World";
        final int num_clients = 2;
        clients = new CuratorFramework[num_clients];
        SimpleDistributedQueue queueHandles[] = new SimpleDistributedQueue[num_clients];
        for ( int i = 0; i < clients.length; i++ )
        {
            clients[i] = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
            clients[i].start();
            queueHandles[i] = new SimpleDistributedQueue(clients[i], dir);
        }

        for ( int i = 0; i < n; i++ )
        {
            String offerString = testString + i;
            queueHandles[0].offer(offerString.getBytes());
        }

        byte data[] = null;
        for ( int i = 0; i < m; i++ )
        {
            data = queueHandles[1].remove();
        }
        assertEquals(new String(data), testString + (m - 1));
    }
    finally
    {
        closeAll(clients);
    }
}
 
Example #17
Source File: ZkStoreBucketServiceTest.java    From pravega with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 10000)
public void testBucketOwnership() throws Exception {
    // verify that ownership is not taken up by another host
    assertFalse(retentionService.takeBucketOwnership(0, "", executor).join());

    // Introduce connection failure error
    zkClient.getZookeeperClient().close();

    // restart
    CuratorFramework zkClient2 = CuratorFrameworkFactory.newClient(zkServer.getConnectString(), 10000, 1000,
            (r, e, s) -> false);
    zkClient2.start();
    BucketStore bucketStore2 = StreamStoreFactory.createZKBucketStore(zkClient2, executor);
    String scope = "scope1";
    String streamName = "stream1";
    bucketStore2.addStreamToBucketStore(BucketStore.ServiceType.RetentionService, scope, streamName, executor).join();
    zkClient2.close();

    zkClient.getZookeeperClient().start();

    Stream stream = new StreamImpl(scope, streamName);

    // verify that at least one of the buckets got the notification
    Map<Integer, BucketService> bucketServices = retentionService.getBucketServices();

    int bucketId = BucketStore.getBucket(scope, streamName, 3);
    BucketService bucketService = bucketServices.get(bucketId);
    AtomicBoolean added = new AtomicBoolean(false);
    RetryHelper.loopWithDelay(() -> !added.get(), () -> CompletableFuture.completedFuture(null)
            .thenAccept(x -> added.set(bucketService.getKnownStreams().size() > 0)), Duration.ofSeconds(1).toMillis(), executor).join();
    assertTrue(bucketService.getKnownStreams().contains(stream));
}
 
Example #18
Source File: ConfigurationsUtils.java    From metron with Apache License 2.0 5 votes vote down vote up
/**
 * Update indexing configs from ZooKeeper.
 *
 * @param configurations The configurations to load into
 * @param client The Zk client to use
 * @throws Exception If there's an error reading data
 */
public static void updateSensorIndexingConfigsFromZookeeper(IndexingConfigurations configurations, CuratorFramework client) throws Exception {
  updateConfigsFromZookeeper( configurations
                            , INDEXING
                            , sensorType -> configurations.updateSensorIndexingConfig(sensorType, readSensorIndexingConfigBytesFromZookeeper(sensorType, client))
                            , client
                            );
}
 
Example #19
Source File: SyncSwitch.java    From canal-1.1.3 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("resource")
private synchronized void startListen(String destination, BooleanMutex mutex) {
    try {
        String path = SYN_SWITCH_ZK_NODE + destination;
        CuratorFramework curator = curatorClient.getCurator();
        NodeCache nodeCache = new NodeCache(curator, path);
        nodeCache.start();
        nodeCache.getListenable().addListener(() -> initMutex(curator, destination, mutex));
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage());
    }
}
 
Example #20
Source File: TestInterProcessSemaphore.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetParticipantNodes() throws Exception
{
    final int LEASES = 3;

    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    List<Lease> leases = Lists.newArrayList();
    client.start();
    try
    {
        InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", LEASES);
        for ( int i = 0; i < LEASES; ++i )
        {
            leases.add(semaphore.acquire());
        }

        Assert.assertEquals(semaphore.getParticipantNodes().size(), LEASES);
    }
    finally
    {
        for ( Lease l : leases )
        {
            CloseableUtils.closeQuietly(l);
        }
        TestCleanState.closeAndTestClean(client);
    }
}
 
Example #21
Source File: TestLeaderSelectorWithExecutor.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception
{
    Timing timing = new Timing();
    LeaderSelector leaderSelector = null;
    CuratorFramework client = CuratorFrameworkFactory.builder()
        .retryPolicy(new ExponentialBackoffRetry(100, 3))
        .connectString(server.getConnectString())
        .sessionTimeoutMs(timing.session())
        .connectionTimeoutMs(timing.connection())
        .build();
    try
    {
        client.start();

        MyLeaderSelectorListener listener = new MyLeaderSelectorListener();
        ExecutorService executorPool = Executors.newFixedThreadPool(20);
        leaderSelector = new LeaderSelector(client, "/test", threadFactory, executorPool, listener);

        leaderSelector.autoRequeue();
        leaderSelector.start();

        timing.sleepABit();

        Assert.assertEquals(listener.getLeaderCount(), 1);
    }
    finally
    {
        CloseableUtils.closeQuietly(leaderSelector);
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #22
Source File: ZkApplicationDiscovery.java    From xian with Apache License 2.0 5 votes vote down vote up
@Override
public ServiceProvider<NodeStatus> load(String key) throws Exception {
    ServiceProvider<NodeStatus> serviceProvider = serviceDiscovery.serviceProviderBuilder()
            // 如果我传入一个不存在的service名,会成功返回一个discovery对象,然后一直返回null的服务实例
            .serviceName(key)
            .build();
    serviceProvider.start();
    serviceProvider.serviceCache().addListener(new ServiceCacheListener<NodeStatus>() {
        @Override
        public void cacheChanged() {
        }

        @Override
        public void cacheChanged(PathChildrenCacheEvent event, ServiceInstance<NodeStatus> instance) {
            ApplicationInstance applicationInstance = ZkServiceInstanceAdaptor.applicationInstance(instance);
            switch (event.getType()) {
                case CHILD_ADDED:
                    EventPublisher.publish(new NodeOnlineEvent().setInstance(applicationInstance));
                    break;
                case CHILD_REMOVED:
                    EventPublisher.publish(new NodeOfflineEvent().setInstance(applicationInstance));
                    break;
                case CHILD_UPDATED:
                    EventPublisher.publish(new NodeUpdatedEvent().setInstance(applicationInstance));
                    break;
                default:
                    LOG.debug("忽略其他事件:" + event.getType());
                    break;
            }
        }

        @Override
        public void stateChanged(CuratorFramework client, ConnectionState newState) {
        }
    });
    return serviceProvider;
}
 
Example #23
Source File: DefaultCurrentClusterServer.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@Override
protected void doStart() throws Exception {
	
	CuratorFramework client = zkClient.get();
	
	if(client.checkExists().forPath(serverPath) != null){ 
		
		byte []data = client.getData().forPath(serverPath);
		throw new IllegalStateException("server already exist:" + new String(data));
	}

	persistentNode = new PersistentNode(zkClient.get(), CreateMode.EPHEMERAL, false, serverPath, Codec.DEFAULT.encodeAsBytes(getClusterInfo()));
	persistentNode.start();
}
 
Example #24
Source File: CheckpointIDCounterTest.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that counter node is NOT removed from ZooKeeper after suspend.
 */
@Test
public void testSuspendKeepsState() throws Exception {
	CheckpointIDCounter counter = createCompletedCheckpoints();
	counter.start();

	CuratorFramework client = ZooKeeper.getClient();
	assertNotNull(client.checkExists().forPath("/checkpoint-id-counter"));

	counter.shutdown(JobStatus.SUSPENDED);
	assertNotNull(client.checkExists().forPath("/checkpoint-id-counter"));
}
 
Example #25
Source File: ZooKeeperWriteProviderFunctionalTest.java    From xio with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteHttp1DeterministicRuleEngineConfig() throws Exception {
  try (TestingServer server = new TestingServer()) {
    server.start();

    Http1DeterministicRuleEngineConfig config = new Http1DeterministicRuleEngineConfig();

    HashMultimap<String, String> headers = HashMultimap.create();
    headers.put("User-Agent", "Bad-actor: 1.0");
    Http1DeterministicRuleEngineConfig.Rule bad =
        new Http1DeterministicRuleEngineConfig.Rule(
            HttpMethod.GET, "/path/to/failure", HttpVersion.HTTP_1_0, headers);
    Http1DeterministicRuleEngineConfig.Rule good =
        new Http1DeterministicRuleEngineConfig.Rule(null, null, null, null);
    config.blacklistRule(bad);
    config.whitelistRule(good);

    ThriftMarshaller marshaller = new ThriftMarshaller();
    RetryPolicy retryPolicy = new RetryOneTime(1);
    try (CuratorFramework client =
        CuratorFrameworkFactory.newClient(server.getConnectString(), retryPolicy)) {
      client.start();
      String path = "/some/path/to/nodes/http1Rules";

      ZooKeeperWriteProvider provider = new ZooKeeperWriteProvider(marshaller, client);

      provider.write(path, config);

      byte[] data = client.getData().forPath(path);
      ThriftUnmarshaller unmarshaller = new ThriftUnmarshaller();
      Http1DeterministicRuleEngineConfig read = new Http1DeterministicRuleEngineConfig();
      unmarshaller.unmarshall(read, data);

      assertEquals(config, read);
    }
  }
}
 
Example #26
Source File: EventContainer.java    From DBus with Apache License 2.0 5 votes vote down vote up
protected void saveZk(String node, String packet) {
    try {
        CuratorFramework curator = CuratorContainer.getInstance().getCurator();
        if (curator.getState() == CuratorFrameworkState.STOPPED) {
            LOG.info("[EventContainer] CuratorFrameworkState:{}", CuratorFrameworkState.STOPPED.name());
        } else {
            curator.setData().forPath(node, packet.getBytes());
        }
    } catch (Exception e) {
        LOG.error("[control-event] 报错znode: " + node + ",数据包:" + packet + "失败!", e);
    }
}
 
Example #27
Source File: MinLagDurationTask.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Inject
public MinLagDurationTask(TaskRegistry taskRegistry,
                          @Maintenance String scope,
                          @GlobalFullConsistencyZooKeeper CuratorFramework curator,
                          @MinLagDurationValues Map<String, ValueStore<Duration>> durationCache) {
    super(taskRegistry, scope + "-compaction-lag", "Full consistency minimum lag",
            durationCache, curator, new ZkDurationSerializer(),
            Suppliers.ofInstance(MinLagConsistencyTimeProvider.DEFAULT_LAG));
}
 
Example #28
Source File: ZookeeperDistributedLock.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public Closeable watchLocks(String lockPathRoot, Executor executor, final Watcher watcher) {
    PathChildrenCache cache = new PathChildrenCache(curator, lockPathRoot, true);
    try {
        cache.start();
        cache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                switch (event.getType()) {
                case CHILD_ADDED:
                    watcher.onLock(event.getData().getPath(),
                            new String(event.getData().getData(), StandardCharsets.UTF_8));
                    break;
                case CHILD_REMOVED:
                    watcher.onUnlock(event.getData().getPath(),
                            new String(event.getData().getData(), StandardCharsets.UTF_8));
                    break;
                default:
                    break;
                }
            }
        }, executor);
    } catch (Exception ex) {
        logger.error("Error to watch lock path " + lockPathRoot, ex);
    }
    return cache;
}
 
Example #29
Source File: MasterRespondsWithNoZkTest.java    From helios with Apache License 2.0 5 votes vote down vote up
@Override
public CuratorFramework newClient(final String connectString, final int sessionTimeoutMs,
                                  final int connectionTimeoutMs, final RetryPolicy retryPolicy,
                                  final ACLProvider aclProvider,
                                  final List<AuthInfo> authorization) {
  final CuratorFramework curator = mock(CuratorFramework.class);

  final RetryLoop retryLoop = mock(RetryLoop.class);
  when(retryLoop.shouldContinue()).thenReturn(false);

  final CuratorZookeeperClient czkClient = mock(CuratorZookeeperClient.class);
  when(czkClient.newRetryLoop()).thenReturn(retryLoop);

  when(curator.getZookeeperClient()).thenReturn(czkClient);

  @SuppressWarnings("unchecked") final Listenable<ConnectionStateListener> mockListener =
      (Listenable<ConnectionStateListener>) mock(Listenable.class);

  when(curator.getConnectionStateListenable()).thenReturn(mockListener);

  final GetChildrenBuilder builder = mock(GetChildrenBuilder.class);
  when(curator.getChildren()).thenReturn(builder);

  try {
    when(builder.forPath(anyString())).thenThrow(
        new KeeperException.ConnectionLossException());
  } catch (Exception ignored) {
    // never throws
  }
  when(curator.newNamespaceAwareEnsurePath(anyString())).thenReturn(mock(EnsurePath.class));

  return curator;
}
 
Example #30
Source File: ZookeeperLeaderAutoConfiguration.java    From spring-cloud-cluster with Apache License 2.0 5 votes vote down vote up
@Bean(initMethod = "start", destroyMethod = "close")
public CuratorFramework zookeeperLeaderCuratorClient() throws Exception {
	CuratorFramework client = CuratorFrameworkFactory.builder()
			.defaultData(new byte[0])
			.retryPolicy(new ExponentialBackoffRetry(1000, 3))
			.connectString(zkp.getConnect()).build();
	return client;
}