Example usage for org.apache.zookeeper WatchedEvent getState

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

Introduction

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

Prototype

public KeeperState getState() 

Source Link

Usage

From source file:org.apache.hadoop.contrib.bkjournal.TestBookKeeperConfiguration.java

License:Apache License

private static ZooKeeper connectZooKeeper(String ensemble)
        throws IOException, KeeperException, InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);

    ZooKeeper zkc = new ZooKeeper(HOSTPORT, ZK_SESSION_TIMEOUT, new Watcher() {
        public void process(WatchedEvent event) {
            if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
                latch.countDown();/*  w  ww. j  a va  2  s  .  c  o m*/
            }
        }
    });
    if (!latch.await(ZK_SESSION_TIMEOUT, TimeUnit.MILLISECONDS)) {
        throw new IOException("Zookeeper took too long to connect");
    }
    return zkc;
}

From source file:org.apache.hadoop.contrib.bkjournal.TestCurrentInprogress.java

License:Apache License

private static ZooKeeper connectZooKeeper(String ensemble)
        throws IOException, KeeperException, InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);

    ZooKeeper zkc = new ZooKeeper(HOSTPORT, 3600, new Watcher() {
        public void process(WatchedEvent event) {
            if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
                latch.countDown();//  w  ww.j ava2 s .  c o  m
            }
        }
    });
    if (!latch.await(10, TimeUnit.SECONDS)) {
        throw new IOException("Zookeeper took too long to connect");
    }
    return zkc;
}

From source file:org.apache.hadoop.contrib.bkjournal.WriteLock.java

License:Apache License

public void process(WatchedEvent event) {
    if (event.getState() == KeeperState.Disconnected || event.getState() == KeeperState.Expired) {
        LOG.warn("Lost zookeeper session, lost lock ");
        lockCount.set(0);/* w  w  w. j a  v  a 2s .  com*/
    } else {
        // reapply the watch
        synchronized (this) {
            LOG.info("Zookeeper event " + event + " received, reapplying watch to " + myznode);
            if (myznode != null) {
                try {
                    zkc.exists(myznode, this);
                } catch (Exception e) {
                    LOG.warn("Could not set watch on lock, releasing", e);
                    try {
                        release();
                    } catch (IOException ioe) {
                        LOG.error("Could not release Zk lock", ioe);
                    }
                }
            }
        }
    }
}

From source file:org.apache.hadoop.ha.ActiveStandbyElector.java

License:Apache License

/**
 * interface implementation of Zookeeper watch events (connection and node),
 * proxied by {@link WatcherWithClientRef}.
 */// ww  w .  j a va2 s. co m
synchronized void processWatchEvent(ZooKeeper zk, WatchedEvent event) {
    Event.EventType eventType = event.getType();
    if (isStaleClient(zk))
        return;
    LOG.debug("Watcher event type: " + eventType + " with state:" + event.getState() + " for path:"
            + event.getPath() + " connectionState: " + zkConnectionState + " for " + this);

    if (eventType == Event.EventType.None) {
        // the connection state has changed
        switch (event.getState()) {
        case SyncConnected:
            LOG.info("Session connected.");
            // if the listener was asked to move to safe state then it needs to
            // be undone
            ConnectionState prevConnectionState = zkConnectionState;
            zkConnectionState = ConnectionState.CONNECTED;
            if (prevConnectionState == ConnectionState.DISCONNECTED && wantToBeInElection) {
                monitorActiveStatus();
            }
            break;
        case Disconnected:
            LOG.info("Session disconnected. Entering neutral mode...");

            // ask the app to move to safe state because zookeeper connection
            // is not active and we dont know our state
            zkConnectionState = ConnectionState.DISCONNECTED;
            enterNeutralMode();
            break;
        case Expired:
            // the connection got terminated because of session timeout
            // call listener to reconnect
            LOG.info("Session expired. Entering neutral mode and rejoining...");
            enterNeutralMode();
            reJoinElection(0);
            break;
        case SaslAuthenticated:
            LOG.info("Successfully authenticated to ZooKeeper using SASL.");
            break;
        default:
            fatalError("Unexpected Zookeeper watch event state: " + event.getState());
            break;
        }

        return;
    }

    // a watch on lock path in zookeeper has fired. so something has changed on
    // the lock. ideally we should check that the path is the same as the lock
    // path but trusting zookeeper for now
    String path = event.getPath();
    if (path != null) {
        switch (eventType) {
        case NodeDeleted:
            if (state == State.ACTIVE) {
                enterNeutralMode();
            }
            joinElectionInternal();
            break;
        case NodeDataChanged:
            monitorActiveStatus();
            break;
        default:
            LOG.debug("Unexpected node event: " + eventType + " for path: " + path);
            monitorActiveStatus();
        }

        return;
    }

    // some unexpected error has occurred
    fatalError("Unexpected watch error from Zookeeper");
}

From source file:org.apache.hadoop.ha.TestActiveStandbyElector.java

License:Apache License

