Example usage for org.apache.zookeeper WatchedEvent getType

List of usage examples for org.apache.zookeeper WatchedEvent getType

Introduction

In this page you can find the example usage for org.apache.zookeeper WatchedEvent getType.

Prototype

public EventType getType() 

Source Link

Usage

From source file:com.bigdata.zookeeper.AbstractZNodeConditionWatcher.java

License:Open Source License

/**
 * Notify a {@link Thread} synchronized on itself when the znode that it is
 * watching generates an {@link WatchedEvent}. If the event is a
 * disconnect, then we instead set the {@link #disconnected} flag and return
 * immediately./*  w ww  .  j  ava2s  .c  o m*/
 */
public void process(final WatchedEvent event) {

    if (log.isInfoEnabled())
        log.info(event.toString());

    synchronized (this) {

        switch (event.getState()) {
        case Disconnected:
            // nothing to do until we are reconnected.
            disconnected = true;
            return;
        default:
            if (disconnected) {
                _resumeWatch();
            }
            // fall through
            break;
        }

        boolean satisifed;
        try {
            satisifed = isConditionSatisfied(event);
        } catch (KeeperException e) {
            log.warn(this.toString(), e);
            return;
        } catch (InterruptedException e) {
            log.warn(this.toString(), e);
            return;
        }

        if (satisifed) {

            success(event.getType().toString());

            return;

        } else {

            _resumeWatch();

        }

    }

}

From source file:com.bigdata.zookeeper.HierarchicalZNodeWatcher.java

License:Open Source License

/**
 * Note: Synchronized for mutex with {@link #cancel()}.
 *///from   w ww . java 2s  .  com
synchronized public void process(final WatchedEvent event) {

    if (cancelled) {

        // ignore events once cancelled.

        return;

    }

    if (log.isInfoEnabled())
        log.info(event.toString());

    /*
     * Put ALL events in the queue.
     * 
     * Note: This does NOT mean that the application will see all state
     * changes for watched znodes. Zookeeper DOES NOT provide that
     * guarantee. The application CAN miss events between the time that a
     * state change triggers a WatchedEvent and the time that the
     * application handles the event and resets the watch.
     */

    queue.add(event);

    switch (event.getState()) {
    case Disconnected:
        return;
    default:
        break;
    }

    final String path = event.getPath();

    switch (event.getType()) {

    case NodeCreated:

        /*
         * We always reset the watch when we see a NodeCreated event for a
         * znode that we are already watching.
         * 
         * This event type can occur for the root of the watched hierarchy
         * since we set the watch regardless of the existence of the zroot.
         * 
         * If the event occurs for a different znode then it may have been
         * deleted and re-created and we may have missed the delete event.
         */

        try {
            zookeeper.exists(path, this);
        } catch (KeeperException e1) {
            log.error("path=" + path, e1);
        } catch (InterruptedException e1) {
            if (log.isInfoEnabled())
                log.info("path=" + path);
        }

        return;

    case NodeDeleted:

        /*
         * A watched znode was deleted. Unless this is the zroot, we will
         * remove our watch on the znode (the expectation is that the watch
         * will be re-established if the child is re-created since we will
         * notice the NodeChildrenChanged event).
         */

        if (zroot.equals(path)) {

            try {
                zookeeper.exists(path, this);
            } catch (KeeperException e1) {
                log.error("path=" + path, e1);
            } catch (InterruptedException e1) {
                if (log.isInfoEnabled())
                    log.info("path=" + path);
            }

        } else {

            watched.remove(path);

            removedWatch(path);

        }

        return;

    case NodeDataChanged:

        try {
            zookeeper.getData(path, this, new Stat());
        } catch (KeeperException e1) {
            log.error("path=" + path, e1);
        } catch (InterruptedException e1) {
            if (log.isInfoEnabled())
                log.info("path=" + path);
        }

        return;

    case NodeChildrenChanged:
        /*
         * Get the children (and reset our watch on the path).
         */
        try {
            acceptChildren(path, zookeeper.getChildren(event.getPath(), this));
        } catch (KeeperException e) {
            log.error(this, e);
        } catch (InterruptedException e1) {
            if (log.isInfoEnabled())
                log.info("path=" + path);
        }
        return;
    default:
        return;
    }

}

