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:io.s4.zeno.route.ZKRouter.java

License:Open Source License

/**
 * Read map./*from   w w  w .ja va  2 s.co  m*/
 */
private void readMap() {
    // scan partsBase
    logger.debug("reading router map from " + zkpath.partsBase);

    try {
        List<String> parts = zookeeper.getChildren(zkpath.partsBase + "/items", new Watcher() {
            public void process(WatchedEvent w) {
                readMap();
            }
        });

        ArrayList<Part.Id> partIds = new ArrayList<Part.Id>();

        // for each node, check route map and holds.
        // update routemap
        for (String p : parts) {
            Part.Id id = Part.Id.fromString(p);

            if (id != null) {
                partIds.add(id);
                updateDest(zkpath.routeMap(id.toString()));
                updateHold(zkpath.routeHold(id.toString()));
            }
        }

        hasher.rebuild(partIds);

    } catch (KeeperException e) {
        logger.error("exception while listing parts: " + e);
        throw (new ZenoError("error reading routing map at " + zkpath.partsBase, e));

    } catch (InterruptedException e) {
        logger.error("interrupted while listing parts");
    }

}

From source file:io.seldon.api.state.ZkABTestingUpdater.java

License:Apache License

@Override
public void run() {
    logger.info("Starting");
    try {/*from   w  w  w  . j  a  v  a2  s .  c om*/
        while (keepRunning) {
            boolean error = false;
            try {

                CuratorFramework client = null;
                boolean ok = false;
                for (int attempts = 0; attempts < 4 && !ok; attempts++) {
                    client = curatorHandler.getCurator().usingNamespace(clientName);
                    logger.info("Waiting until zookeeper connected");
                    ok = client.getZookeeperClient().blockUntilConnectedOrTimedOut();
                    if (ok)
                        logger.info("zookeeper connected on attempt " + attempts);
                    else {
                        logger.error("Timed out waiting for zookeeper connect : attempt " + attempts);
                    }
                }
                if (!ok) {
                    logger.error("Failed to connect to zookeeper after multiple attempts - STOPPING");
                    return;
                }
                queue = new LinkedBlockingQueue<>();
                Watcher watcher = new Watcher() {
                    boolean expired;

                    @Override
                    public void process(WatchedEvent event) {
                        try {
                            if (event.getPath() != null)
                                queue.put(event.getPath());
                            else {
                                logger.warn("Unexpected event " + event.getType().name() + " -> "
                                        + event.toString());
                                switch (event.getState()) {
                                case SyncConnected: {
                                }
                                    break;
                                case Expired: {
                                    queue.put("");
                                }
                                    break;
                                case Disconnected: {
                                }
                                    break;
                                }
                            }
                        } catch (InterruptedException e) {
                            throw new Error(e);
                        }
                    }
                };

                logger.info("Checking path " + DYNAMIC_PARAM_PATH + " exists");
                if (client.checkExists().forPath(DYNAMIC_PARAM_PATH) == null) {
                    logger.warn("Path " + DYNAMIC_PARAM_PATH + " does not exist for client " + clientName
                            + " creating...");
                    client.create().forPath(DYNAMIC_PARAM_PATH);
                }

                logger.info("Checking path " + AB_ALG_PATH + " exists");
                if (client.checkExists().forPath(AB_ALG_PATH) == null) {
                    logger.warn("Path " + AB_ALG_PATH + " does not exist for client " + clientName
                            + " creating...");
                    client.create().forPath(AB_ALG_PATH);
                }

                client.getData().usingWatcher(watcher).forPath(DYNAMIC_PARAM_PATH);
                client.getData().usingWatcher(watcher).forPath(AB_ALG_PATH);

                boolean restart = false;
                while (keepRunning && !restart) {

                    String path = queue.take();
                    if (!StringUtils.isEmpty(path)) {
                        logger.info("Alg Path changed " + path);

                        System.out.println("Alg Path changed " + path);

                        if (path.endsWith(DYNAMIC_PARAM_PATH)) {
                            try {
                                byte[] bytes = client.getData().forPath(DYNAMIC_PARAM_PATH);
                                ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
                                DynamicParameterBean bean = (DynamicParameterBean) in.readObject();
                                in.close();
                                logger.info("Updating dynamic parameter: " + bean.getName()
                                        + " and setting to value: " + bean.getValue() + " for client "
                                        + clientName);
                                DynamicParameterServer.setParameterBean(clientName, bean);
                                numUpdates++;
                            } catch (ClassNotFoundException e) {
                                logger.error("Can't find class ", e);
                            } catch (IOException e) {
                                logger.error("Failed to deserialize algorithm for client " + clientName, e);
                            } finally {
                                client.getData().usingWatcher(watcher).forPath(DYNAMIC_PARAM_PATH);
                            }

                        } else if (path.endsWith(AB_ALG_PATH)) {
                            try {
                                byte[] bytes = client.getData().forPath(AB_ALG_PATH);

                                ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
                                ABTest abTest = (ABTest) in.readObject();
                                in.close();
                                logger.info("Updating Algorithm percentage for client " + clientName + " to "
                                        + abTest.toString());
                                ABTestingServer.setABTest(clientName, abTest);
                                numUpdates++;
                            } catch (ClassNotFoundException e) {
                                logger.error("Can't find class ", e);
                            } catch (IOException e) {
                                logger.error("Failed to deserialize algorithm for client " + clientName, e);
                            } finally {
                                client.getData().usingWatcher(watcher).forPath(AB_ALG_PATH);
                            }
                        } else {
                            logger.error("Unknown path " + path + " changed so reseting watchers");
                        }
                    } else {
                        //client.getData().usingWatcher(watcher).forPath(DYNAMIC_PARAM_PATH);
                        //client.getData().usingWatcher(watcher).forPath(AB_ALG_PATH);
                        logger.warn("Will try to restart");
                        restart = true;
                    }

                }

            } catch (IOException e) {
                logger.error("Exception trying to create sk client ", e);
                error = true;
            } catch (Exception e) {
                logger.error("Exception from zookeeper client ", e);
                error = true;
            } finally {

            }

            if (keepRunning && error) {
                logger.info("Sleeping " + sleepTime);
                Thread.sleep(sleepTime);
                if (sleepTime * 2 < maxSleepTime)
                    sleepTime = sleepTime * 2;
                error = false;
            }

        }
    } catch (InterruptedException e) {
        logger.warn("Sleep interuppted ", e);
    }
    logger.info("Stopping");
}

