org.apache.curator.framework.state.ConnectionStateListener Java Examples

The following examples show how to use org.apache.curator.framework.state.ConnectionStateListener. 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: CuratorStateManager.java    From incubator-heron with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<Boolean> setMetricsCacheLocation(
    TopologyMaster.MetricsCacheLocation location,
    String topologyName) {
  client.getConnectionStateListenable().addListener(new ConnectionStateListener() {
    @Override
    public void stateChanged(CuratorFramework arg0, ConnectionState arg1) {
      if (arg1 != ConnectionState.CONNECTED) {
        // if not the first time successful connection, fail fast
        throw new RuntimeException("Unexpected state change to: " + arg1.name());
      }
    }
  });
  return createNode(
      StateLocation.METRICSCACHE_LOCATION, topologyName, location.toByteArray(), true);
}
 
Example #2
Source File: TestQueueSharder.java    From curator with Apache License 2.0 6 votes vote down vote up
private BlockingQueueConsumer<String> makeConsumer(final CountDownLatch latch)
{
    ConnectionStateListener connectionStateListener = new ConnectionStateListener()
    {
        @Override
        public void stateChanged(CuratorFramework client, ConnectionState newState)
        {
        }
    };

    return new BlockingQueueConsumer<String>(connectionStateListener)
    {
        @Override
        public void consumeMessage(String message) throws Exception
        {
            if ( latch != null )
            {
                latch.await();
            }
            super.consumeMessage(message);
        }
    };
}
 
Example #3
Source File: CuratorFrameworkBuilder.java    From chassis with Apache License 2.0 6 votes vote down vote up
private CuratorFramework buildCuratorWithZookeeperDirectly(Configuration configuration) {
      LOGGER.debug("configuring direct zookeeper connection.");
      
      CuratorFramework curator = CuratorFrameworkFactory.newClient(
              this.zookeeperConnectionString,
              configuration.getInt(ZOOKEEPER_SESSION_TIMEOUT_MILLIS.getPropertyName()),
              configuration.getInt(ZOOKEEPER_CONNECTION_TIMEOUT_MILLIS.getPropertyName()),
              buildZookeeperRetryPolicy(configuration));
      curator.getConnectionStateListenable().addListener(new ConnectionStateListener() {
	public void stateChanged(CuratorFramework client, ConnectionState newState) {
		LOGGER.debug("Connection state to ZooKeeper changed: " + newState);
	}
});
      
      return curator;
  }
 
Example #4
Source File: TestQueueSharder.java    From xian with Apache License 2.0 6 votes vote down vote up
private BlockingQueueConsumer<String> makeConsumer(final CountDownLatch latch)
{
    ConnectionStateListener connectionStateListener = new ConnectionStateListener()
    {
        @Override
        public void stateChanged(CuratorFramework client, ConnectionState newState)
        {
        }
    };

    return new BlockingQueueConsumer<String>(connectionStateListener)
    {
        @Override
        public void consumeMessage(String message) throws Exception
        {
            if ( latch != null )
            {
                latch.await();
            }
            super.consumeMessage(message);
        }
    };
}
 