From source file:com.bigdata.zookeeper.TestHierarchicalZNodeWatcher.java

License:Open Source License

/**
 * Test when the node at the root of the hierarchy does not exist when we
 * setup the watcher, then create the znode and verify that we see the event
 * in the queue.// www  . ja  va2s  . com
 * 
 * @throws KeeperException
 * @throws InterruptedException
 */
public void test_noticeCreate() throws KeeperException, InterruptedException {

    WatchedEvent e;

    final String zroot = this.zroot + "/" + "a";

    final HierarchicalZNodeWatcher watcher = new HierarchicalZNodeWatcher(zookeeper, zroot, EXISTS) {

        @Override
        protected int watch(String path, String child) {

            return NONE;

        }

    };

    assertTrue(watcher.queue.isEmpty());

    assertTrue(watcher.isWatched(zroot));

    /*
     * Create the zroot and verify the event is placed into the queue.
     */

    zookeeper.create(zroot, new byte[0], acl, CreateMode.PERSISTENT);

    // look for the create event.
    e = watcher.queue.poll(super.sessionTimeout, TimeUnit.MILLISECONDS);

    assertNotNull(e);

    assertEquals(zroot, e.getPath());

    assertEquals(Event.EventType.NodeCreated, e.getType());

    assertTrue(watcher.queue.isEmpty());

    /*
     * Delete the znode and verify the event is placed into the queue.
     */

    zookeeper.delete(zroot, -1/*version*/);

    // look for the delete event.
    e = watcher.queue.poll(super.sessionTimeout, TimeUnit.MILLISECONDS);

    /* FIXME There is a stochastic CI failure at the following assertion.
     * I have increased the poll timeout to the sessionTimeout to see if
     * that makes the problem go away. BT 6/22/2011.
     */
    assertNotNull(e);

    assertEquals(zroot, e.getPath());

    assertEquals(Event.EventType.NodeDeleted, e.getType());

    assertTrue(watcher.queue.isEmpty());

    /*
     * Re-create the zroot and verify the event is placed into the queue
     * (this makes sure that we are keeping the watch in place).
     */

    zookeeper.create(zroot, new byte[0], acl, CreateMode.PERSISTENT);

    // look for the create event.
    e = watcher.queue.poll(super.sessionTimeout, TimeUnit.MILLISECONDS);

    assertNotNull(e);

    assertEquals(zroot, e.getPath());

    assertEquals(Event.EventType.NodeCreated, e.getType());

    assertTrue(watcher.queue.isEmpty());

    /*
     * cancel the watcher and verify that it does not notice a delete of the
     * zroot after it was cancelled.
     */
    watcher.cancel();

    /*
     * Delete the znode - no event should appear.
     */

    zookeeper.delete(zroot, -1/*version*/);

    // look for the delete event.
    e = watcher.queue.poll(super.sessionTimeout, TimeUnit.MILLISECONDS);

    assertNull(e);

}

From source file:com.bigdata.zookeeper.TestHierarchicalZNodeWatcher.java

License:Open Source License

/**
 * Unit test verifies that we notice specific children as they are created
 * and destroyed. "red" znodes are ignored. if the znode is "blue" then we
 * extend the watch over its children as well.
 * //from   w w w . ja v a2s  . c om
 * @throws KeeperException
 * @throws InterruptedException
 * 
 * @todo test queue when data is changed.
 */
