Example usage for org.apache.zookeeper Watcher Watcher

List of usage examples for org.apache.zookeeper Watcher Watcher

Introduction

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

Prototype

Watcher

Source Link

Usage

From source file:com.andyadc.menagerie.latches.ZkCyclicBarrierTest.java

License:Apache License

private static ZooKeeper newZooKeeper() throws IOException {
    return new ZooKeeper("localhost:2181", timeout, new Watcher() {
        @Override/*  ww  w.  ja va  2s  . c  om*/
        public void process(WatchedEvent event) {
            //                System.out.println(event);
        }
    });
}

From source file:com.andyadc.menagerie.locks.ReentrantZkLock2Test.java

License:Apache License

private static ZooKeeper newZooKeeper() throws IOException {
    return new ZooKeeper(hostString, timeout, new Watcher() {
        @Override/*from  w w w  . j  a v  a 2  s .  c  o  m*/
        public void process(WatchedEvent event) {
            //                System.out.println(event);
        }
    });
}

From source file:com.andyadc.menagerie.locks.ReentrantZkLockTest.java

License:Apache License

private static ZooKeeper newZooKeeper() throws IOException {
    System.out.printf("%s: Creating new ZooKeeper%n", Thread.currentThread().getName());
    return new ZooKeeper(hostString, timeout, new Watcher() {
        @Override/*ww  w  .ja v  a 2  s. c o  m*/
        public void process(WatchedEvent event) {
            //                System.out.println(event);
        }
    });
}

From source file:com.andyadc.menagerie.MenagerieTest.java

License:Apache License

/**
 * Creates a new test ZooKeeper instance
 *
 * @return a new ZooKeeper instance/*from  w w w . j ava2  s.  c om*/
 * @throws IOException if there is trouble connecting to ZooKeeper
 */
protected static ZooKeeper newZooKeeper() throws IOException {
    return new ZooKeeper(hostString, timeout, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            //                System.out.println(event);
        }
    });
}

From source file:com.andyadc.menagerie.ZkSessionPoller.java

License:Apache License