Example #5
Source File: TestDistributedDelayQueue.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void     testBasic() throws Exception
{
    Timing                          timing = new Timing();
    DistributedDelayQueue<Long>     queue = null;
    CuratorFramework                client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    client.start();
    try
    {
        BlockingQueueConsumer<Long> consumer = new BlockingQueueConsumer<Long>(Mockito.mock(ConnectionStateListener.class));
        queue = QueueBuilder.builder(client, consumer, new LongSerializer(), "/test").buildDelayQueue();
        queue.start();

        queue.put(1L, System.currentTimeMillis() + 1000);
        Thread.sleep(100);
        Assert.assertEquals(consumer.size(), 0);    // delay hasn't been reached

        Long        value = consumer.take(timing.forWaiting().seconds(), TimeUnit.SECONDS);
        Assert.assertEquals(value, Long.valueOf(1));
    }
    finally
    {
        CloseableUtils.closeQuietly(queue);
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #6
Source File: TestDistributedDelayQueue.java    From xian with Apache License 2.0 6 votes vote down vote up
@Test
public void     testBasic() throws Exception
{
    Timing                          timing = new Timing();
    DistributedDelayQueue<Long>     queue = null;
    CuratorFramework                client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    client.start();
    try
    {
        BlockingQueueConsumer<Long> consumer = new BlockingQueueConsumer<Long>(Mockito.mock(ConnectionStateListener.class));
        queue = QueueBuilder.builder(client, consumer, new LongSerializer(), "/test").buildDelayQueue();
        queue.start();

        queue.put(1L, System.currentTimeMillis() + 1000);
        Thread.sleep(100);
        Assert.assertEquals(consumer.size(), 0);    // delay hasn't been reached

        Long        value = consumer.take(timing.forWaiting().seconds(), TimeUnit.SECONDS);
        Assert.assertEquals(value, Long.valueOf(1));
    }
    finally
    {
        CloseableUtils.closeQuietly(queue);
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #7
Source File: AgentServicesAutoConfiguration.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Get an implementation of {@link AgentRoutingService} if one hasn't already been defined.
 * This bean is created if Zookeeper is enabled, it uses Curator's {@link ServiceDiscovery}.
 *
 * @param genieHostInfo                    The local genie host information
 * @param serviceDiscovery                 The Zookeeper Curator service discovery
 * @param taskScheduler                    The task scheduler
 * @param listenableCuratorConnectionState the connection state listenable
 * @param registry                         The metrics registry
 * @return A {@link AgentRoutingServiceImpl} instance
 */
@Bean
@ConditionalOnBean(ServiceDiscovery.class)
@ConditionalOnMissingBean(AgentRoutingService.class)
public AgentRoutingService agentRoutingServiceCurator(
    final GenieHostInfo genieHostInfo,
    final ServiceDiscovery<AgentRoutingServiceCuratorDiscoveryImpl.Agent> serviceDiscovery,
    @Qualifier("genieTaskScheduler") final TaskScheduler taskScheduler,
    final Listenable<ConnectionStateListener> listenableCuratorConnectionState,
    final MeterRegistry registry
) {
    return new AgentRoutingServiceCuratorDiscoveryImpl(
        genieHostInfo,
        serviceDiscovery,
        taskScheduler,
        listenableCuratorConnectionState,
        registry
    );
}
 
Example #8
Source File: WorkStateMachine.java    From DBus with Apache License 2.0 6 votes vote down vote up
private void registerConnectionStateListener() {
    ConnectionStateListener listener = new ConnectionStateListener() {
        @Override
        public void stateChanged(CuratorFramework client, ConnectionState newState) {
            switch (newState) {
                default: {
                    break;
                }
                case RECONNECTED: {
                    registerAssignmentListener();
                    break;
                }
            }
        }
    };
    zkUtils.setConnectionStateListenable(listener);
}
 
Example #9
Source File: ZKClientImpl.java    From bistoury with GNU General Public License v3.0 6 votes vote down vote up
private void waitUntilZkStart() {
    final CountDownLatch latch = new CountDownLatch(1);
    addConnectionChangeListener(new ConnectionStateListener() {
        @Override
        public void stateChanged(CuratorFramework client, ConnectionState newState) {
            if (newState == ConnectionState.CONNECTED) {
                latch.countDown();
            }
        }
    });
    client.start();
    try {
        latch.await();
    } catch (InterruptedException e) {
        logger.error("start zk latch.await() error", e);
        Thread.currentThread().interrupt();
    }
}
 
Example #10
Source File: AgentRoutingServiceCuratorDiscoveryImpl.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor.
 *
 * @param genieHostInfo                    The genie local host information
 * @param serviceDiscovery                 The service discovery client
 * @param taskScheduler                    The task scheduler
 * @param listenableCuratorConnectionState The listenable curator client connection status
 * @param registry                         The metrics registry
 */
public AgentRoutingServiceCuratorDiscoveryImpl(
    final GenieHostInfo genieHostInfo,
    final ServiceDiscovery<Agent> serviceDiscovery,
    final TaskScheduler taskScheduler,
    final Listenable<ConnectionStateListener> listenableCuratorConnectionState,
    final MeterRegistry registry
) {
    this.localHostname = genieHostInfo.getHostname();
    this.serviceDiscovery = serviceDiscovery;
    this.taskScheduler = taskScheduler;
    this.registry = registry;

    // Schedule periodic reconciliation between in-memory connected set and Service Discovery state
    this.taskScheduler.schedule(this::reconcileRegistrationsTask, trigger);

    // Listen for Curator session state changes
    listenableCuratorConnectionState.addListener(this::handleConnectionStateChange);

    // Create gauge metric for agents connected and registered
    registry.gauge(CONNECTED_AGENTS_GAUGE_NAME, EMPTY_TAG_SET, this.connectedAgentsSet, Set::size);
    registry.gaugeMapSize(REGISTERED_AGENTS_GAUGE_NAME, EMPTY_TAG_SET, this.registeredAgentsMap);
}
 
Example #11
Source File: ZKDiscoveryServiceImpl.java    From YuRPC with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化方法,(仅在使用无参构造器时使用)
 *
 * @param zookeeper
 * @throws java.lang.Throwable 异常
 */
public void init(String zookeeper) throws Throwable {
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
    this.client = CuratorFrameworkFactory.newClient(zookeeper, retryPolicy);
    this.client.start();
    this.client.getConnectionStateListenable().addListener((ConnectionStateListener) (CuratorFramework cf, ConnectionState cs) -> {
        if (cs == ConnectionState.RECONNECTED) {
            if (pathValue != null && !pathValue.isEmpty()) {
                pathValue.entrySet().forEach((entry) -> {
                    String path = entry.getKey();
                    byte[] value = entry.getValue();
                    try {
                        cf.create().withMode(CreateMode.EPHEMERAL).forPath(path, value);
                    } catch (Exception ex) {
                        LOGGER.error(ex.getMessage());
                    }
                });
            }
        }
    }, watcherExecutorService);
}
 
Example #12
Source File: CustomZKManager.java    From zkdoctor with Apache License 2.0 6 votes vote down vote up
/**
 * 获取zk连接,统一入口
 *
 * @param instanceId 实例id
 * @param host       zk ip
 * @param port       zk port
 * @return
 */
public CuratorFramework getZookeeper(final int instanceId, final String host, final int port) {
    if (!ZK_CONNECT_POOL.containsKey(instanceId)) {
        synchronized (this) { // 保证创建的客户端连接只有唯一一个
            if (!ZK_CONNECT_POOL.containsKey(instanceId)) {
                CuratorFramework zkClient = createClient(host, port, new ConnectionStateListener() {
                    @Override
                    public void stateChanged(CuratorFramework client, ConnectionState newState) {
                        LOGGER.warn("ZK client connection state changed:{}, host:port = {}:{}.", newState, host, port);
                    }
                });
                if (zkClient != null) {
                    ZK_CONNECT_POOL.put(instanceId, zkClient);
                }
                return zkClient;
            } else {
                return ZK_CONNECT_POOL.get(instanceId);
            }
        }
    } else {
        return ZK_CONNECT_POOL.get(instanceId);
    }
}
 
Example #13
Source File: WorkerHealthcheck.java    From DBus with Apache License 2.0 6 votes vote down vote up
private void registerConnectionStateListener() {
    ConnectionStateListener listener = new ConnectionStateListener() {
        @Override
        public void stateChanged(CuratorFramework client, ConnectionState newState) {
            switch (newState) {
                default: {
                    break;
                }
                case RECONNECTED: {
                    try {
                        register();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }
    };
    zkUtils.setConnectionStateListenable(listener);
}
 
Example #14
Source File: ZookeeperWorkerRegister.java    From idworker with Apache License 2.0 5 votes vote down vote up
/**
 * 添加连接监听
 * 
 * @param listener zk状态监听listener
 */
@Deprecated
public void addConnectionListener(ConnectionStateListener listener) {
    // CuratorFramework client = (CuratorFramework)
    // regCenter.getRawClient();
    // client.getConnectionStateListenable().addListener(listener);
}
 
Example #15
Source File: TestDistributedPriorityQueue.java    From xian with Apache License 2.0 5 votes vote down vote up
@Test
public void     testMinItemsBeforeRefresh() throws Exception
{
    DistributedPriorityQueue<Integer>   queue = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();
    try
    {
        final int minItemsBeforeRefresh = 3;

        BlockingQueueConsumer<Integer> consumer = new BlockingQueueConsumer<Integer>(Mockito.mock(ConnectionStateListener.class));
        queue = QueueBuilder.builder(client, consumer, new IntSerializer(), "/test").buildPriorityQueue(minItemsBeforeRefresh);
        queue.start();

        for ( int i = 0; i < 10; ++i )
        {
            queue.put(i, 10 + i);
        }

        Assert.assertEquals(consumer.take(1, TimeUnit.SECONDS), new Integer(0));
        queue.put(1000, 1); // lower priority

        int         count = 0;
        while ( consumer.take(1, TimeUnit.SECONDS) < 1000 )
        {
            ++count;
        }
        Assert.assertTrue(Math.abs(minItemsBeforeRefresh - count) < minItemsBeforeRefresh, String.format("Diff: %d - min: %d", Math.abs(minItemsBeforeRefresh - count), minItemsBeforeRefresh));     // allows for some slack - testing that within a slop value the newly inserted item with lower priority comes out
    }
    finally
    {
        CloseableUtils.closeQuietly(queue);
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #16
Source File: TestDistributedDelayQueue.java    From xian with Apache License 2.0 5 votes vote down vote up
@Test
public void     testLateAddition() throws Exception
{
    Timing                          timing = new Timing();
    DistributedDelayQueue<Long>     queue = null;
    CuratorFramework                client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    client.start();
    try
    {
        BlockingQueueConsumer<Long> consumer = new BlockingQueueConsumer<Long>(Mockito.mock(ConnectionStateListener.class));
        queue = QueueBuilder.builder(client, consumer, new LongSerializer(), "/test").buildDelayQueue();
        queue.start();

        queue.put(1L, System.currentTimeMillis() + Integer.MAX_VALUE);  // never come out
        Long        value = consumer.take(1, TimeUnit.SECONDS);
        Assert.assertNull(value);

        queue.put(2L, System.currentTimeMillis());
        value = consumer.take(timing.seconds(), TimeUnit.SECONDS);
        Assert.assertEquals(value, Long.valueOf(2));

        value = consumer.take(1, TimeUnit.SECONDS);
        Assert.assertNull(value);
    }
    finally
    {
        CloseableUtils.closeQuietly(queue);
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #17
Source File: TestSharedCount.java    From xian with Apache License 2.0 5 votes vote down vote up
@Test
public void testDisconnectEventOnWatcherDoesNotRetry() throws Exception
{
    final CountDownLatch gotSuspendEvent = new CountDownLatch(1);

    CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryNTimes(10, 1000));
    curatorFramework.start();
    curatorFramework.blockUntilConnected();

    SharedCount sharedCount = new SharedCount(curatorFramework, "/count", 10);
    sharedCount.start();

    curatorFramework.getConnectionStateListenable().addListener(new ConnectionStateListener() {
        @Override
        public void stateChanged(CuratorFramework client, ConnectionState newState) {
            if (newState == ConnectionState.SUSPENDED) {
                gotSuspendEvent.countDown();
            }
        }
    });

    try
    {
        server.stop();
        // if watcher goes into 10second retry loop we won't get timely notification
        Assert.assertTrue(gotSuspendEvent.await(5, TimeUnit.SECONDS));
    }
    finally
    {
        CloseableUtils.closeQuietly(sharedCount);
        CloseableUtils.closeQuietly(curatorFramework);
    }
}
 
Example #18
Source File: TestDistributedDelayQueue.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void     testLateAddition() throws Exception
{
    Timing                          timing = new Timing();
    DistributedDelayQueue<Long>     queue = null;
    CuratorFramework                client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    client.start();
    try
    {
        BlockingQueueConsumer<Long> consumer = new BlockingQueueConsumer<Long>(Mockito.mock(ConnectionStateListener.class));
        queue = QueueBuilder.builder(client, consumer, new LongSerializer(), "/test").buildDelayQueue();
        queue.start();

        queue.put(1L, System.currentTimeMillis() + Integer.MAX_VALUE);  // never come out
        Long        value = consumer.take(1, TimeUnit.SECONDS);
        Assert.assertNull(value);

        queue.put(2L, System.currentTimeMillis());
        value = consumer.take(timing.seconds(), TimeUnit.SECONDS);
        Assert.assertEquals(value, Long.valueOf(2));

        value = consumer.take(1, TimeUnit.SECONDS);
        Assert.assertNull(value);
    }
    finally
    {
        CloseableUtils.closeQuietly(queue);
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #19
Source File: TestSharedCount.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testDisconnectEventOnWatcherDoesNotRetry() throws Exception
{
    final CountDownLatch gotSuspendEvent = new CountDownLatch(1);

    CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryNTimes(10, 1000));
    curatorFramework.start();
    curatorFramework.blockUntilConnected();

    SharedCount sharedCount = new SharedCount(curatorFramework, "/count", 10);
    sharedCount.start();

    curatorFramework.getConnectionStateListenable().addListener(new ConnectionStateListener() {
        @Override
        public void stateChanged(CuratorFramework client, ConnectionState newState) {
            if (newState == ConnectionState.SUSPENDED) {
                gotSuspendEvent.countDown();
            }
        }
    });

    try
    {
        server.stop();
        // if watcher goes into 10second retry loop we won't get timely notification
        Assert.assertTrue(gotSuspendEvent.await(5, TimeUnit.SECONDS));
    }
    finally
    {
        CloseableUtils.closeQuietly(sharedCount);
        CloseableUtils.closeQuietly(curatorFramework);
    }
}
 
Example #20
Source File: ZookeeperAutoConfiguration.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * The Curator-client connection state listenable.
 *
 * @param client              The curator framework client to use
 * @return {@link ServiceDiscovery} bean for instances of type {@link AgentRoutingServiceCuratorDiscoveryImpl.Agent}
 */
@Bean
@ConditionalOnMissingBean(Listenable.class)
Listenable<ConnectionStateListener> listenableCuratorConnectionState(
    final CuratorFramework client
) {
    return client.getConnectionStateListenable();
}
 
Example #21
Source File: CustomZKManager.java    From zkdoctor with Apache License 2.0 5 votes vote down vote up
/**
 * 创建zk客户端
 *
 * @param host     zk ip
 * @param port     zk port
 * @param listener 连接监听器
 * @return
 */
private CuratorFramework createClient(String host, int port, ConnectionStateListener listener) {
    if (StringUtils.isBlank(host)) {
        return null;
    }
    CuratorFramework zkClient = CuratorFrameworkFactory.newClient(genertateConnectStr(host, port),
            sessionTimeOut, connectionTimeOut, defaultRetryPolicy);
    zkClient.start();
    if (listener != null) {
        zkClient.getConnectionStateListenable().addListener(listener);
    }
    return zkClient;
}
 
Example #22
Source File: TestDistributedQueue.java    From xian with Apache License 2.0 5 votes vote down vote up
@Test
public void     testSimple() throws Exception
{
    final int                   itemQty = 10;

    DistributedQueue<TestQueueItem>  queue = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();
    try
    {
        BlockingQueueConsumer<TestQueueItem> consumer = new BlockingQueueConsumer<TestQueueItem>(Mockito.mock(ConnectionStateListener.class));

        queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH).buildQueue();
        queue.start();

        QueueTestProducer producer = new QueueTestProducer(queue, itemQty, 0);

        ExecutorService     service = Executors.newCachedThreadPool();
        service.submit(producer);

        int                 iteration = 0;
        while ( consumer.size() < itemQty )
        {
            Assert.assertTrue(++iteration < 10);
            Thread.sleep(1000);
        }

        int                 i = 0;
        for ( TestQueueItem item : consumer.getItems() )
        {
            Assert.assertEquals(item.str, Integer.toString(i++));
        }
    }
    finally
    {
        CloseableUtils.closeQuietly(queue);
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #23
Source File: ZookeeperClient.java    From kafka-monitor with Apache License 2.0 5 votes vote down vote up
private void reconnectProcess() {
    curator.getConnectionStateListenable().addListener(new ConnectionStateListener() {
        @Override
        public void stateChanged(CuratorFramework client, ConnectionState newState) {
        }
    });
}
 
Example #24
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 #25
Source File: CuratorFrameworkBuilder.java    From chassis with Apache License 2.0 5 votes vote down vote up
private CuratorFramework buildCuratorWithExhibitor(Configuration configuration) {
      LOGGER.debug("configuring zookeeper connection through Exhibitor...");
      ExhibitorEnsembleProvider ensembleProvider =
              new KixeyeExhibitorEnsembleProvider(
                      exhibitors,
                      new KixeyeExhibitorRestClient(configuration.getBoolean(EXHIBITOR_USE_HTTPS.getPropertyName())),
                      configuration.getString(EXHIBITOR_URI_PATH.getPropertyName()),
                      configuration.getInt(EXHIBITOR_POLL_INTERVAL.getPropertyName()),
                      new ExponentialBackoffRetry(
                              configuration.getInt(EXHIBITOR_INITIAL_SLEEP_MILLIS.getPropertyName()),
                              configuration.getInt(EXHIBITOR_MAX_RETRIES.getPropertyName()),
                              configuration.getInt(EXHIBITOR_RETRIES_MAX_MILLIS.getPropertyName())));

      //without this (undocumented) step, curator will attempt (and fail) to connect to a local instance of zookeeper (default behavior if no zookeeper connection string is provided) for
      //several seconds until the EnsembleProvider polls to get the SERVER list from Exhibitor. Polling before staring curator
      //ensures that the SERVER list from Exhibitor is already downloaded before curator attempts to connect to zookeeper.
      try {
          ensembleProvider.pollForInitialEnsemble();
      } catch (Exception e) {
          try {
              Closeables.close(ensembleProvider, true);
          } catch (IOException e1) {
          }
          throw new BootstrapException("Failed to initialize Exhibitor with host(s) " + exhibitors.getHostnames(), e);
      }
      
      CuratorFramework curator = CuratorFrameworkFactory.builder().ensembleProvider(ensembleProvider).retryPolicy(buildZookeeperRetryPolicy(configuration)).build();
      curator.getConnectionStateListenable().addListener(new ConnectionStateListener() {
	public void stateChanged(CuratorFramework client, ConnectionState newState) {
		LOGGER.debug("Connection state to ZooKeeper changed: " + newState);
	}
});
      
      return curator;
  }
 
Example #26
Source File: JobNodeStorageTest.java    From shardingsphere-elasticjob-lite with Apache License 2.0 5 votes vote down vote up
@Test
public void assertAddConnectionStateListener() {
    CuratorFramework client = mock(CuratorFramework.class);
    @SuppressWarnings("unchecked")
    Listenable<ConnectionStateListener> listeners = mock(Listenable.class);
    ConnectionStateListener listener = mock(ConnectionStateListener.class);
    when(client.getConnectionStateListenable()).thenReturn(listeners);
    when(regCenter.getRawClient()).thenReturn(client);
    jobNodeStorage.addConnectionStateListener(listener);
    verify(listeners).addListener(listener);
}
 
Example #27
Source File: TestDistributedQueue.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void     testMultiPutterSingleGetter() throws Exception
{
    final int                   itemQty = 100;

    DistributedQueue<TestQueueItem>  queue = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();
    try
    {
        BlockingQueueConsumer<TestQueueItem> consumer = new BlockingQueueConsumer<TestQueueItem>(Mockito.mock(ConnectionStateListener.class));

        queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH).buildQueue();
        queue.start();

        QueueTestProducer producer1 = new QueueTestProducer(queue, itemQty / 2, 0);
        QueueTestProducer producer2 = new QueueTestProducer(queue, ((itemQty + 1) / 2), itemQty / 2);

        ExecutorService     service = Executors.newCachedThreadPool();
        service.submit(producer1);
        service.submit(producer2);

        int                 iteration = 0;
        while ( consumer.size() < itemQty )
        {
            Assert.assertTrue(++iteration < 10);
            Thread.sleep(1000);
        }

        List<TestQueueItem> items = consumer.getItems();

        Assert.assertEquals(com.google.common.collect.Sets.<TestQueueItem>newHashSet(items).size(), items.size()); // check no duplicates
    }
    finally
    {
        CloseableUtils.closeQuietly(queue);
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #28
Source File: ClusterStateHolder.java    From hermes with Apache License 2.0 5 votes vote down vote up
private void addConnectionStateListener() {
	m_client.get().getConnectionStateListenable().addListener(new ConnectionStateListener() {

		@Override
		public void stateChanged(CuratorFramework client, ConnectionState newState) {
			switch (newState) {
			case LOST:
				if (m_connected.get()) {
					m_connected.set(false);
					m_guard.upgradeVersion();
					log.info("Disconnected from zk(state:{})", newState);
				}
				break;
			case RECONNECTED:
			case CONNECTED:
				if (!m_connected.get()) {
					m_connected.set(true);
					becomeObserver();
					log.info("Reconnected to zk(state:{})", newState);
				}
				break;
			default:
				break;
			}
		}
	}, m_roleChangeExecutor);
}
 
Example #29
Source File: TestDistributedPriorityQueue.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void     testMinItemsBeforeRefresh() throws Exception
{
    DistributedPriorityQueue<Integer>   queue = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();
    try
    {
        final int minItemsBeforeRefresh = 3;

        BlockingQueueConsumer<Integer> consumer = new BlockingQueueConsumer<Integer>(Mockito.mock(ConnectionStateListener.class));
        queue = QueueBuilder.builder(client, consumer, new IntSerializer(), "/test").buildPriorityQueue(minItemsBeforeRefresh);
        queue.start();

        for ( int i = 0; i < 10; ++i )
        {
            queue.put(i, 10 + i);
        }

        Assert.assertEquals(consumer.take(1, TimeUnit.SECONDS), new Integer(0));
        queue.put(1000, 1); // lower priority

        int         count = 0;
        while ( consumer.take(1, TimeUnit.SECONDS) < 1000 )
        {
            ++count;
        }
        Assert.assertTrue(Math.abs(minItemsBeforeRefresh - count) < minItemsBeforeRefresh, String.format("Diff: %d - min: %d", Math.abs(minItemsBeforeRefresh - count), minItemsBeforeRefresh));     // allows for some slack - testing that within a slop value the newly inserted item with lower priority comes out
    }
    finally
    {
        CloseableUtils.closeQuietly(queue);
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #30
Source File: TestDistributedQueue.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void     testSimple() throws Exception
{
    final int                   itemQty = 10;

    DistributedQueue<TestQueueItem>  queue = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();
    try
    {
        BlockingQueueConsumer<TestQueueItem> consumer = new BlockingQueueConsumer<TestQueueItem>(Mockito.mock(ConnectionStateListener.class));

        queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH).buildQueue();
        queue.start();

        QueueTestProducer producer = new QueueTestProducer(queue, itemQty, 0);

        ExecutorService     service = Executors.newCachedThreadPool();
        service.submit(producer);

        int                 iteration = 0;
        while ( consumer.size() < itemQty )
        {
            Assert.assertTrue(++iteration < 10);
            Thread.sleep(1000);
        }

        int                 i = 0;
        for ( TestQueueItem item : consumer.getItems() )
        {
            Assert.assertEquals(item.str, Integer.toString(i++));
        }
    }
    finally
    {
        CloseableUtils.closeQuietly(queue);
        CloseableUtils.closeQuietly(client);
    }
}