From source file:io.seldon.api.state.ZkAlgorithmUpdater.java

License:Apache License

@Override
public void run() {
    logger.info("Starting");
    try {//from ww w  .ja  v  a  2s .  com
        boolean error = false;
        while (keepRunning) {
            try {

                CuratorFramework client = null;
                boolean ok = false;
                for (int attempts = 0; attempts < 4 && !ok; attempts++) {
                    client = curatorHandler.getCurator().usingNamespace(clientName);
                    logger.info("Waiting until zookeeper connected on attempt " + attempts);
                    ok = client.getZookeeperClient().blockUntilConnectedOrTimedOut();
                    if (ok)
                        logger.info("zookeeper connected");
                    else {
                        logger.error("Timed out waiting for zookeeper connect : attempt " + attempts);
                    }
                }
                if (!ok) {
                    logger.error("Failed to connect to zookeeper after multiple attempts - STOPPING");
                    return;
                }
                queue = new LinkedBlockingQueue<>();
                final Watcher watcher = new Watcher() {
                    boolean expired = false;

                    @Override
                    public void process(WatchedEvent event) {
                        try {
                            if (event.getPath() != null)
                                queue.put(event.getPath());
                            else {
                                logger.warn("Unexpected event " + event.getType().name() + " -> "
                                        + event.toString());
                                switch (event.getState()) {
                                case SyncConnected: {
                                }
                                    break;
                                case Expired: {
                                    queue.put("");
                                }
                                    break;
                                case Disconnected: {
                                    logger.warn("Disconnected from server");
                                    //queue.put("");                                      
                                }
                                    break;
                                }

                            }
                        } catch (InterruptedException e) {
                            throw new Error(e);
                        }
                    }
                };

                logger.info("Checking path " + ALG_PATH + " exists");
                if (client.checkExists().forPath(ALG_PATH) == null) {
                    logger.warn(
                            "Path " + ALG_PATH + " does not exist for client " + clientName + " creating...");
                    client.create().forPath(ALG_PATH);
                } else
                    logger.info("Path " + ALG_PATH + " exists");

                //client.getConnectionStateListenable().addListener(stateListener);
                boolean restart = false;
                while (keepRunning && !restart) {

                    client.getData().usingWatcher(watcher).forPath(ALG_PATH);

                    String path = queue.take();
                    if (!StringUtils.isEmpty(path)) {
                        logger.info("Alg Path changed " + path);

                        byte[] bytes = client.getData().forPath(ALG_PATH);

                        try {
                            ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
                            CFAlgorithm alg = (CFAlgorithm) in.readObject();
                            in.close();
                            //Update Algorithm for client
                            logger.info(
                                    "Updating algorithm options for " + clientName + " to " + alg.toString());
                            Util.getAlgorithmService().setAlgorithmOptions(clientName, alg);
                            numUpdates++;
                        } catch (ClassNotFoundException e) {
                            logger.error("Can't find class ", e);
                        } catch (IOException e) {
                            logger.error("Failed to deserialize algorithm for client " + clientName, e);
                        }
                    } else {
                        //logger.warn("Empty path - maybe zookeeper connection state change watcher will be reset");
                        logger.warn("Will try to restart");
                        restart = true;
                    }
                }

            } catch (IOException e) {
                logger.error("Exception trying to create sk client ", e);
                error = true;
            } catch (Exception e) {
                logger.error("Exception from zookeeper client ", e);
                error = true;
            } finally {

            }

            if (keepRunning && error) {
                logger.info("Sleeping " + sleepTime);
                Thread.sleep(sleepTime);
                if (sleepTime * 2 < maxSleepTime)
                    sleepTime = sleepTime * 2;
                error = false;
            }

        }
    } catch (InterruptedException e) {
        logger.warn("Sleep interuppted ", e);
    }
    logger.info("Stopping");
}

