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:com.twitter.distributedlog.impl.ZKNamespaceWatcher.java

License:Apache License

@Override
public void process(WatchedEvent event) {
    if (event.getType() == Event.EventType.None) {
        if (event.getState() == Event.KeeperState.Expired) {
            scheduleTask(this, conf.getZKSessionTimeoutMilliseconds());
        }//from   w w w  .  j  a va  2 s . c  o  m
        return;
    }
    if (event.getType() == Event.EventType.NodeChildrenChanged) {
        // watch namespace changes again.
        doWatchNamespaceChanges();
    }
}

From source file:com.twitter.distributedlog.LocalDLMEmulator.java

License:Apache License

public static ZooKeeper connectZooKeeper(String zkHost, int zkPort, int zkTimeoutSec)
        throws IOException, KeeperException, InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final String zkHostPort = zkHost + ":" + zkPort;

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

From source file:com.twitter.distributedlog.readahead.ReadAheadWorker.java

License:Apache License

@Override
public void process(WatchedEvent event) {
    if (zkNotificationDisabled) {
        return;//from  w  ww  .j av a 2s.  c o  m
    }

    if ((event.getType() == Watcher.Event.EventType.None)
            && (event.getState() == Watcher.Event.KeeperState.SyncConnected)) {
        LOG.debug("Reconnected ...");
    } else if (((event.getType() == Event.EventType.None) && (event.getState() == Event.KeeperState.Expired))
            || ((event.getType() == Event.EventType.NodeChildrenChanged))) {
        AsyncNotification notification;
        synchronized (notificationLock) {
            reInitializeMetadata = true;
            LOG.debug("{} Read ahead node changed", fullyQualifiedName);
            notification = metadataNotification;
            metadataNotification = null;
        }
        metadataNotificationTimeMillis = System.currentTimeMillis();
        if (null != notification) {
            notification.notifyOnOperationComplete();
        }
    } else if (event.getType() == Event.EventType.NodeDeleted) {
        logDeleted = true;
        setReadAheadError(tracker);
    }
}

From source file:com.twitter.distributedlog.TestZooKeeperClient.java

License:Apache License

private void expireZooKeeperSession(ZooKeeper zk, int timeout)
        throws IOException, InterruptedException, KeeperException {
    final CountDownLatch latch = new CountDownLatch(1);

    ZooKeeper newZk = new ZooKeeper(zkServers, timeout, new Watcher() {
        @Override//  www.jav a  2  s.  com
        public void process(WatchedEvent event) {
            if (event.getType() == EventType.None && event.getState() == KeeperState.SyncConnected) {
                latch.countDown();
            }
        }
    }, zk.getSessionId(), zk.getSessionPasswd());

    if (!latch.await(timeout, TimeUnit.MILLISECONDS)) {
        throw KeeperException.create(KeeperException.Code.CONNECTIONLOSS);
    }

    newZk.close();
}

From source file:com.twitter.distributedlog.TestZooKeeperClient.java

License:Apache License

private CountDownLatch awaitConnectionEvent(final KeeperState state, final ZooKeeperClient zkc) {
    final CountDownLatch connected = new CountDownLatch(1);
    Watcher watcher = new Watcher() {
        @Override/* w w w  . ja va  2s .  co m*/
        public void process(WatchedEvent event) {
            if (event.getType() == EventType.None && event.getState() == state) {
                connected.countDown();
            }
        }
    };
    zkc.register(watcher);
    return connected;
}

From source file:com.twitter.distributedlog.util.LimitedPermitManager.java

License:Apache License

@Override
public void process(WatchedEvent event) {
    if (event.getType().equals(Event.EventType.None)) {
        switch (event.getState()) {
        case SyncConnected:
            forceSetAllowPermits(true);//  w  w  w  .j  a  va 2  s.co m
            break;
        case Disconnected:
            forceSetAllowPermits(false);
            break;
        case Expired:
            forceSetAllowPermits(false);
            break;
        default:
            break;
        }
    }
}

From source file:com.twitter.distributedlog.ZooKeeperClient.java

License:Apache License

