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.bloomreach.bstore.highavailability.zookeeper.ZKConnectionManager.java

License:Apache License

/**
 * Attempts to randomly connect to a zookeeper node in an ensemble
 * with a maximum of 3 retries.//  w  w w .  ja va 2s .  c o m
 *
 * @param host
 * @return
 */
public static ZooKeeper connectToZookeeper(final String host) {

    Callable<ZooKeeper> callable = new Callable<ZooKeeper>() {
        String[] hosts = host.split(",");
        Random r = new Random();
        final String randomZkHost = hosts[r.nextInt(hosts.length)];

        public ZooKeeper call() throws Exception {
            //Make a synchronized connect to ZooKeeper
            ZooKeeper zk = new ZooKeeper(randomZkHost, 120000, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
                        connectedSignal.countDown();
                    }
                }
            });
            return zk;
        }
    };

    ZooKeeper zk = null;
    Retryer<ZooKeeper> retryer = RetryerBuilder.<ZooKeeper>newBuilder()
            .retryIfResult(Predicates.<ZooKeeper>isNull()).retryIfExceptionOfType(Exception.class)
            .retryIfRuntimeException().withStopStrategy(StopStrategies.stopAfterAttempt(3)).build();
    try {
        zk = retryer.call(callable);
    } catch (RetryException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    return zk;
}

From source file:com.bloomreach.zk.replicate.ZKConnectionManager.java

License:Apache License

public static ZooKeeper connectToZookeeper(final String host) {

    Callable<ZooKeeper> callable = new Callable<ZooKeeper>() {
        ArrayList<String> hostLists = new ArrayList(Arrays.asList(host.split(",")));

        public ZooKeeper call() throws Exception {
            while (hostLists.size() > 0) {
                Random r = new Random();
                int tempHostPosition = r.nextInt(hostLists.size());
                final String randomZkHost = hostLists.get(tempHostPosition);
                try {
                    // Make a synchronized connect to ZooKeeper
                    ZooKeeper zk = new ZooKeeper(randomZkHost, 120000, new Watcher() {
                        @Override
                        public void process(WatchedEvent event) {
                            if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
                                connectedSignal.countDown();
                            }//w w  w .  j  a  va  2s.c  o  m
                        }
                    });
                    connectedSignal.await(1L, TimeUnit.SECONDS);
                    //Check if the zk connection is good by fetching files
                    zk.getData("/zookeeper", null, null);
                    return zk;
                } catch (Exception e) {
                    hostLists.remove(tempHostPosition);
                }
            }
            return null;
        }
    };

    ZooKeeper zk = null;
    Retryer<ZooKeeper> retryer = RetryerBuilder.<ZooKeeper>newBuilder()
            .retryIfResult(Predicates.<ZooKeeper>isNull()).retryIfExceptionOfType(Exception.class)
            .retryIfRuntimeException().withStopStrategy(StopStrategies.stopAfterAttempt(3)).build();
    try {
        zk = retryer.call(callable);
    } catch (RetryException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    return zk;
}

From source file:com.boundary.zoocreeper.CommonOptions.java

License:Apache License

/**
 * Creates a connection to ZooKeeper (waiting for the connection to be made).
 * @param logger Logger used for informational messages.
 * @return A ZooKeeper client (in SyncConnected state).
 * @throws IOException If the connection couldn't be made.
 * @throws InterruptedException If interrupted while waiting for connection to be made.
 *///from w w w.  j a  v a 2s  .c  om
public ZooKeeper createZooKeeper(Logger logger) throws IOException, InterruptedException {
    final CountDownLatch connected = new CountDownLatch(1);
    logger.info("Connecting to ZooKeeper: {}", zkConnect);
    final ZooKeeper zk = new ZooKeeper(zkConnect, Ints.checkedCast(zkSessionTimeoutMs), new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (event.getState() == Event.KeeperState.SyncConnected) {
                connected.countDown();
            }
        }
    });
    try {
        if (!connected.await(zkConnectTimeoutMs, TimeUnit.MILLISECONDS)) {
            throw new IOException("Timeout out connecting to: " + zkConnect);
        }
        logger.info("Connected");
        return zk;
    } catch (InterruptedException e) {
        try {
            zk.close();
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        throw e;
    }
}

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.ja va2 s . 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.chinamobile.bcbsp.client.BSPJobClient.java

License:Apache License