From source file:lab.examples.zookeeper.demo.ZooKeeperConnector.java

License:Apache License

public void init() throws Exception {
    if (hosts == null) {
        throw new IllegalArgumentException(
                "No hosts set for the ZookeeperConnector. Zookeeper connection cannot be created.");
    }//  ww w  .j av a 2s  .c o m

    zooKeeper = new ZooKeeper(hosts, // ZooKeeper service hosts
            15000, // Session timeout in milliseconds                
            new Watcher() { // Anonymous Watcher Object
                @Override
                public void process(WatchedEvent event) {
                    // release lock if ZooKeeper is connected.
                    if (event.getState() == KeeperState.SyncConnected) {
                        connectedSignal.countDown();
                    }
                }
            });
    connectedSignal.await();
}

From source file:majordodo.replication.SimpleZKBrokerLocatorWithSupplierTest.java

License:Apache License

@Override
protected BrokerLocator createBrokerLocator() throws Exception {

    suppliedClient = new ZooKeeper(zkEnv.getAddress(), zkEnv.getTimeout(), new Watcher() {

        @Override/*from ww  w. j a va 2 s .  c o  m*/
        public void process(WatchedEvent event) {

        }
    });
    return new ZKBrokerLocator(() -> suppliedClient, zkEnv.getPath());

}

From source file:mazewar.Mazewar.java

License:Open Source License

/**
 * The place where all the pieces are put together.
 *///from ww  w  .j a v  a2  s. c om