private ZooKeeper buildZooKeeper() throws ZooKeeperConnectionException, InterruptedException {
    Watcher watcher = new Watcher() {
        @Override//w  ww  .  j  av  a 2  s . com
        public void process(WatchedEvent event) {
            switch (event.getType()) {
            case None:
                switch (event.getState()) {
                case Expired:
                    if (null == retryPolicy) {
                        LOG.info("ZooKeeper {}' session expired. Event: {}", name, event);
                        closeInternal();
                    }
                    authenticated = false;
                    break;
                case Disconnected:
                    if (null == retryPolicy) {
                        LOG.info("ZooKeeper {} is disconnected from zookeeper now,"
                                + " but it is OK unless we received EXPIRED event.", name);
                    }
                    // Mark as not authenticated if expired or disconnected. In both cases
                    // we lose any attached auth info. Relying on Expired/Disconnected is
                    // sufficient since all Expired/Disconnected events are processed before
                    // all SyncConnected events, and the underlying member is not updated until
                    // SyncConnected is received.
                    authenticated = false;
                    break;
                default:
                    break;
                }
            }

            try {
                for (Watcher watcher : watchers) {
                    try {
                        watcher.process(event);
                    } catch (Throwable t) {
                        LOG.warn("Encountered unexpected exception from watcher {} : ", watcher, t);
                    }
                }
            } catch (Throwable t) {
                LOG.warn("Encountered unexpected exception when firing watched event {} : ", event, t);
            }
        }
    };

    Set<Watcher> watchers = new HashSet<Watcher>();
    watchers.add(watcher);

    ZooKeeper zk;
    try {
        RetryPolicy opRetryPolicy = null == retryPolicy
                ? new BoundExponentialBackoffRetryPolicy(sessionTimeoutMs, sessionTimeoutMs, 0)
                : retryPolicy;
        RetryPolicy connectRetryPolicy = null == retryPolicy
                ? new BoundExponentialBackoffRetryPolicy(sessionTimeoutMs, sessionTimeoutMs, 0)
                : new BoundExponentialBackoffRetryPolicy(sessionTimeoutMs, sessionTimeoutMs, Integer.MAX_VALUE);
        zk = org.apache.bookkeeper.zookeeper.ZooKeeperClient.newBuilder().connectString(zooKeeperServers)
                .sessionTimeoutMs(sessionTimeoutMs).watchers(watchers).operationRetryPolicy(opRetryPolicy)
                .connectRetryPolicy(connectRetryPolicy).statsLogger(statsLogger)
                .retryThreadCount(retryThreadCount).requestRateLimit(requestRateLimit).build();
    } catch (KeeperException e) {
        throw new ZooKeeperConnectionException("Problem connecting to servers: " + zooKeeperServers, e);
    } catch (IOException e) {
        throw new ZooKeeperConnectionException("Problem connecting to servers: " + zooKeeperServers, e);
    }
    return zk;
}

From source file:com.twitter.distributedlog.ZooKeeperClient.java

License:Apache License

/**
 * Clients that need to re-establish state after session expiration can register an
 * {@code onExpired} command to execute.
 *
 * @param onExpired the {@code Command} to register
 * @return the new {@link Watcher} which can later be passed to {@link #unregister} for
 *         removal./*from  ww w .  j ava 2  s . c  o m*/
 */
public Watcher registerExpirationHandler(final ZooKeeperSessionExpireNotifier onExpired) {
    Watcher watcher = new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (event.getType() == EventType.None && event.getState() == KeeperState.Expired) {
                try {
                    onExpired.notifySessionExpired();
                } catch (Exception exc) {
                    // do nothing
                }
            }
        }
    };
    register(watcher);
    return watcher;
}

From source file:com.twitter.distributedlog.ZooKeeperClientUtils.java

License:Apache License

/**
 * Expire given zookeeper client's session.
 *
 * @param zkc//from  www .j ava 2 s.c om
 *          zookeeper client
 * @param zkServers
 *          zookeeper servers
 * @param timeout
 *          timeout
 * @throws Exception
 */