/**
 * verify behavior of watcher.process callback with non-node event
 *///from   w  w  w. ja  v a2  s . c  om
@Test
public void testProcessCallbackEventNone() throws Exception {
    mockNoPriorActive();
    elector.joinElection(data);

    WatchedEvent mockEvent = Mockito.mock(WatchedEvent.class);
    Mockito.when(mockEvent.getType()).thenReturn(Event.EventType.None);

    // first SyncConnected should not do anything
    Mockito.when(mockEvent.getState()).thenReturn(Event.KeeperState.SyncConnected);
    elector.processWatchEvent(mockZK, mockEvent);
    Mockito.verify(mockZK, Mockito.times(0)).exists(Mockito.anyString(), Mockito.anyBoolean(),
            Mockito.<AsyncCallback.StatCallback>anyObject(), Mockito.<Object>anyObject());

    // disconnection should enter safe mode
    Mockito.when(mockEvent.getState()).thenReturn(Event.KeeperState.Disconnected);
    elector.processWatchEvent(mockZK, mockEvent);
    Mockito.verify(mockApp, Mockito.times(1)).enterNeutralMode();

    // re-connection should monitor master status
    Mockito.when(mockEvent.getState()).thenReturn(Event.KeeperState.SyncConnected);
    elector.processWatchEvent(mockZK, mockEvent);
    verifyExistCall(1);

    // session expired should enter safe mode and initiate re-election
    // re-election checked via checking re-creation of new zookeeper and
    // call to create lock znode
    Mockito.when(mockEvent.getState()).thenReturn(Event.KeeperState.Expired);
    elector.processWatchEvent(mockZK, mockEvent);
    // already in safe mode above. should not enter safe mode again
    Mockito.verify(mockApp, Mockito.times(1)).enterNeutralMode();
    // called getNewZooKeeper to create new session. first call was in
    // constructor
    Assert.assertEquals(2, count);
    // once in initial joinElection and one now
    Mockito.verify(mockZK, Mockito.times(2)).create(ZK_LOCK_NAME, data, Ids.OPEN_ACL_UNSAFE,
            CreateMode.EPHEMERAL, elector, mockZK);

    // create znode success. become master and monitor
    elector.processResult(Code.OK.intValue(), ZK_LOCK_NAME, mockZK, ZK_LOCK_NAME);
    Mockito.verify(mockApp, Mockito.times(1)).becomeActive();
    verifyExistCall(2);

    // error event results in fatal error
    Mockito.when(mockEvent.getState()).thenReturn(Event.KeeperState.AuthFailed);
    elector.processWatchEvent(mockZK, mockEvent);
    Mockito.verify(mockApp, Mockito.times(1))
            .notifyFatalError("Unexpected Zookeeper watch event state: AuthFailed");
    // only 1 state change callback is called at a time
    Mockito.verify(mockApp, Mockito.times(1)).enterNeutralMode();
}

From source file:org.apache.hadoop.ha.TestActiveStandbyElector.java

License:Apache License

/**
 * joinElection(..) should happen only after SERVICE_HEALTHY.
 *///from   w  w w.  j  a v a 2 s .  c  o m
@Test
public void testBecomeActiveBeforeServiceHealthy() throws Exception {
    mockNoPriorActive();
    WatchedEvent mockEvent = Mockito.mock(WatchedEvent.class);
    Mockito.when(mockEvent.getType()).thenReturn(Event.EventType.None);
    // session expired should enter safe mode
    // But for first time, before the SERVICE_HEALTY i.e. appData is set,
    // should not enter the election.
    Mockito.when(mockEvent.getState()).thenReturn(Event.KeeperState.Expired);
    elector.processWatchEvent(mockZK, mockEvent);
    // joinElection should not be called.
    Mockito.verify(mockZK, Mockito.times(0)).create(ZK_LOCK_NAME, null, Ids.OPEN_ACL_UNSAFE,
            CreateMode.EPHEMERAL, elector, mockZK);
}

From source file:org.apache.hadoop.hbase.stargate.RESTServlet.java

License:Apache License

@Override
public void process(WatchedEvent event) {
    LOG.debug(("ZooKeeper.Watcher event " + event.getType() + " with path " + event.getPath()));
    // handle disconnection (or manual delete to test disconnection scenario)
    if (event.getState() == KeeperState.Expired
            || (event.getType().equals(EventType.NodeDeleted) && event.getPath().equals(znode))) {
        wrapper.close();/*from w w  w .  j  a v  a2s  . com*/
        wrapper = null;
        while (!stopping.get())
            try {
                wrapper = initZooKeeperWrapper();
                break;
            } catch (IOException e) {
                LOG.error(StringUtils.stringifyException(e));
                try {
                    Thread.sleep(10 * 1000);
                } catch (InterruptedException ex) {
                }
            }
    }
}

From source file:org.apache.hadoop.hbase.zookeeper.ZKWatcher.java

License:Apache License

/**
 * Method called from ZooKeeper for events and connection status.
 * <p>/*  ww  w . j  a va  2  s.com*/
 * Valid events are passed along to listeners.  Connection status changes
 * are dealt with locally.
 */