public Mazewar(String zkServer, int zkPort, int port, String name, String game, boolean robot) {
    super("ECE419 Mazewar");
    consolePrintLn("ECE419 Mazewar started!");

    /* Set up parent */
    ZK_PARENT += game;

    // Throw up a dialog to get the GUIClient name.
    if (name != null) {
        clientId = name;
    } else {
        clientId = JOptionPane.showInputDialog("Enter your name");
    }
    if ((clientId == null) || (clientId.length() == 0)) {
        Mazewar.quit();
    }

    /* Connect to ZooKeeper and get sequencer details */
    List<ClientNode> nodeList = null;
    try {
        zkWatcher = new ZkWatcher();
        zkConnected = new CountDownLatch(1);
        zooKeeper = new ZooKeeper(zkServer + ":" + zkPort, ZK_TIMEOUT, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                /* Release Lock if ZooKeeper is connected */
                if (event.getState() == SyncConnected) {
                    zkConnected.countDown();
                } else {
                    System.err.println("Could not connect to ZooKeeper!");
                    System.exit(0);
                }
            }
        });
        zkConnected.await();

        /* Successfully connected, now create our node on ZooKeeper */
        zooKeeper.create(Joiner.on('/').join(ZK_PARENT, clientId),
                Joiner.on(':').join(InetAddress.getLocalHost().getHostAddress(), port).getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);

        /* Get Seed from Parent */
        mazeSeed = Long.parseLong(new String(zooKeeper.getData(ZK_PARENT, false, null)));

        /* Initialize Sequence Number */
        sequenceNumber = new AtomicInteger(zooKeeper.exists(ZK_PARENT, false).getVersion());

        /* Get list of nodes */
        nodeList = ClientNode.sortList(zooKeeper.getChildren(ZK_PARENT, false));
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    // Create the maze
    maze = new MazeImpl(new Point(mazeWidth, mazeHeight), mazeSeed);
    assert (maze != null);

    // Have the ScoreTableModel listen to the maze to find
    // out how to adjust scores.
    ScoreTableModel scoreModel = new ScoreTableModel();
    assert (scoreModel != null);
    maze.addMazeListener(scoreModel);

    /* Initialize packet queue */
    packetQueue = new ArrayBlockingQueue<MazePacket>(QUEUE_SIZE);
    sequencedQueue = new PriorityBlockingQueue<MazePacket>(QUEUE_SIZE, new Comparator<MazePacket>() {
        @Override
        public int compare(MazePacket o1, MazePacket o2) {
            return o1.sequenceNumber.compareTo(o2.sequenceNumber);
        }
    });

    /* Inject Event Bus into Client */
    Client.setEventBus(eventBus);

    /* Initialize ZMQ Context */
    context = ZMQ.context(2);

    /* Set up publisher */
    publisher = context.socket(ZMQ.PUB);
    publisher.bind("tcp://*:" + port);
    System.out.println("ZeroMQ Publisher Bound On: " + port);

    try {
        Thread.sleep(100);
    } catch (Exception e) {
        e.printStackTrace();
    }

    /* Set up subscriber */
    subscriber = context.socket(ZMQ.SUB);
    subscriber.subscribe(ArrayUtils.EMPTY_BYTE_ARRAY);

    clients = new ConcurrentHashMap<String, Client>();
    try {
        for (ClientNode client : nodeList) {
            if (client.getName().equals(clientId)) {
                clientPath = ZK_PARENT + "/" + client.getPath();
                guiClient = robot ? new RobotClient(clientId) : new GUIClient(clientId);
                clients.put(clientId, guiClient);
                maze.addClient(guiClient);
                eventBus.register(guiClient);
                subscriber.connect("tcp://" + new String(zooKeeper.getData(clientPath, false, null)));
            } else {
                addRemoteClient(client);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    checkNotNull(guiClient, "Should have received our clientId in CLIENTS list!");

    // Create the GUIClient and connect it to the KeyListener queue
    this.addKeyListener(guiClient);
    this.isRobot = robot;

    // Use braces to force constructors not to be called at the beginning of the
    // constructor.
    /*{
    maze.addClient(new RobotClient("Norby"));
    maze.addClient(new RobotClient("Robbie"));
    maze.addClient(new RobotClient("Clango"));
    maze.addClient(new RobotClient("Marvin"));
    }*/

    // Create the panel that will display the maze.
    overheadPanel = new OverheadMazePanel(maze, guiClient);
    assert (overheadPanel != null);
    maze.addMazeListener(overheadPanel);

    // Don't allow editing the console from the GUI
    console.setEditable(false);
    console.setFocusable(false);
    console.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder()));

    // Allow the console to scroll by putting it in a scrollpane
    JScrollPane consoleScrollPane = new JScrollPane(console);
    assert (consoleScrollPane != null);
    consoleScrollPane
            .setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Console"));

    // Create the score table
    scoreTable = new JTable(scoreModel);
    assert (scoreTable != null);
    scoreTable.setFocusable(false);
    scoreTable.setRowSelectionAllowed(false);

    // Allow the score table to scroll too.
    JScrollPane scoreScrollPane = new JScrollPane(scoreTable);
    assert (scoreScrollPane != null);
    scoreScrollPane.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Scores"));

    // Create the layout manager
    GridBagLayout layout = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
    getContentPane().setLayout(layout);

    // Define the constraints on the components.
    c.fill = GridBagConstraints.BOTH;
    c.weightx = 1.0;
    c.weighty = 3.0;
    c.gridwidth = GridBagConstraints.REMAINDER;
    layout.setConstraints(overheadPanel, c);
    c.gridwidth = GridBagConstraints.RELATIVE;
    c.weightx = 2.0;
    c.weighty = 1.0;
    layout.setConstraints(consoleScrollPane, c);
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.weightx = 1.0;
    layout.setConstraints(scoreScrollPane, c);

    // Add the components
    getContentPane().add(overheadPanel);
    getContentPane().add(consoleScrollPane);
    getContentPane().add(scoreScrollPane);

    // Pack everything neatly.
    pack();

    // Let the magic begin.
    setVisible(true);
    overheadPanel.repaint();
    this.requestFocusInWindow();
}

