use of org.apache.zookeeper.WatchedEvent in project curator by Netflix.
the class CuratorZKClientBridge method connect.
@Override
public void connect(final Watcher watcher) {
if (watcher != null) {
CuratorListener localListener = new CuratorListener() {
@Override
public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
if (event.getWatchedEvent() != null) {
watcher.process(event.getWatchedEvent());
}
}
};
curator.getCuratorListenable().addListener(localListener);
listener.set(localListener);
try {
BackgroundCallback callback = new BackgroundCallback() {
@Override
public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
WatchedEvent fakeEvent = new WatchedEvent(Watcher.Event.EventType.None, curator.getZookeeperClient().isConnected() ? Watcher.Event.KeeperState.SyncConnected : Watcher.Event.KeeperState.Disconnected, null);
watcher.process(fakeEvent);
}
};
curator.checkExists().inBackground(callback).forPath("/foo");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
use of org.apache.zookeeper.WatchedEvent in project pinpoint by naver.
the class ZookeeperClusterService method setUp.
@PostConstruct
@Override
public void setUp() throws KeeperException, IOException, InterruptedException {
if (!config.isClusterEnable()) {
logger.info("pinpoint-collector cluster disable.");
return;
}
switch(this.serviceState.getCurrentState()) {
case NEW:
if (this.serviceState.changeStateInitializing()) {
logger.info("{} initialization started.", this.getClass().getSimpleName());
ClusterManagerWatcher watcher = new ClusterManagerWatcher();
this.client = new DefaultZookeeperClient(config.getClusterAddress(), config.getClusterSessionTimeout(), watcher);
this.client.connect();
this.profilerClusterManager = new ZookeeperProfilerClusterManager(client, serverIdentifier, clusterPointRouter.getTargetClusterPointRepository());
this.profilerClusterManager.start();
this.webClusterManager = new ZookeeperWebClusterManager(client, PINPOINT_WEB_CLUSTER_PATH, serverIdentifier, clusterConnectionManager);
this.webClusterManager.start();
this.serviceState.changeStateStarted();
logger.info("{} initialization completed.", this.getClass().getSimpleName());
if (client.isConnected()) {
WatcherEvent watcherEvent = new WatcherEvent(EventType.None.getIntValue(), KeeperState.SyncConnected.getIntValue(), "");
WatchedEvent event = new WatchedEvent(watcherEvent);
watcher.process(event);
}
}
break;
case INITIALIZING:
logger.info("{} already initializing.", this.getClass().getSimpleName());
break;
case STARTED:
logger.info("{} already started.", this.getClass().getSimpleName());
break;
case DESTROYING:
throw new IllegalStateException("Already destroying.");
case STOPPED:
throw new IllegalStateException("Already stopped.");
case ILLEGAL_STATE:
throw new IllegalStateException("Invalid State.");
}
}
use of org.apache.zookeeper.WatchedEvent in project druid by druid-io.
the class LoadQueuePeon method processSegmentChangeRequest.
private void processSegmentChangeRequest() {
if (currentlyProcessing == null) {
if (!segmentsToDrop.isEmpty()) {
currentlyProcessing = segmentsToDrop.firstEntry().getValue();
log.info("Server[%s] dropping [%s]", basePath, currentlyProcessing.getSegmentIdentifier());
} else if (!segmentsToLoad.isEmpty()) {
currentlyProcessing = segmentsToLoad.firstEntry().getValue();
log.info("Server[%s] loading [%s]", basePath, currentlyProcessing.getSegmentIdentifier());
} else {
return;
}
try {
if (currentlyProcessing == null) {
if (!stopped) {
log.makeAlert("Crazy race condition! server[%s]", basePath).emit();
}
actionCompleted();
return;
}
log.info("Server[%s] processing segment[%s]", basePath, currentlyProcessing.getSegmentIdentifier());
final String path = ZKPaths.makePath(basePath, currentlyProcessing.getSegmentIdentifier());
final byte[] payload = jsonMapper.writeValueAsBytes(currentlyProcessing.getChangeRequest());
curator.create().withMode(CreateMode.EPHEMERAL).forPath(path, payload);
processingExecutor.schedule(new Runnable() {
@Override
public void run() {
try {
if (curator.checkExists().forPath(path) != null) {
failAssign(new ISE("%s was never removed! Failing this operation!", path));
}
} catch (Exception e) {
failAssign(e);
}
}
}, config.getLoadTimeoutDelay().getMillis(), TimeUnit.MILLISECONDS);
final Stat stat = curator.checkExists().usingWatcher(new CuratorWatcher() {
@Override
public void process(WatchedEvent watchedEvent) throws Exception {
switch(watchedEvent.getType()) {
case NodeDeleted:
entryRemoved(watchedEvent.getPath());
}
}
}).forPath(path);
if (stat == null) {
final byte[] noopPayload = jsonMapper.writeValueAsBytes(new SegmentChangeRequestNoop());
// Create a node and then delete it to remove the registered watcher. This is a work-around for
// a zookeeper race condition. Specifically, when you set a watcher, it fires on the next event
// that happens for that node. If no events happen, the watcher stays registered foreverz.
// Couple that with the fact that you cannot set a watcher when you create a node, but what we
// want is to create a node and then watch for it to get deleted. The solution is that you *can*
// set a watcher when you check to see if it exists so, we first create the node and then set a
// watcher on its existence. However, if already does not exist by the time the existence check
// returns, then the watcher that was set will never fire (nobody will ever create the node
// again) and thus lead to a slow, but real, memory leak. So, we create another node to cause
// that watcher to fire and delete it right away.
//
// We do not create the existence watcher first, because then it will fire when we create the
// node and we'll have the same race when trying to refresh that watcher.
curator.create().withMode(CreateMode.EPHEMERAL).forPath(path, noopPayload);
entryRemoved(path);
}
} catch (Exception e) {
failAssign(e);
}
} else {
log.info("Server[%s] skipping doNext() because something is currently loading[%s].", basePath, currentlyProcessing.getSegmentIdentifier());
}
}
use of org.apache.zookeeper.WatchedEvent in project weave by continuuity.
the class AbstractZKServiceController method actOnExists.
private void actOnExists(final String path, final Runnable action) {
// Watch for node existence.
final AtomicBoolean nodeExists = new AtomicBoolean(false);
Futures.addCallback(zkClient.exists(path, new Watcher() {
@Override
public void process(WatchedEvent event) {
// Other event type would be handled by the action.
if (event.getType() == Event.EventType.NodeCreated && nodeExists.compareAndSet(false, true)) {
action.run();
}
}
}), new FutureCallback<Stat>() {
@Override
public void onSuccess(Stat result) {
if (result != null && nodeExists.compareAndSet(false, true)) {
action.run();
}
}
@Override
public void onFailure(Throwable t) {
LOG.error("Failed in exists call to {}. Shutting down service.", path, t);
forceShutDown();
}
}, Threads.SAME_THREAD_EXECUTOR);
}
use of org.apache.zookeeper.WatchedEvent in project yyl_example by Relucent.
the class Test1 method main.
public static void main(String[] args) throws Exception {
ZooKeeper zk = new ZooKeeper("localhost:2181", 1000, new Watcher() {
// 监控所有被触发的事件
public void process(WatchedEvent event) {
System.out.println("已经触发了" + event.getType() + "事件!");
}
});
// 创建一个目录节点
zk.create("/testRootPath", "testRootData".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// 创建一个子目录节点
zk.create("/testRootPath/testChildPathOne", "testChildDataOne".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println(new String(zk.getData("/testRootPath", false, null)));
// 取出子目录节点列表
System.out.println(zk.getChildren("/testRootPath", true));
// 修改子目录节点数据
zk.setData("/testRootPath/testChildPathOne", "modifyChildDataOne".getBytes(), -1);
System.out.println("目录节点状态:[" + zk.exists("/testRootPath", true) + "]");
// 创建另外一个子目录节点
zk.create("/testRootPath/testChildPathTwo", "testChildDataTwo".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println(new String(zk.getData("/testRootPath/testChildPathTwo", true, null)));
// 删除子目录节点
zk.delete("/testRootPath/testChildPathTwo", -1);
zk.delete("/testRootPath/testChildPathOne", -1);
// 删除父目录节点
zk.delete("/testRootPath", -1);
// 关闭连接
zk.close();
}
Aggregations