@Override
public void process(WatchedEvent event) {
    LOG.debug(prefix("Received ZooKeeper Event, " + "type=" + event.getType() + ", " + "state="
            + event.getState() + ", " + "path=" + event.getPath()));

    switch (event.getType()) {

    // If event type is NONE, this is a connection status change
    case None: {
        connectionEvent(event);
        break;
    }

    // Otherwise pass along to the listeners

    case NodeCreated: {
        for (ZKListener listener : listeners) {
            listener.nodeCreated(event.getPath());
        }
        break;
    }

    case NodeDeleted: {
        for (ZKListener listener : listeners) {
            listener.nodeDeleted(event.getPath());
        }
        break;
    }

    case NodeDataChanged: {
        for (ZKListener listener : listeners) {
            listener.nodeDataChanged(event.getPath());
        }
        break;
    }

    case NodeChildrenChanged: {
        for (ZKListener listener : listeners) {
            listener.nodeChildrenChanged(event.getPath());
        }
        break;
    }
    default:
        throw new IllegalStateException("Received event is not valid: " + event.getState());
    }
}

From source file:org.apache.hadoop.hbase.zookeeper.ZKWatcher.java

License:Apache License

/**
 * Called when there is a connection-related event via the Watcher callback.
 * <p>/* w  ww  . j a va  2s .  c o  m*/
 * If Disconnected or Expired, this should shutdown the cluster. But, since
 * we send a KeeperException.SessionExpiredException along with the abort
 * call, it's possible for the Abortable to catch it and try to create a new
 * session with ZooKeeper. This is what the client does in HCM.
 * <p>
 * @param event the connection-related event
 */
private void connectionEvent(WatchedEvent event) {
    switch (event.getState()) {
    case SyncConnected:
        this.identifier = this.prefix + "-0x" + Long.toHexString(this.recoverableZooKeeper.getSessionId());
        // Update our identifier.  Otherwise ignore.
        LOG.debug(this.identifier + " connected");
        break;

    // Abort the server if Disconnected or Expired
    case Disconnected:
        LOG.debug(prefix("Received Disconnected from ZooKeeper, ignoring"));
        break;

    case Expired:
        String msg = prefix(this.identifier + " received expired from " + "ZooKeeper, aborting");
        // TODO: One thought is to add call to ZKListener so say,
        // ZKNodeTracker can zero out its data values.
        if (this.abortable != null) {
            this.abortable.abort(msg, new KeeperException.SessionExpiredException());
        }
        break;

    case ConnectedReadOnly:
    case SaslAuthenticated:
    case AuthFailed:
        break;

    default:
        throw new IllegalStateException("Received event is not valid: " + event.getState());
    }
}

From source file:org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher.java

License:Apache License

/**
 * Called when there is a connection-related event via the Watcher callback.
 * <p>/*from w w w  .  ja  va 2s.  co  m*/
 * If Disconnected or Expired, this should shutdown the cluster. But, since
 * we send a KeeperException.SessionExpiredException along with the abort
 * call, it's possible for the Abortable to catch it and try to create a new
 * session with ZooKeeper. This is what the client does in HCM.
 * <p>
 * @param event
 */
private void connectionEvent(WatchedEvent event) {
    switch (event.getState()) {
    case SyncConnected:
        // Now, this callback can be invoked before the this.zookeeper is set.
        // Wait a little while.
        long finished = System.currentTimeMillis()
                + this.conf.getLong("hbase.zookeeper.watcher.sync.connected.wait", 2000);
        while (System.currentTimeMillis() < finished) {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                LOG.warn("Interrupted while sleeping");
                throw new RuntimeException("Interrupted while waiting for" + " recoverableZooKeeper is set");
            }
            if (this.recoverableZooKeeper != null)
                break;
        }

        if (this.recoverableZooKeeper == null) {
            LOG.error(
                    "ZK is null on connection event -- see stack trace "
                            + "for the stack trace when constructor was called on this zkw",
                    this.constructorCaller);
            throw new NullPointerException("ZK is null");
        }
        this.identifier = this.prefix + "-0x" + Long.toHexString(this.recoverableZooKeeper.getSessionId());
        // Update our identifier.  Otherwise ignore.
        LOG.debug(this.identifier + " connected");
        break;

    // Abort the server if Disconnected or Expired
    case Disconnected:
        LOG.debug(prefix("Received Disconnected from ZooKeeper, ignoring"));
        break;

    case Expired:
        String msg = prefix(this.identifier + " received expired from " + "ZooKeeper, aborting");
        // TODO: One thought is to add call to ZooKeeperListener so say,
        // ZooKeeperNodeTracker can zero out its data values.
        if (this.abortable != null) {
            this.abortable.abort(msg, new KeeperException.SessionExpiredException());
        }
        break;

    case ConnectedReadOnly:
    case SaslAuthenticated:
    case AuthFailed:
        break;

    default:
        throw new IllegalStateException("Received event is not valid: " + event.getState());
    }
}