From source file:msec.org.AccessZooKeeper.java

License:Open Source License

private void connectZooKeeper() {
    try {/*from ww  w  .  j ava 2 s .c  o  m*/
        zk = new ZooKeeper(connectStr, 5000, new Watcher() {
            @Override
            public void process(WatchedEvent event) {

                if (event.getState() == Event.KeeperState.SyncConnected) {
                    countDownLatch.countDown();
                }
            }
        });
        countDownLatch.await();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.killa.kept.KeptLock.java

License:Apache License

private boolean lockIt(long t, TimeUnit tu) throws KeeperException, InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);

    // convert the given time to milliseconds and add it to the current time
    long last = System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(t, tu);
    do {/*from w  ww . j a va 2 s.  com*/
        if (this.keeper.exists(this.znode, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                if (event.getType() == EventType.NodeDeleted)
                    latch.countDown();
                else if (event.getType() == EventType.NodeCreated)
                    ; // ignore it
                else
                    throw new RuntimeException("unexpected event type" + event.getType());
            }
        }) != null) {
            if (!latch.await(t, tu))
                try {
                    this.keeper.create(this.znode, ManagementFactory.getRuntimeMXBean().getName().getBytes(),
                            this.acl, CreateMode.EPHEMERAL);

                    return true;
                } catch (KeeperException.NodeExistsException e) {
                    // ignore it
                } catch (KeeperException e) {
                    throw e;
                }
            else
                return false;
        } else {
            try {
                this.keeper.create(this.znode, ManagementFactory.getRuntimeMXBean().getName().getBytes(),
                        this.acl, CreateMode.EPHEMERAL);

                return true;
            } catch (KeeperException.NodeExistsException e) {
                // ignore it
            } catch (KeeperException e) {
                throw e;
            }
        }
    } while (System.currentTimeMillis() < last);

    return false;
}

From source file:net.revelc.code.zookeeper.maven.plugin.StartZooKeeperMojo.java

