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

The following examples show how to use org.apache.curator.framework.state.ConnectionState. 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: SharedCount.java    From xian with Apache License 2.0 6 votes vote down vote up
@Override
public void     addListener(final SharedCountListener listener, Executor executor)
{
    SharedValueListener     valueListener = new SharedValueListener()
    {
        @Override
        public void valueHasChanged(SharedValueReader sharedValue, byte[] newValue) throws Exception
        {
            listener.countHasChanged(SharedCount.this, fromBytes(newValue));
        }

        @Override
        public void stateChanged(CuratorFramework client, ConnectionState newState)
        {
            listener.stateChanged(client, newState);
        }
    };
    sharedValue.getListenable().addListener(valueListener, executor);
    listeners.put(listener, valueListener);
}
 
Example #2
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 #3
Source File: DistributedIdQueueExample.java    From ZKRecipesByExample with Apache License 2.0 6 votes vote down vote up
private static QueueConsumer<String> createQueueConsumer() {

		return new QueueConsumer<String>(){

			@Override
			public void stateChanged(CuratorFramework client, ConnectionState newState) {
				System.out.println("connection new state: " + newState.name());
			}

			@Override
			public void consumeMessage(String message) throws Exception {
				System.out.println("consume one message: " + message);				
			}
			
		};
	}
 
Example #4
Source File: AgentRoutingServiceCuratorDiscoveryImpl.java    From genie with Apache License 2.0 6 votes vote down vote up
private void handleConnectionStateChange(final CuratorFramework client, final ConnectionState newState) {

        this.registry.counter(
            ZOOKEEPER_SESSION_STATE_COUNTER_NAME,
            Sets.newHashSet(Tag.of(ZK_CONNECTION_STATE_TAG_NAME, newState.name()))
        ).increment();

        switch (newState) {
            case CONNECTED:
                // Immediately schedule a reconciliation
                log.info("Zookeeper/Curator connected (or re-connected)");
                this.taskScheduler.schedule(this::reconcileRegistrationsTask, Instant.now());
                break;

            case LOST:
                // When session expires, all ephemeral nodes disappear
                log.info("Zookeeper/Curator session expired, all instances will need to re-register");
                this.registeredAgentsMap.clear();
                break;

            default:
                log.debug("Zookeeper/Curator connection state changed to: {}", newState);
        }
    }
 
Example #5
Source File: CuratorFrameworkImpl.java    From xian with Apache License 2.0 6 votes vote down vote up
void validateConnection(Watcher.Event.KeeperState state)
{
    if ( state == Watcher.Event.KeeperState.Disconnected )
    {
        suspendConnection();
    }
    else if ( state == Watcher.Event.KeeperState.Expired )
    {
        connectionStateManager.addStateChange(ConnectionState.LOST);
    }
    else if ( state == Watcher.Event.KeeperState.SyncConnected )
    {
        connectionStateManager.addStateChange(ConnectionState.RECONNECTED);
    }
    else if ( state == Watcher.Event.KeeperState.ConnectedReadOnly )
    {
        connectionStateManager.addStateChange(ConnectionState.READ_ONLY);
    }
}
 
Example #6
Source File: ZooKeeperLeaderElectionService.java    From flink with Apache License 2.0 6 votes vote down vote up
protected void handleStateChange(ConnectionState newState) {
	switch (newState) {
		case CONNECTED:
			LOG.debug("Connected to ZooKeeper quorum. Leader election can start.");
			break;
		case SUSPENDED:
			LOG.warn("Connection to ZooKeeper suspended. The contender " + leaderContender.getAddress()
				+ " no longer participates in the leader election.");
			break;
		case RECONNECTED:
			LOG.info("Connection to ZooKeeper was reconnected. Leader election can be restarted.");
			break;
		case LOST:
			// Maybe we have to throw an exception here to terminate the JobManager
			LOG.warn("Connection to ZooKeeper lost. The contender " + leaderContender.getAddress()
				+ " no longer participates in the leader election.");
			break;
	}
}
 
Example #7
Source File: EventuateLeaderSelectorListener.java    From light-eventuate-4j with Apache License 2.0 6 votes vote down vote up
@Override
public void stateChanged(CuratorFramework client, ConnectionState newState) {

  logger.debug("StateChanged: {}", newState);

  switch (newState) {
    case SUSPENDED:
      resignLeadership();
      break;

    case RECONNECTED:
      try {
        takeLeadership();
      } catch (InterruptedException e) {
        logger.error("While handling RECONNECTED", e);
      }
      break;

    case LOST:
      resignLeadership();
      break;
  }
}
 