public static void expireSession(ZooKeeperClient zkc, String zkServers, int timeout) throws Exception {
    final CountDownLatch expireLatch = new CountDownLatch(1);
    final CountDownLatch latch = new CountDownLatch(1);
    ZooKeeper oldZk = zkc.get();
    oldZk.exists("/", new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            logger.debug("Receive event : {}", event);
            if (event.getType() == Event.EventType.None && event.getState() == Event.KeeperState.Expired) {
                expireLatch.countDown();
            }
        }
    });
    ZooKeeper newZk = new ZooKeeper(zkServers, timeout, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (Event.EventType.None == event.getType()
                    && Event.KeeperState.SyncConnected == event.getState()) {
                latch.countDown();
            }
        }
    }, oldZk.getSessionId(), oldZk.getSessionPasswd());
    if (!latch.await(timeout, TimeUnit.MILLISECONDS)) {
        throw KeeperException.create(KeeperException.Code.CONNECTIONLOSS);
    }
    newZk.close();

    boolean done = false;
    Stopwatch expireWait = Stopwatch.createStarted();
    while (!done && expireWait.elapsed(TimeUnit.MILLISECONDS) < timeout * 2) {
        try {
            zkc.get().exists("/", false);
            done = true;
        } catch (KeeperException ke) {
            done = (ke.code() == KeeperException.Code.SESSIONEXPIRED);
        }
    }

    assertTrue("Client should receive session expired event.",
            expireLatch.await(timeout, TimeUnit.MILLISECONDS));
}

From source file:com.twitter.finagle.common.zookeeper.ZooKeeperClient.java

License:Apache License

/**
 * Returns the current active ZK connection or establishes a new one if none has yet been
 * established or a previous connection was disconnected or had its session time out.  This
 * method will attempt to re-use sessions when possible.
 *
 * @param connectionTimeout the maximum amount of time to wait for the connection to the ZK
 *     cluster to be established; 0 to wait forever
 * @return a connected ZooKeeper client/* www. j  av  a  2s  .c  om*/
 * @throws ZooKeeperConnectionException if there was a problem connecting to the ZK cluster
 * @throws InterruptedException if interrupted while waiting for a connection to be established
 * @throws TimeoutException if a connection could not be established within the configured
 *     session timeout
 */
public synchronized ZooKeeper get(Duration connectionTimeout)
        throws ZooKeeperConnectionException, InterruptedException, TimeoutException {

    if (zooKeeper == null) {
        final CountDownLatch connected = new CountDownLatch(1);
        Watcher watcher = new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                switch (event.getType()) {
                // Guard the None type since this watch may be used as the default watch on calls by
                // the client outside our control.
                case None:
                    switch (event.getState()) {
                    case Expired:
                        LOG.info("Zookeeper session expired. Event: " + event);
                        close();
                        break;
                    case SyncConnected:
                        connected.countDown();
                        break;
                    default:
                        break; // nop
                    }
                    break;
                default:
                    break; // nop
                }

                eventQueue.offer(event);
            }
        };

        try {
            zooKeeper = (sessionState != null)
                    ? new ZooKeeper(connectString, sessionTimeoutMs, watcher, sessionState.sessionId,
                            sessionState.sessionPasswd)
                    : new ZooKeeper(connectString, sessionTimeoutMs, watcher);
        } catch (IOException e) {
            throw new ZooKeeperConnectionException("Problem connecting to servers: " + zooKeeperServers, e);
        }

        if (connectionTimeout.inMillis() > 0) {
            if (!connected.await(connectionTimeout.inMillis(), TimeUnit.MILLISECONDS)) {
                close();
                throw new TimeoutException("Timed out waiting for a ZK connection after " + connectionTimeout);
            }
        } else {
            try {
                connected.await();
            } catch (InterruptedException ex) {
                LOG.info("Interrupted while waiting to connect to zooKeeper");
                close();
                throw ex;
            }
        }
        credentials.authenticate(zooKeeper);

        sessionState = new SessionState(zooKeeper.getSessionId(), zooKeeper.getSessionPasswd());
    }
    return zooKeeper;
}