@Override
public void process(WatchedEvent event) {
    if (event.getType().toString().equals("NodeDeleted")) {
        LOG.info("Now the BspController will change");
        ensureFreshjJobSubmitClient();/* ww w.ja v  a 2 s . c  o  m*/
        synchronized (mutex) {
            mutex.notify();
        }
    }
    // add for ZooKeeper connection Loss bug
    if (event.getState() == KeeperState.SyncConnected) {
        this.connectedLatch.countDown();
    }
}

From source file:com.chinamobile.bcbsp.sync.GeneralSSController.java

License:Apache License

@Override
public void process(WatchedEvent event) {
    synchronized (mutex) {
        mutex.notify();//from   w  w  w  . ja  v  a 2  s  . c  o m
    }
    if (event.getState() == new BSPkeeperStateImpl().getSyncConnected()) {
        this.connectedLatch.countDown();
    }
}

From source file:com.chinamobile.bcbsp.sync.WorkerSSController.java

License:Apache License

/**
 * @param event//from  w ww  . jav a 2s . c  om
 *        The WatchedEvent event.
 */
@Override
public void process(WatchedEvent event) {
    if (event.getState() == new BSPkeeperStateImpl().getSyncConnected()) {
        this.connectedLatch.countDown();
    }
}

From source file:com.cloudera.flume.master.ZKClient.java

License:Apache License

/**
 * Establishes a connection with a cluster of ZooKeeper servers. Throws an
 * IOException on failure.//from w ww .  j a va  2  s.c om
 */
public synchronized boolean init(final InitCallback initCallback) throws IOException {
    Preconditions.checkState(this.zk == null, "zk not null in ZKClient.init");
    initCallBack = initCallback;
    final Retryable retry = new Retryable() {
        public boolean doTry() throws Exception {
            // Wait on this latch for a connection to complete
            // It's important that every try gets its own latch
            final CountDownLatch latch = new CountDownLatch(1);
            final Watcher watcher = new Watcher() {
                public void process(WatchedEvent event) {
                    // Don't down the latch if we weren't the most recent attempt
                    if (event.getState() == KeeperState.SyncConnected) {
                        latch.countDown();
                    }
                }
            };

            zk = new ZooKeeper(hosts, 5000, watcher);

            if (!latch.await(5, TimeUnit.SECONDS)) {
                throw new IOException("Could not connect to ZooKeeper!");
            }
            if (initCallback != null) {
                initCallback.success(ZKClient.this);
            }
            return true;
        };
    };
    RetryHarness harness = new RetryHarness(retry, new FixedRetryPolicy(3), true);

    try {
        return harness.attempt();
    } catch (IOException i) {
        throw i;
    } catch (Exception e) {
        throw new IOException("Unexpected exception connecting to ZK", e);
    }
}

From source file:com.codefollower.lealone.zookeeper.ZooKeeperWatcher.java

License:Apache License

private void connectionEvent(WatchedEvent event) {
    switch (event.getState()) {
    case SyncConnected:
    case SaslAuthenticated:
    case AuthFailed:
    case Disconnected:
        break;/*from   w w  w . j  a v a  2  s . c o m*/
    case Expired:
        throw DbException.convert(new KeeperException.SessionExpiredException());
    }
}

From source file:com.codemacro.jcm.storage.ZookeeperStorageEngine.java

License:Apache License

public void process(WatchedEvent event) {
    if (event.getType() == Event.EventType.None) {
        switch (event.getState()) {
        case SyncConnected: // no matter session expired or not, we simply reload all
            for (ZookeeperPathWatcher w : watchers.values()) {
                w.onConnected();/*from w ww.  j  av  a2s .c  om*/
            }
            countDownLatch.countDown();
            break;
        case Disconnected: // zookeeper client will reconnect
            logger.warn("disconnected from zookeeper");
            break;
        // to test session expired, just close the laptop cover, making OS sleeping
        case Expired: // session expired by zookeeper server (after reconnected)
            logger.warn("session expired from zookeeper");
            for (ZookeeperPathWatcher w : watchers.values()) {
                w.onSessionExpired();
            }
            reconnect();
            break;
        default:
            break;
        }
    }
    String path = event.getPath();
    ZookeeperPathWatcher watcher = findWatcher(path);
    if (watcher == null) {
        return;
    }
    switch (event.getType()) {
    case NodeChildrenChanged:
        watcher.onListChanged();
        break;
    case NodeDataChanged:
        watcher.onChildData(path.substring(1 + path.lastIndexOf('/')));
    default:
        break;
    }
}