License:Apache License

@Override
protected void runMojo() throws MojoExecutionException, MojoFailureException {
    parseConfig();//from   w  w  w.  ja  va  2  s  .c o m

    ProcessBuilder builder = new ProcessBuilder();
    builder.command().add(getJavaCommand());

    String classpath = getClasspath();
    getLog().warn(classpath);
    if (!classpath.isEmpty()) {
        builder.command().add("-cp");
        builder.command().add(classpath);
    }

    builder.command().add(ZooKeeperLauncher.class.getName());
    builder.command().add("--shutdownPort");
    builder.command().add(Integer.toString(shutdownPort));
    builder.command().add("--shutdownString");
    builder.command().add(shutdownString);

    String token = UUID.randomUUID().toString();
    builder.command().add("--token");
    builder.command().add(token);

    File zooCfgFile = createZooCfg();
    builder.command().add("--zoocfg");
    builder.command().add(zooCfgFile.getAbsolutePath());

    builder.directory(project.getBasedir());
    getLog().info("Starting ZooKeeper");

    Process forkedProcess = null;
    try {
        // merge stderr and stdout from child
        builder.redirectErrorStream(true);
        forkedProcess = builder.start();
        try (Scanner scanner = new Scanner(forkedProcess.getInputStream(), UTF_8.name())) {
            getLog().info("Waiting for ZooKeeper service to start...");
            int checklines = 50;
            boolean verifiedStart = false;
            while (scanner.hasNextLine() && checklines > 0) {
                String line = scanner.nextLine();
                getLog().debug("LINE: " + line);
                if (line.contains("Token: " + token)) {
                    verifiedStart = true;
                    break;
                }
                checklines--;
            }
            boolean canConnect = false;
            Watcher noopWatcher = new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                }
            };
            while (!canConnect) {
                ZooKeeper zk = null;
                try {
                    String address = clientPortAddress + ":" + clientPort;
                    getLog().info("Waiting for ZooKeeper on " + address + "...");
                    zk = new ZooKeeper(address, tickTime, noopWatcher);
                    zk.getChildren("/", false);
                    getLog().info("ZooKeeper is running on " + address + ".");
                    canConnect = true;
                } catch (Exception e) {
                    getLog().info("ZooKeeper not yet ready: " + e.getMessage());
                    getLog().debug("ZooKeeper not yet ready: " + e.getMessage(), e);
                } finally {
                    if (zk != null) {
                        try {
                            zk.close();
                        } catch (InterruptedException e) {
                            // don't care
                        }
                    }
                }
            }
            if (verifiedStart) {
                getLog().info("ZooKeeper service has started");
            } else {
                getLog().warn("Unable to verify ZooKeeper service started");
            }
        }
    } catch (IOException e) {
        throw new MojoFailureException("Unable to start process (or verify that it has started)", e);
    }
}

From source file:org.apache.accumulo.cloudtrace.instrument.receivers.ZooSpanClient.java

License:Apache License

public ZooSpanClient(String keepers, final String path, String host, String service, long millis)
        throws IOException, KeeperException, InterruptedException {
    super(host, service, millis);
    this.path = path;
    zoo = new ZooKeeper(keepers, 30 * 1000, new Watcher() {
        @Override//from  ww w.  j a  va  2  s. c  o m
        public void process(WatchedEvent event) {
            try {
                if (zoo != null) {
                    updateHosts(path, zoo.getChildren(path, null));
                }
            } catch (Exception ex) {
                log.error("unable to get destination hosts in zookeeper", ex);
            }
        }
    });
    for (int i = 0; i < TOTAL_TIME_WAIT_CONNECT_MS; i += TIME_WAIT_CONNECT_CHECK_MS) {
        if (zoo.getState().equals(States.CONNECTED))
            break;
        try {
            Thread.sleep(TIME_WAIT_CONNECT_CHECK_MS);
        } catch (InterruptedException ex) {
            break;
        }
    }
    zoo.getChildren(path, true);
}