Example #8
Source File: SharedCacheCoordinator.java    From datawave with Apache License 2.0 6 votes vote down vote up
private void reregisterCounter(String counterName, SharedCountListener listener, int seedValue) throws Exception {
    ArgumentChecker.notNull(counterName, listener);
    
    SharedCount count = new SharedCount(curatorClient, ZKPaths.makePath("/counters", counterName), seedValue);
    count.start();
    sharedCounters.put(counterName, count);
    sharedCountListeners.put(counterName, listener);
    localCounters.put(counterName, count.getCount());
    
    count.addListener(new SharedCountListener() {
        @Override
        public void countHasChanged(SharedCountReader sharedCountReader, int i) throws Exception {}
        
        @Override
        public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) {
            if (connectionState == ConnectionState.RECONNECTED) {
                try {
                    reregisterCounter(counterName, sharedCountListeners.get(counterName), localCounters.get(counterName));
                } catch (Exception e) {
                    System.err.println("Unable to re-register counter " + counterName + ": " + e.getMessage());
                }
            }
        }
    });
    count.addListener(listener);
}
 
Example #9
Source File: TenantRepository.java    From vespa with Apache License 2.0 6 votes vote down vote up
private void stateChanged(CuratorFramework framework, ConnectionState connectionState) {
    switch (connectionState) {
        case CONNECTED:
            metricUpdater.incZKConnected();
            break;
        case SUSPENDED:
            metricUpdater.incZKSuspended();
            break;
        case RECONNECTED:
            metricUpdater.incZKReconnected();
            break;
        case LOST:
            metricUpdater.incZKConnectionLost();
            break;
        case READ_ONLY:
            // NOTE: Should not be relevant for configserver.
            break;
    }
}
 
Example #10
Source File: ZooKeeperCheckpointIDCounter.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public void setCount(long newId) throws Exception {
	ConnectionState connState = connStateListener.getLastState();

	if (connState != null) {
		throw new IllegalStateException("Connection state: " + connState);
	}

	if (newId > Integer.MAX_VALUE) {
		throw new IllegalArgumentException("ZooKeeper checkpoint counter only supports " +
				"checkpoints Ids up to " + Integer.MAX_VALUE  + ", but given value is" +
				newId);
	}

	sharedCount.setCount((int) newId);
}
 
Example #11
Source File: SharedTriState.java    From datawave with Apache License 2.0 6 votes vote down vote up
public void addListener(final SharedTriStateListener listener, Executor executor) {
    SharedValueListener valueListener = new SharedValueListener() {
        public void valueHasChanged(SharedValueReader sharedValue, byte[] newValue) throws Exception {
            if (log.isDebugEnabled()) {
                log.debug("valueHasChanged in " + Arrays.toString(sharedValue.getValue()) + " to " + Arrays.toString(newValue));
            }
            
            listener.stateHasChanged(SharedTriState.this, SharedTriState.fromBytes(newValue));
        }
        
        public void stateChanged(CuratorFramework client, ConnectionState newState) {
            listener.stateChanged(client, newState);
        }
    };
    this.sharedValue.getListenable().addListener(valueListener, executor);
    this.listeners.put(listener, valueListener);
}
 
Example #12
Source File: ZkLeaderSelector.java    From binlake with Apache License 2.0 6 votes vote down vote up
public void stateChanged(CuratorFramework client, ConnectionState newState) {
    try {
        LogUtils.warn.warn(client.getData().toString() + " state change to " + newState);
    } catch (Throwable exp) {
        // catch any null pointer exception
    }

    if (newState == ConnectionState.SUSPENDED || newState == ConnectionState.LOST) {
        try {
            refreshLogPos(); // 链接状态变更 则需要将最新的binlog offset 刷新到 zk
        } catch (Exception e) {
            // 更新binlog 位置异常
            LogUtils.error.error("state change to " + newState + " refresh log position error", e);
        }
        killWorkAndAbandonLeader();
    }
}
 