public static void main(String... args) throws Exception {
    Logger rootLogger = Logger.getRootLogger();
    rootLogger.setLevel(Level.INFO);
    rootLogger.addAppender(new ConsoleAppender(new SimpleLayout()));

    final ZooKeeper zk = new ZooKeeper("172.16.84.129:2181", 2000, new Watcher() {
        @Override//from w  ww  . j a v a  2  s .c om
        public void process(WatchedEvent event) {
            System.out.printf("state=%s\ttype=%s%n", event.getState(), event.getType());
        }
    });

    final CountDownLatch latch = new CountDownLatch(1);

    ZkSessionPoller poller = new ZkSessionPoller(zk, 200, new ConnectionListenerSkeleton() {

        @Override
        public void expired() {
            System.err.println("Session Expired, shutting down.");
            try {
                zk.close();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            latch.countDown();
        }
    });

    poller.startPolling();
    latch.await();
    poller.stopPolling();
}

From source file:com.att.nsa.zkUtils.ZkWatcher.java

License:Open Source License

public static Watcher getLoggingWatcher(final String title, final Logger log) {
    return new Watcher() {
        @Override/*from w w w  .  ja v  a  2s  . com*/
        public void process(WatchedEvent event) {
            log.info("ZK watch for " + title + ": " + event.getType() + " @ " + event.getPath());
        }
    };
}

From source file:com.bigdata.journal.jini.ha.AbstractHA3JournalServerTestCase.java

License:Open Source License

/**
 * Return Zookeeper quorum that can be used to reflect (or act on) the
 * distributed quorum state for the logical service.
 * //from  www .  j a v  a2  s  .  c om
 * @throws ConfigurationException
 * @throws InterruptedException 
 * @throws KeeperException 
 * @throws IOException 
 */
protected Quorum<HAGlue, QuorumClient<HAGlue>> newQuorum()
        throws ConfigurationException, InterruptedException, KeeperException, IOException {

    final Configuration config = ConfigurationProvider
            .getInstance(new String[] { SRC_PATH + getZKConfigFile() });

    zkClientConfig = new ZookeeperClientConfig(config);

    final List<ACL> acl = zkClientConfig.acl;
    final String zoohosts = zkClientConfig.servers;
    final int sessionTimeout = zkClientConfig.sessionTimeout;

    // Note: Save reference.
    this.zookeeper = new ZooKeeper(zoohosts, sessionTimeout, new Watcher() {
        @Override
        public void process(final WatchedEvent event) {
            if (log.isInfoEnabled())
                log.info(event);
        }
    });
    /**
     * Wait until zookeeper is connected. Figure out how long that took. If
     * reverse DNS is not setup, then the following two tickets will prevent
     * the service from starting up in a timely manner. We detect this with
     * a delay of 4+ seconds before zookeeper becomes connected. This issue
     * does not appear in zookeeper 3.3.4.
     * 
     * @see https://issues.apache.org/jira/browse/ZOOKEEPER-1652
     * @see https://issues.apache.org/jira/browse/ZOOKEEPER-1666
     */
    {
        final long begin = System.nanoTime();
        while (zookeeper.getState().isAlive()) {
            if (zookeeper.getState() == States.CONNECTED) {
                // connected.
                break;
            }
            final long elapsed = System.nanoTime() - begin;
            if (TimeUnit.NANOSECONDS.toSeconds(elapsed) > 4) {
                fail("Either zookeeper is not running or reverse DNS is not configured. "
                        + "The ZooKeeper client is taking too long to resolve server(s): state="
                        + zookeeper.getState() + ", config=" + zkClientConfig + ", took="
                        + TimeUnit.NANOSECONDS.toMillis(elapsed) + "ms");
            }
            // wait and then retry.
            Thread.sleep(100/* ms */);
        }
    }

    // znode name for the logical service.
    //        final String logicalServiceId = (String) config.getEntry(
    //                ZookeeperClientConfig.Options.NAMESPACE,
    //                ConfigurationOptions.LOGICAL_SERVICE_ID, String.class);
    final String logicalServiceId = getLogicalServiceId();

    final String logicalServiceZPathPrefix = zkClientConfig.zroot + "/" + HAJournalServer.class.getName();

    // zpath for the logical service (save reference).
    logicalServiceZPath = logicalServiceZPathPrefix + "/" + logicalServiceId;

    /**
     * Note: This is defined in the HAJournal.config file, which is where
     * the HAJournalServer gets the correct value.
     * 
     * However, we also need to have the replicationFactor on hand for the
     * test suite so we can setup the quorum in the test fixture correctly.
     */
    final int replicationFactor = replicationFactor();
    //        {
    //            replicationFactor = (Integer) config.getEntry(
    //                    ConfigurationOptions.COMPONENT,
    //                    ConfigurationOptions.REPLICATION_FACTOR, Integer.TYPE);
    //        }

    //        if (!zka.awaitZookeeperConnected(10, TimeUnit.SECONDS)) {
    //
    //            throw new RuntimeException("Could not connect to zk");
    //
    //        }
    //
    //        if (log.isInfoEnabled()) {
    //            log.info("Connected to zookeeper");
    //        }

    /*
     * Ensure key znodes exist.
     */
    try {
        getZookeeper().create(zkClientConfig.zroot, new byte[] { /* data */ }, acl, CreateMode.PERSISTENT);
    } catch (NodeExistsException ex) {
        // ignore.
    }
    try {
        getZookeeper().create(logicalServiceZPathPrefix, new byte[] { /* data */ }, acl, CreateMode.PERSISTENT);
    } catch (NodeExistsException ex) {
        // ignore.
    }
    try {
        getZookeeper().create(logicalServiceZPath, new byte[] { /* data */ }, acl, CreateMode.PERSISTENT);
    } catch (NodeExistsException ex) {
        // ignore.
    }

    // Quorum that can be used to monitor the distributed quorum state.
    final Quorum<HAGlue, QuorumClient<HAGlue>> quorum = (Quorum) new ZKQuorumImpl<HAGlue, ZKQuorumClient<HAGlue>>(
            replicationFactor);//, zka, acl);

    quorum.start(new MockQuorumClient<HAGlue>(logicalServiceZPath));

    return quorum;

}

From source file:com.bigdata.service.jini.AbstractServer.java

License:Open Source License

/**
 * Server startup reads {@link Configuration} data from the file or URL
 * named by <i>args</i> and applies any optional overrides, starts the
 * service, and advertises the service for discovery. Aside from the server
 * class to start, the behavior is more or less entirely parameterized by
 * the {@link Configuration}./* w  w w.  ja  va 2  s  .  c  o m*/
 * 
 * @param args
 *            Either the command line arguments or the arguments from the
 *            {@link ServiceDescriptor}. Either way they identify the jini
 *            {@link Configuration} (you may specify either a file or URL)
 *            and optional overrides for that {@link Configuration}.
 * @param lifeCycle
 *            The life cycle object. This is used if the server is started
 *            by the jini {@link ServiceStarter}. Otherwise specify a
 *            {@link FakeLifeCycle}.
 * 
 * @see NonActivatableServiceDescriptor
 */
protected AbstractServer(final String[] args, final LifeCycle lifeCycle) {

    // Show the copyright banner during startup.
    Banner.banner();

    if (lifeCycle == null)
        throw new IllegalArgumentException();

    this.lifeCycle = lifeCycle;

    setSecurityManager();

    /*
     * Display the banner.
     * 
     * Note: This also installs the UncaughtExceptionHandler.
     * 
     * @see https://sourceforge.net/apps/trac/bigdata/ticket/601
     */
    Banner.banner();
    //        Thread.setDefaultUncaughtExceptionHandler(
    //                new Thread.UncaughtExceptionHandler() {
    //                    public void uncaughtException(Thread t, Throwable e) {
    //                        log.warn("Uncaught exception in thread", e);
    //                    }
    //                });

    /*
     * Read jini configuration & service properties 
     */

    List<Entry> entries = null;

    final JiniClientConfig jiniClientConfig;
    try {

        config = ConfigurationProvider.getInstance(args);

        jiniClientConfig = new JiniClientConfig(getClass().getName(), config);

        /*
         * The zpath of the logical service.
         * 
         * @todo null allowed if zookeeper not in use. make required if
         * zookeeper is a required integration, but then you will really
         * need to use the ServicesManager to start any service since the
         * zookeeper configuration needs to be established as well.
         */
        logicalServiceZPath = (String) config.getEntry(getClass().getName(),
                ConfigurationOptions.LOGICAL_SERVICE_ZPATH, String.class, null/* default */);

        /*
         * Make sure that the parent directory exists.
         * 
         * Note: the parentDir will be null if the serviceIdFile is in the
         * root directory or if it is specified as a filename without any
         * parents in the path expression. Note that the file names a file
         * in the current working directory in the latter case and the root
         * always exists in the former - and in both of those cases we do
         * not have to create the parent directory.
         */
        serviceDir = (File) config.getEntry(getClass().getName(), ConfigurationOptions.SERVICE_DIR, File.class);

        if (serviceDir != null && !serviceDir.exists()) {

            log.warn("Creating: " + serviceDir);

            serviceDir.mkdirs();

        }

        // The file on which the ServiceID will be written.
        serviceIdFile = new File(serviceDir, "service.id");

        // The lock file.
        lockFile = new File(serviceDir, ".lock");

        /*
         * Attempt to acquire an exclusive lock on a file in the same
         * directory as the serviceIdFile.
         */
        acquireFileLock();

        writePIDFile(pidFile = new File(serviceDir, "pid"));

        // convert Entry[] to a mutable list.
        entries = new LinkedList<Entry>(Arrays.asList(jiniClientConfig.entries));

        /*
         * Make sure that there is a Name and Hostname associated with the
         * service. If a ServiceID was pre-assigned in the Configuration
         * then we will extract that also.
         */
        {

            String serviceName = null;

            String hostname = null;

            UUID serviceUUID = null;

            for (Entry e : entries) {

                if (e instanceof Name && serviceName == null) {

                    // found a name.
                    serviceName = ((Name) e).name;

                }

                if (e instanceof Hostname && hostname == null) {

                    hostname = ((Hostname) e).hostname;

                }

                if (e instanceof ServiceUUID && serviceUUID == null) {

                    serviceUUID = ((ServiceUUID) e).serviceUUID;

                }

            }

            // if serviceName not given then set it now.
            if (serviceName == null) {

                // assign a default service name.

                final String defaultName = getClass().getName() + "@"
                        + AbstractStatisticsCollector.fullyQualifiedHostName + "#" + hashCode();

                serviceName = defaultName;

                // add to the Entry[].
                entries.add(new Name(serviceName));

            }

            // set the field on the class.
            this.serviceName = serviceName;

            // if hostname not given then set it now.
            if (hostname == null) {

                /*
                 * @todo This is a best effort during startup and unchanging
                 * thereafter. We should probably report all names for the
                 * host and report the current names for the host. However
                 * there are a number of issues where similar data are not
                 * being updated which could lead to problems if host name
                 * assignments were changed.
                 */

                hostname = AbstractStatisticsCollector.fullyQualifiedHostName;

                // add to the Entry[].
                entries.add(new Hostname(hostname));

            }

            // set the field on the class.
            this.hostname = hostname;

            // if serviceUUID assigned then set ServiceID from it now.
            if (serviceUUID != null) {

                // set serviceID.
                this.serviceID = JiniUtil.uuid2ServiceID(serviceUUID);

                if (!serviceIdFile.exists()) {

                    // write the file iff it does not exist.
                    writeServiceIDOnFile(this.serviceID);

                }

            } else if (!serviceIdFile.exists()) {

                /*
                 * Since nobody assigned us a ServiceID and since there is
                 * none on record in the [serviceIdFile], we assign one now
                 * ourselves.
                 */

                // set serviceID.
                this.serviceID = JiniUtil.uuid2ServiceID(UUID.randomUUID());

                // write the file iff it does not exist.
                writeServiceIDOnFile(this.serviceID);

            }

        }

        /*
         * Extract how the service will provision itself from the
         * Configuration.
         */

        // The exporter used to expose the service proxy.
        exporter = (Exporter) config.getEntry(//
                getClass().getName(), // component
                ConfigurationOptions.EXPORTER, // name
                Exporter.class, // type (of the return object)
                /*
                 * The default exporter is a BasicJeriExporter using a
                 * TcpServerEnpoint.
                 */
                new BasicJeriExporter(TcpServerEndpoint.getInstance(0), new BasicILFactory()));

        if (serviceIdFile.exists()) {

            try {

                final ServiceID serviceIDFromFile = readServiceId(serviceIdFile);

                if (this.serviceID == null) {

                    // set field on class.
                    this.serviceID = serviceIDFromFile;

                } else if (!this.serviceID.equals(serviceIDFromFile)) {

                    /*
                     * This is a paranoia check on the Configuration and the
                     * serviceIdFile. The ServiceID should never change so
                     * these values should remain in agreement.
                     */

                    throw new ConfigurationException(
                            "ServiceID in Configuration does not agree with the value in " + serviceIdFile
                                    + " : Configuration=" + this.serviceID + ", serviceIdFile="
                                    + serviceIDFromFile);

                }

            } catch (IOException ex) {

                fatal("Could not read serviceID from existing file: " + serviceIdFile + ": " + this, ex);

            }

        } else {

            if (log.isInfoEnabled())
                log.info("New service instance.");

        }

    } catch (ConfigurationException ex) {

        fatal("Configuration error: " + this, ex);

    }

    /*
     * The runtime shutdown hook appears to be a robust way to handle ^C by
     * providing a clean service termination.
     * 
     * Note: This is setup before we start any async threads, including
     * service discovery.
     */
    Runtime.getRuntime().addShutdownHook(new ShutdownThread(this));

    /*
     * Start the client - this provides a means to connect to the other
     * services running in the federation (it runs a DiscoveryManager to do
     * that).
     */
    try {

        // new client - defer connection to fed.
        client = new JiniClient(getClass(), config);

        //            // connect to the federation (starts service discovery for the client).
        //            client.connect();

    } catch (Throwable t) {

        fatal("Could not create JiniClient: " + this, t);

    }

    /*
     * Create the service object.
     */
    JiniFederation<?> fed = null;
    try {

        /*
         * Note: By creating the service object here rather than outside of
         * the constructor we potentially create problems for subclasses of
         * AbstractServer since their own constructor will not have been
         * executed yet.
         * 
         * Some of those problems are worked around using a JiniClient to
         * handle all aspects of service discovery (how this service locates
         * the other services in the federation).
         * 
         * Note: If you explicitly assign values to those clients when the
         * fields are declared, e.g., [timestampServiceClient=null] then the
         * ctor will overwrite the values set by [newService] since it is
         * running before those initializations are performed. This is
         * really crufty, may be JVM dependent, and needs to be refactored
         * to avoid this subclass ctor init problem.
         */

        if (log.isInfoEnabled())
            log.info("Creating service impl...");

        // init w/ client's properties.
        impl = newService(client.getProperties());

        if (log.isInfoEnabled())
            log.info("Service impl is " + impl);

        // Connect to the federation (starts service discovery for client).
        final JiniFederation<?> f = fed = client.connect();

        /*
         * Add a watcher that will create the ephemeral znode for the
         * federation on zookeeper (re-)connect.
         * 
         * Note: We don't have to do this once we have been connected, but
         * if the service starts without a zookeeper connection and then
         * later connects then it will otherwise fail to create its znode.
         */
        fed.getZookeeperAccessor().addWatcher(new Watcher() {

            boolean sessionValid = false;

            public void process(WatchedEvent event) {

                switch (event.getState()) {
                case Expired:
                    sessionValid = false;
                    synchronized (AbstractServer.this) {
                        /*
                         * Synchronized so that creating and cancelling the
                         * master election future are atomic.
                         */
                        if (masterElectionFuture != null) {
                            masterElectionFuture.cancel(true/* mayInterruptIfRunning */);
                            masterElectionFuture = null;
                            log.warn("Zookeeper session expired: cancelled master election task: " + this);
                        }
                    }
                    break;
                case NoSyncConnected:
                case SyncConnected:
                    if (!sessionValid) {
                        sessionValid = true;
                        if (serviceID != null) {
                            try {
                                notifyZookeeper(f, JiniUtil.serviceID2UUID(serviceID));
                            } catch (Throwable t) {
                                log.error(AbstractServer.this, t);
                            }
                        }
                    }
                } // switch

            } // process(event)
        }); // Watcher

        // start the service.
        if (impl instanceof AbstractService) {

            ((AbstractService) impl).start();

        }

    } catch (Exception ex) {

        fatal("Could not start service: " + this, ex);

    }

    /*
     * Export a proxy object for this service instance.
     * 
     * Note: This must be done before we start the join manager since the
     * join manager will register the proxy.
     */
    try {

        proxy = exporter.export(impl);

        if (log.isInfoEnabled())
            log.info("Proxy is " + proxy + "(" + proxy.getClass() + ")");

    } catch (ExportException ex) {

        fatal("Export error: " + this, ex);

    }

    /*
     * Start the join manager. 
     */
    try {

        assert proxy != null : "No proxy?";

        final Entry[] attributes = entries.toArray(new Entry[0]);

        if (this.serviceID != null) {

            /*
             * We read the serviceID from local storage (either the
             * serviceIDFile and/or the Configuration).
             */

            joinManager = new JoinManager(proxy, // service proxy
                    attributes, // attr sets
                    serviceID, // ServiceID
                    fed.getDiscoveryManagement(), // DiscoveryManager
                    new LeaseRenewalManager(), //
                    config);

        } else {

            /*
             * We are requesting a serviceID from the registrar.
             */

            joinManager = new JoinManager(proxy, // service proxy
                    attributes, // attr sets
                    this, // ServiceIDListener
                    fed.getDiscoveryManagement(), // DiscoveryManager
                    new LeaseRenewalManager(), //
                    config);

        }

    } catch (Exception ex) {

        fatal("JoinManager: " + this, ex);

    }

    /*
     * Note: This is synchronized in case set via listener by the
     * JoinManager, which would be rather fast action on its part.
     */
    synchronized (this) {

        if (this.serviceID != null) {

            /*
             * Notify the service that it's service UUID has been set.
             * 
             * @todo Several things currently depend on this notification.
             * In effect, it is being used as a proxy for the service
             * registration event.
             */

            notifyServiceUUID(serviceID);

        }

    }

}

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

License:Open Source License

/**
 * Return a new {@link ZooKeeper} instance connects to the same
 * zookeeper ensemble but which uses distinct {@link ZooKeeper} session.
 * //from  w ww  .  j a v a 2 s  . c om
 * @throws InterruptedException
 * @throws IOException 
 */
protected ZooKeeper getZooKeeperAccessorWithDistinctSession() throws InterruptedException, IOException {

    return new ZooKeeper(zookeeperAccessor.hosts, zookeeperAccessor.sessionTimeout, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (log.isInfoEnabled())
                log.info(event);
        }
    });

    //        final ZooKeeper zookeeper2 = new ZooKeeper(zookeeperAccessor.hosts,
    //                zookeeperAccessor.sessionTimeout, new Watcher() {
    //                    public void process(WatchedEvent e) {
    //
    //                    }
    //                });
    //        
    //        /*
    //         * Wait until this instance is connected.
    //         */
    //        final long timeout = TimeUnit.MILLISECONDS.toNanos(1000/* ms */);
    //
    //        final long begin = System.nanoTime();
    //
    //        while (zookeeper2.getState() != ZooKeeper.States.CONNECTED
    //                && zookeeper2.getState().isAlive()) {
    //
    //            final long elapsed = System.nanoTime() - begin;
    //
    //            if (elapsed > timeout) {
    //
    //                fail("ZooKeeper session did not connect? elapsed="
    //                        + TimeUnit.NANOSECONDS.toMillis(elapsed));
    //
    //            }
    //
    //            if (log.isInfoEnabled()) {
    //
    //                log.info("Awaiting connected.");
    //
    //            }
    //
    //            Thread.sleep(100/* ms */);
    //
    //        }
    //
    //        if (!zookeeper2.getState().isAlive()) {
    //
    //            fail("Zookeeper died?");
    //
    //        }
    //
    //        if(log.isInfoEnabled())
    //            log.info("Zookeeper connected.");
    //        
    //        return zookeeper2;

}

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