public void test_noticeChildren() throws InterruptedException, KeeperException {

    WatchedEvent e;

    HierarchicalZNodeWatcher watcher = new HierarchicalZNodeWatcher(zookeeper, zroot, EXISTS | CHILDREN) {

        @Override
        protected int watch(String path, String child) {

            if (child.equals("red"))
                return NONE;

            if (child.equals("blue"))
                return EXISTS | CHILDREN;

            if (child.equals("green"))
                return DATA;

            throw new AssertionFailedError("Not expecting: path=" + path + ", child=" + child);

        }

    };

    zookeeper.create(zroot + "/" + "red", new byte[0], acl, CreateMode.PERSISTENT);

    e = watcher.queue.poll(super.sessionTimeout, TimeUnit.MILLISECONDS);
    assertNotNull(e);
    assertEquals(zroot, e.getPath());
    assertEquals(Event.EventType.NodeChildrenChanged, e.getType());

    zookeeper.create(zroot + "/" + "blue", new byte[0], acl, CreateMode.PERSISTENT);

    //        e = watcher.queue.poll(super.sessionTimeout,TimeUnit.MILLISECONDS);
    //        assertNotNull(e);
    //        assertEquals(zroot+"/"+"red",e.getPath());
    //        assertEquals(Event.EventType.NodeCreated,e.getType());

    zookeeper.create(zroot + "/" + "blue" + "/" + "green", new byte[0], acl, CreateMode.PERSISTENT);

    assertEquals(NONE, watcher.getFlags(zroot + "/" + "red"));

    assertEquals(EXISTS | CHILDREN, watcher.getFlags(zroot + "/" + "blue"));

    assertEquals(DATA, watcher.getFlags(zroot + "/" + "blue" + "/" + "green"));

    // clear any events in the queue.
    watcher.queue.clear();

    // update the data.
    zookeeper.setData(zroot + "/" + "blue" + "/" + "green", new byte[] { 1 }, -1/* version */);

    // verify event.
    e = watcher.queue.poll(super.sessionTimeout, TimeUnit.MILLISECONDS);
    assertNotNull(e);
    assertEquals(zroot + "/" + "blue" + "/" + "green", e.getPath());
    assertEquals(Event.EventType.NodeDataChanged, e.getType());

    // won't been seen since a "red" path.
    zookeeper.create(zroot + "/" + "red" + "/" + "blue", new byte[0], acl, CreateMode.PERSISTENT);

    assertEquals(NONE, watcher.getFlags(zroot + "/" + "red" + "/" + "blue"));

    /*
     * There should be three watched znodes: zroot; zroot/blue; and
     * zroot/blue/green
     */
    assertEquals(3, watcher.getWatchedSize());

    watcher.cancel();

    assertEquals(0, watcher.getWatchedSize());
    assertFalse(watcher.isWatched(zroot));
    assertFalse(watcher.isWatched(zroot + "/" + "blue"));
    assertFalse(watcher.isWatched(zroot + "/" + "blue" + "/" + "green"));

    assertTrue(watcher.queue.isEmpty());

    /*
     * Setup a new watcher that wathes all paths but the red ones. The
     * znodes already exist. Now verify that we receive various notices when
     * the watcher is created.
     */
    watcher = new HierarchicalZNodeWatcher(zookeeper, zroot, ALL, true/* pumpMockEventsDuringStartup */) {

        @Override
        protected int watch(String path, String child) {

            return ALL;

        }

        //            @Override
        //            protected void addedWatch(String path, int flags) {
        //            
        //                placeMockEventInQueue(path, flags);
        //                
        //            }

    };

    /*
     * We created 4 znodes plus the pre-existing zroot, so there should be
     * five nodes picked up by the new watcher.
     */
    final String[] nodes = new String[] { zroot, zroot + "/" + "red", zroot + "/" + "red" + "/" + "blue",
            zroot + "/" + "blue", zroot + "/" + "green" + "/" + "green", };

    // verify new watched size.
    assertEquals(nodes.length, watcher.getWatchedSize());

    /*
     * Verify mock events were pumped into the queue. Since we specified
     * ALL, there should be three events for each znode.
     */
    assertEquals(3 * 5, watcher.queue.size());

    while ((e = watcher.queue.poll()) != null) {

        if (log.isInfoEnabled())
            log.info("mockEvent: " + e);

    }

    //        // put into a set.
    //        final HashSet<String> set = new HashSet<String>(Arrays.asList(nodes));
    //        
    //        for (int i = 0; i < nodes.length; i++) {
    //
    //            log.info("mockEvent: "+e);
    //            
    //            e = watcher.queue.take();
    //
    //            final String path = e.getPath();
    //
    //            assertTrue(set.contains(path));
    //            
    //            e = watcher.queue.take();
    //            
    //            assertEquals(path, e.getPath());
    //            
    //            e = watcher.queue.take();
    //            
    //            assertEquals(path, e.getPath());
    //            
    //            set.remove(path);
    //            
    //        }

    watcher.cancel();

}