Example #13
Source File: DistributedQueueExample.java    From ZKRecipesByExample with Apache License 2.0 6 votes vote down vote up
private static QueueConsumer<String> createQueueConsumer() {

		return new QueueConsumer<String>(){

			@Override
			public void stateChanged(CuratorFramework client, ConnectionState newState) {
				System.out.println("connection new state: " + newState.name());
			}

			@Override
			public void consumeMessage(String message) throws Exception {
				System.out.println("consume one message: " + message);				
			}
			
		};
	}
 
Example #14
Source File: ServiceDiscoveryImpl.java    From curator with Apache License 2.0 6 votes vote down vote up
@Override
public void stateChanged(CuratorFramework client, ConnectionState newState)
{
    if ( (newState == ConnectionState.RECONNECTED) || (newState == ConnectionState.CONNECTED) )
    {
        try
        {
            log.debug("Re-registering due to reconnection");
            reRegisterServices();
        }
        catch (InterruptedException ex)
        {
            Thread.currentThread().interrupt();
        }
        catch ( Exception e )
        {
            log.error("Could not re-register instances after reconnection", e);
        }
    }
}
 
Example #15
Source File: ZooKeeperLeaderElectionService.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
protected void handleStateChange(ConnectionState newState) {
	switch (newState) {
		case CONNECTED:
			LOG.debug("Connected to ZooKeeper quorum. Leader election can start.");
			break;
		case SUSPENDED:
			LOG.warn("Connection to ZooKeeper suspended. The contender " + leaderContender.getAddress()
				+ " no longer participates in the leader election.");
			break;
		case RECONNECTED:
			LOG.info("Connection to ZooKeeper was reconnected. Leader election can be restarted.");
			break;
		case LOST:
			// Maybe we have to throw an exception here to terminate the JobManager
			LOG.warn("Connection to ZooKeeper lost. The contender " + leaderContender.getAddress()
				+ " no longer participates in the leader election.");
			break;
	}
}
 
Example #16
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 #17
Source File: ResyncListener.java    From Baragon with Apache License 2.0 6 votes vote down vote up
@Override
public void stateChanged(CuratorFramework client, ConnectionState newState) {
  switch (newState) {
    case RECONNECTED:
      LOG.info("Reconnected to zookeeper, checking if configs are still in sync");
      Optional<String> maybeLastRequestForGroup = loadBalancerDatastore.getLastRequestForGroup(configuration.getLoadBalancerConfiguration().getName());
      if (!maybeLastRequestForGroup.isPresent() || !maybeLastRequestForGroup.get().equals(mostRecentRequestId.get())) {
        agentState.set(BaragonAgentState.BOOTSTRAPING);
        reapplyConfigsWithRetry();
      }
      agentState.set(BaragonAgentState.ACCEPTING);
      break;
    case SUSPENDED:
    case LOST:
      agentState.set(BaragonAgentState.DISCONNECTED);
      break;
    case CONNECTED:
      agentState.set(BaragonAgentState.ACCEPTING);
      break;
    default:
      break;
  }
}
 