License:Open Source License

/**
 * Return a new {@link ZooKeeper} instance that is connected to the same
 * zookeeper ensemble as the given instance and is using the same session
 * but is nevertheless a distinct instance.
 * <p>/*from   w  w  w .  ja v a  2 s.  c  o  m*/
 * Note: This is used by some unit tests to force the given
 * {@link ZooKeeper} to report a {@link SessionExpiredException} by closing
 * the returned instance.
 * 
 * @param zookeeper
 *            A zookeeper instance.
 * 
 * @return A distinct instance associated with the same session.
 * 
 * @throws IOException
 * @throws InterruptedException
 */
protected ZooKeeper getDistinctZooKeeperForSameSession(final ZooKeeper zookeeper1)
        throws IOException, InterruptedException {

    final ZooKeeper zookeeper2 = new ZooKeeper(zookeeperAccessor.hosts, zookeeperAccessor.sessionTimeout,
            new Watcher() {
                public void process(WatchedEvent e) {

                }
            }, zookeeper1.getSessionId(), zookeeper1.getSessionPasswd());

    /*
     * Wait until this instance is connected.
     */
    final long timeout = TimeUnit.MILLISECONDS.toNanos(1000/* ms */);

    final long begin = System.nanoTime();

    while (zookeeper2.getState() != ZooKeeper.States.CONNECTED && zookeeper2.getState().isAlive()) {

        final long elapsed = System.nanoTime() - begin;

        if (elapsed > timeout) {

            fail("ZooKeeper session did not connect? elapsed=" + TimeUnit.NANOSECONDS.toMillis(elapsed));

        }

        if (log.isInfoEnabled()) {

            log.info("Awaiting connected.");

        }

        Thread.sleep(100/* ms */);

    }

    if (!zookeeper2.getState().isAlive()) {

        fail("Zookeeper died?");

    }

    if (log.isInfoEnabled())
        log.info("Zookeeper connected.");

    return zookeeper2;

}