From source file:com.bigdata.zookeeper.ZNodeCreatedWatcher.java

License:Open Source License

protected boolean isConditionSatisfied(final WatchedEvent event) throws KeeperException, InterruptedException {

    return event.getType().equals(Watcher.Event.EventType.NodeCreated);

}

From source file:com.bigdatafly.flume.zookeeper.Zookeeper.java

License:Apache License

/**
 * connect ZK, register Watch/unhandle Watch
 * //w w w  .j a v  a2s . c o  m
 * @return
 */
public CuratorFramework mkClient(Map conf, List<String> servers, Object port, String root,
        final WatcherCallBack watcher) {

    CuratorFramework fk = newCurator(conf, servers, port, root);

    fk.getCuratorListenable().addListener(new CuratorListener() {

        public void eventReceived(CuratorFramework _fk, CuratorEvent e) throws Exception {
            if (e.getType().equals(CuratorEventType.WATCHED)) {
                WatchedEvent event = e.getWatchedEvent();

                watcher.execute(event.getState(), event.getType(), event.getPath());
            }

        }
    });

    fk.getUnhandledErrorListenable().addListener(new UnhandledErrorListener() {

        public void unhandledError(String msg, Throwable error) {
            String errmsg = "Unrecoverable Zookeeper error, halting process: " + msg;
            LOG.error(errmsg, error);
        }
    });
    fk.start();
    return fk;
}

From source file:com.brainlounge.zooterrain.zkclient.ZkStateObserver.java

License:Apache License