Example #18
Source File: CuratorZookeeperClient.java    From dubbo3 with Apache License 2.0 6 votes vote down vote up
public CuratorZookeeperClient(URL url) {
    super(url);
    try {
        Builder builder = CuratorFrameworkFactory.builder()
                .connectString(url.getBackupAddress())
                .retryPolicy(new RetryNTimes(Integer.MAX_VALUE, 1000))
                .connectionTimeoutMs(5000);
        String authority = url.getAuthority();
        if (authority != null && authority.length() > 0) {
            builder = builder.authorization("digest", authority.getBytes());
        }
        client = builder.build();
        client.getConnectionStateListenable().addListener((client, state) -> {
            if (state == ConnectionState.LOST) {
                CuratorZookeeperClient.this.stateChanged(StateListener.DISCONNECTED);
            } else if (state == ConnectionState.CONNECTED) {
                CuratorZookeeperClient.this.stateChanged(StateListener.CONNECTED);
            } else if (state == ConnectionState.RECONNECTED) {
                CuratorZookeeperClient.this.stateChanged(StateListener.RECONNECTED);
            }
        });
        client.start();
    } catch (Exception e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}
 
Example #19
Source File: ZooKeeperCheckpointIDCounter.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
@Override
public long getAndIncrement() throws Exception {
	while (true) {
		ConnectionState connState = connStateListener.getLastState();

		if (connState != null) {
			throw new IllegalStateException("Connection state: " + connState);
		}

		VersionedValue<Integer> current = sharedCount.getVersionedValue();
		int newCount = current.getValue() + 1;

		if (newCount < 0) {
			// overflow and wrap around
			throw new Exception("Checkpoint counter overflow. ZooKeeper checkpoint counter only supports " +
					"checkpoints Ids up to " + Integer.MAX_VALUE);
		}

		if (sharedCount.trySetCount(current, newCount)) {
			return current.getValue();
		}
	}
}
 
Example #20
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 #21
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 #22
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 #23
Source File: ZooKeeperUpdatingPersistentDirectory.java    From helios with Apache License 2.0 6 votes vote down vote up
@Override
public void stateChanged(final CuratorFramework client, final ConnectionState newState) {
  switch (newState) {
    case CONNECTED:
      break;
    case SUSPENDED:
      break;
    case RECONNECTED:
      initialized = false;
      reactor.signal();
      break;
    case LOST:
    case READ_ONLY:
    default:
      break;
  }
}
 
Example #24
Source File: CuratorFrameworkImpl.java    From curator with Apache License 2.0 6 votes vote down vote up
void validateConnection(Watcher.Event.KeeperState state)
{
    if ( state == Watcher.Event.KeeperState.Disconnected )
    {
        internalConnectionHandler.suspendConnection(this);
    }
    else if ( state == Watcher.Event.KeeperState.Expired )
    {
        connectionStateManager.addStateChange(ConnectionState.LOST);
    }
    else if ( state == Watcher.Event.KeeperState.SyncConnected )
    {
        internalConnectionHandler.checkNewConnection(this);
        connectionStateManager.addStateChange(ConnectionState.RECONNECTED);
        unSleepBackgroundOperations();
    }
    else if ( state == Watcher.Event.KeeperState.ConnectedReadOnly )
    {
        internalConnectionHandler.checkNewConnection(this);
        connectionStateManager.addStateChange(ConnectionState.READ_ONLY);
    }
}
 
Example #25
Source File: PersistentPathChildrenCache.java    From helios with Apache License 2.0 5 votes vote down vote up
private void fireConnectionStateChanged(final ConnectionState state) {
  for (final Listener listener : listeners) {
    try {
      listener.connectionStateChanged(state);
    } catch (Exception e) {
      log.error("Listener threw exception", e);
    }
  }
}
 
Example #26
Source File: ZooKeeperMetricsImpl.java    From helios with Apache License 2.0 5 votes vote down vote up
public ZooKeeperMetricsImpl(final String group, final MetricRegistry registry) {
  this.prefix = MetricRegistry.name(group, TYPE) + ".";
  this.registry = registry;
  this.transientErrorMeter = registry.meter(prefix + "transient_error_meter");
  this.connectionStateChanged = registry.meter(prefix + "connection_state_changed");

  // create all of the meter instances immediately so that we report 0 values after a restart
  for (final ConnectionState state : ConnectionState.values()) {
    connectionStateMeter(state);
  }
}
 
Example #27
Source File: SharedValue.java    From xian with Apache License 2.0 5 votes vote down vote up
private void notifyListenerOfStateChanged(final ConnectionState newState)
{
    listeners.forEach
        (
            new Function<SharedValueListener, Void>()
            {
                @Override
                public Void apply(SharedValueListener listener)
                {
                    listener.stateChanged(client, newState);
                    return null;
                }
            }
        );
}
 
Example #28
Source File: LeaderSelectorListenerAdapter.java    From xian with Apache License 2.0 5 votes vote down vote up
@Override
public void stateChanged(CuratorFramework client, ConnectionState newState)
{
    if ( (newState == ConnectionState.SUSPENDED) || (newState == ConnectionState.LOST) )
    {
        throw new CancelLeadershipException();
    }
}
 
Example #29
Source File: StateKeeper.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
@Override public void stateChanged(CuratorFramework client, ConnectionState newState) {
    log.warn("state changed, state:{}", newState);
    if (ConnectionState.CONNECTED == newState || ConnectionState.RECONNECTED == newState) {
        log.warn("session change:{}, register again", newState);
        registerAll();
    }
}
 
Example #30
Source File: DistributedSequenceHandler.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void stateChanged(CuratorFramework client, ConnectionState newState) {
    if (newState == ConnectionState.SUSPENDED || newState == ConnectionState.LOST) {
        this.isLeader = false;
        leaderExecutor.shutdownNow();
        throw new CancelLeadershipException();
    }
}