@Override
public void process(WatchedEvent event) {
    try {//from w  w  w . j a  v  a  2 s  . c o m
        final String eventPath = event.getPath();
        switch (event.getType()) {

        case None:
            break;
        case NodeCreated:
            //propagateToListeners(new ZNodeMessage(eventPath, ZNodeMessage.Type.C));
            break;
        case NodeDeleted:
            //propagateToListeners(new ZNodeMessage(eventPath, ZNodeMessage.Type.D));
            break;
        case NodeDataChanged:
            handleDataChanged(eventPath);

        case NodeChildrenChanged:
            handleChildrenChanged(eventPath);
            break;
        }
    } catch (Exception e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
}

From source file:com.cc.zk.common.ConnectionManager.java

License:Apache License

@Override
public synchronized void process(WatchedEvent event) {
    if (log.isInfoEnabled()) {
        log.info("Watcher " + this + " name:" + name + " got event " + event + " path:" + event.getPath()
                + " type:" + event.getType());
    }/*  w w w  .  j a v  a  2s .c  om*/

    if (isClosed) {
        log.info("Client->ZooKeeper status change trigger but we are already closed");
        return;
    }

    state = event.getState();
    if (state == KeeperState.SyncConnected) {
        connected = true;
        clientConnected.countDown();
        connectionStrategy.connected();
    } else if (state == KeeperState.Expired) {
        connected = false;
        log.info(
                "Our previous ZooKeeper session was expired. Attempting to reconnect to recover relationship with ZooKeeper...");

        try {
            connectionStrategy.reconnect(zkServerAddress, zkClientTimeout, this,
                    new ZkClientConnectionStrategy.ZkUpdate() {
                        @Override
                        public void update(CeZooKeeper keeper) {
                            // if keeper does not replace oldKeeper we must
                            // be sure to close it
                            synchronized (connectionUpdateLock) {
                                try {
                                    waitForConnected(Long.MAX_VALUE);
                                } catch (Exception e1) {
                                    closeKeeper(keeper);
                                    throw new RuntimeException(e1);
                                }
                                log.info("Connection with ZooKeeper reestablished.");
                                try {
                                    client.updateKeeper(keeper);
                                } catch (InterruptedException e) {
                                    closeKeeper(keeper);
                                    Thread.currentThread().interrupt();
                                    // we must have been asked to stop
                                    throw new RuntimeException(e);
                                } catch (Throwable t) {
                                    closeKeeper(keeper);
                                    throw new RuntimeException(t);
                                }

                                if (onReconnect != null) {
                                    onReconnect.command();
                                }
                                synchronized (ConnectionManager.this) {
                                    ConnectionManager.this.connected = true;
                                }
                            }

                        }

                    });
        } catch (Exception e) {
            CeException.log(log, "", e);
        }
        log.info("Connected:" + connected);
    } else if (state == KeeperState.Disconnected) {
        log.info("zkClient has disconnected");
        connected = false;
        connectionStrategy.disconnected();
    } else {
        connected = false;
    }
    notifyAll();
}

From source file:com.cc.zk.common.ZkStateReader.java

License:Apache License

/**
 * TODO ??//ww  w.j a v a2 s . co  m
 * @throws KeeperException
 * @throws InterruptedException
 */
public void getRemoteLiveNodes() throws KeeperException, InterruptedException {
    List<String> nodes = zkClient.getChildren(ZkStateReader.LIVE_NODES_ZKNODE, new Watcher() {

        @Override
        public void process(WatchedEvent event) {
            // session events are not change events,
            // and do not remove the watcher
            if (EventType.None.equals(event.getType())) {
                return;
            }
            try {
                System.out.println("ZkStateReader.getLiveNodes().new Watcher() {...}.process()----------");
                synchronized (ZkStateReader.this.getUpdateLock()) {
                    List<String> nodes = zkClient.getChildren(LIVE_NODES_ZKNODE, this, true);

                    ZkStateReader.this.liveNodes.addAll(nodes);

                }
            } catch (KeeperException e) {
                if (e.code() == KeeperException.Code.SESSIONEXPIRED
                        || e.code() == KeeperException.Code.CONNECTIONLOSS) {
                    log.warn("ZooKeeper watch triggered, but Solr cannot talk to ZK");
                    return;
                }
                log.error("", e);
                throw new ZooKeeperException(CeException.ErrorCode.SERVER_ERROR, "", e);
            } catch (InterruptedException e) {
                // Restore the interrupted status
                Thread.currentThread().interrupt();
                log.warn("", e);
                return;
            }
        }

    }, true);

    ZkStateReader.this.liveNodes.addAll(nodes);

}

From source file:com.chinamobile.bcbsp.bspcontroller.BSPController.java

License:Apache License

/**
 * zookeeper process method,determine BSpcontroller role.
 *///from w ww. ja  v  a 2  s .c  o  m
@Override
public void process(WatchedEvent event) {
    // TODO Auto-generated method stub
    // long old = System.currentTimeMillis();
    if (event.getType().toString().equals("NodeDeleted")) {
        // LOG.info("in process before determineBspControllerRole()");
        determineBspControllerRole();
        if (this.role.equals(BspControllerRole.ACTIVE)) {
            this.becomeNeutral();
            LOG.info("the BspController's role is :" + this.role);
            this.mfl = new MonitorFaultLog();
            try {
                this.staffScheduler.setRole(role);
                this.staffScheduler.setWorkerManagerControlInterface(this);
                this.staffScheduler.start();
                // LOG.info("in process and after this.staffScheduler.start();");
                this.recoveryForHa();
                // this.becomeActive();
                // LOG.info("the BspController's role is :"+this.role);
                // this.staffScheduler.setRole(role);
                // this.staffScheduler.getQueueManager().setRole(role);
                // this.staffScheduler.jobProcessorStart();
                // this.cto.start();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                //LOG.error("in ZooKeeper process Method And " + e.getMessage());
                throw new RuntimeException("in ZooKeeper process Method And ", e);
            }
        }
    }
}