Examples of ZContext


Examples of org.zeromq.ZContext

    {
        if (args.length < 1) {
            System.out.printf("I: syntax: flserver2 <endpoint>\n");
            System.exit(0);
        }
        ZContext ctx = new ZContext();
        Socket server = ctx.createSocket(ZMQ.REP);
        server.bind(args[0]);

        System.out.printf ("I: echo service is ready at %s\n", args[0]);
        while (true) {
            ZMsg request = ZMsg.recvMsg(server);
            if (request == null)
                break;          //  Interrupted

            //  Fail nastily if run against wrong client
            assert (request.size() == 2);

            ZFrame identity = request.pop();
            request.destroy();

            ZMsg reply = new ZMsg();
            reply.add(identity);
            reply.add("OK");
            reply.send(server);
        }
        if (Thread.currentThread().isInterrupted())
            System.out.printf ("W: interrupted\n");

        ctx.destroy();
    }
View Full Code Here

Examples of org.zeromq.ZContext

public class clonesrv3 {
    private static Map<String, kvsimple> kvMap = new LinkedHashMap<String, kvsimple>();

    public void run() {

        ZContext ctx = new ZContext();

        Socket snapshot = ctx.createSocket(ZMQ.ROUTER);
        snapshot.bind("tcp://*:5556");

        Socket publisher = ctx.createSocket(ZMQ.PUB);
        publisher.bind("tcp://*:5557");

        Socket collector = ctx.createSocket(ZMQ.PULL);
        collector.bind("tcp://*:5558");

        Poller poller = new Poller(2);
        poller.register(collector, Poller.POLLIN);
        poller.register(snapshot, Poller.POLLIN);

        long sequence = 0;
        while (!Thread.currentThread().isInterrupted()) {
            if (poller.poll(1000) < 0)
                break;              //  Context has been shut down

            // apply state updates from main thread
            if (poller.pollin(0)) {
                kvsimple kvMsg = kvsimple.recv(collector);
                if (kvMsg == null//  Interrupted
                    break;
                kvMsg.setSequence(++sequence);
                kvMsg.send(publisher);
                clonesrv3.kvMap.put(kvMsg.getKey(), kvMsg);
                System.out.printf("I: publishing update %5d\n", sequence);
            }

            // execute state snapshot request
            if (poller.pollin(1)) {
                byte[] identity = snapshot.recv(0);
                if (identity == null)
                    break;      //  Interrupted
                String request = snapshot.recvStr();

                if (!request.equals("ICANHAZ?")) {
                    System.out.println("E: bad request, aborting");
                    break;
                }

                Iterator<Entry<String, kvsimple>> iter = kvMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Entry<String, kvsimple> entry = iter.next();
                    kvsimple msg = entry.getValue();
                    System.out.println("Sending message " + entry.getValue().getSequence());
                    this.sendMessage(msg, identity, snapshot);
                }

                // now send end message with sequence number
                System.out.println("Sending state snapshot = " + sequence);
                snapshot.send(identity, ZMQ.SNDMORE);
                kvsimple message = new kvsimple("KTHXBAI", sequence, "".getBytes());
                message.send(snapshot);
            }
        }
        System.out.printf (" Interrupted\n%d messages handled\n", sequence);
        ctx.destroy();
    }
View Full Code Here

Examples of org.zeromq.ZContext

        }
        self = argv[0];
        System.out.printf("I: preparing broker at %s\n", self);
        Random rand = new Random(System.nanoTime());

        ZContext ctx = new ZContext();

        //  Prepare local frontend and backend
        Socket localfe = ctx.createSocket(ZMQ.ROUTER);
        localfe.bind(String.format("ipc://%s-localfe.ipc", self));
        Socket localbe = ctx.createSocket(ZMQ.ROUTER);
        localbe.bind(String.format("ipc://%s-localbe.ipc", self));


        //  Bind cloud frontend to endpoint
        Socket cloudfe = ctx.createSocket(ZMQ.ROUTER);
        cloudfe.setIdentity(self.getBytes());
        cloudfe.bind(String.format("ipc://%s-cloud.ipc", self));

        //  Connect cloud backend to all peers
        Socket cloudbe = ctx.createSocket(ZMQ.ROUTER);
        cloudbe.setIdentity(self.getBytes());
        int argn;
        for (argn = 1; argn < argv.length; argn++) {
            String peer = argv[argn];
            System.out.printf("I: connecting to cloud forintend at '%s'\n", peer);
            cloudbe.connect(String.format("ipc://%s-cloud.ipc", peer));
        }

        //  Bind state backend to endpoint
        Socket statebe = ctx.createSocket(ZMQ.PUB);
        statebe.bind(String.format("ipc://%s-state.ipc", self));

        //  Connect statefe to all peers
        Socket statefe = ctx.createSocket(ZMQ.SUB);
        statefe.subscribe("".getBytes());
        for (argn = 1; argn < argv.length; argn++) {
            String peer = argv[argn];
            System.out.printf("I: connecting to state backend at '%s'\n", peer);
            statefe.connect(String.format("ipc://%s-state.ipc", peer));
        }

        //  Prepare monitor socket
        Socket monitor = ctx.createSocket(ZMQ.PULL);
        monitor.bind(String.format("ipc://%s-monitor.ipc", self));

        //  Start local workers
        int worker_nbr;
        for (worker_nbr = 0; worker_nbr < NBR_WORKERS; worker_nbr++)
            new worker_task().start();

        //  Start local clients
        int client_nbr;
        for (client_nbr = 0; client_nbr < NBR_CLIENTS; client_nbr++)
            new client_task().start();

        //  Queue of available workers
        int localCapacity = 0;
        int cloudCapacity = 0;
        ArrayList<ZFrame> workers = new ArrayList<ZFrame>();

        //  The main loop has two parts. First we poll workers and our two service
        //  sockets (statefe and monitor), in any case. If we have no ready workers,
        //  there's no point in looking at incoming requests. These can remain on
        //  their internal 0MQ queues:

        while (true) {
            //  First, route any waiting replies from workers
            PollItem primary[] = {
                    new PollItem(localbe, Poller.POLLIN),
                    new PollItem(cloudbe, Poller.POLLIN),
                    new PollItem(statefe, Poller.POLLIN),
                    new PollItem(monitor, Poller.POLLIN)
            };
            //  If we have no workers anyhow, wait indefinitely
            int rc = ZMQ.poll(primary,
                    localCapacity > 0 ? 1000 : -1);
            if (rc == -1)
                break;              //  Interrupted

            //  Track if capacity changes during this iteration
            int previous = localCapacity;


            //  Handle reply from local worker
            ZMsg msg = null;
            if (primary[0].isReadable()) {
                msg = ZMsg.recvMsg(localbe);
                if (msg == null)
                    break;          //  Interrupted
                ZFrame address = msg.unwrap();
                workers.add(address);
                localCapacity++;

                //  If it's READY, don't route the message any further
                ZFrame frame = msg.getFirst();
                if (new String(frame.getData()).equals(WORKER_READY)) {
                    msg.destroy();
                    msg = null;
                }
            }
            //  Or handle reply from peer broker
            else if (primary[1].isReadable()) {
                msg = ZMsg.recvMsg(cloudbe);
                if (msg == null)
                    break;          //  Interrupted
                //  We don't use peer broker address for anything
                ZFrame address = msg.unwrap();
                address.destroy();
            }
            //  Route reply to cloud if it's addressed to a broker
            for (argn = 1; msg != null && argn < argv.length; argn++) {
                byte[] data = msg.getFirst().getData();
                if (argv[argn].equals(new String(data))) {
                    msg.send(cloudfe);
                    msg = null;
                }
            }
            //  Route reply to client if we still need to
            if (msg != null)
                msg.send(localfe);

            //  If we have input messages on our statefe or monitor sockets we
            //  can process these immediately:

            if (primary[2].isReadable()) {
                String peer = statefe.recvStr();
                String status = statefe.recvStr();
                cloudCapacity = Integer.parseInt(status);
            }
            if (primary[3].isReadable()) {
                String status = monitor.recvStr();
                System.out.println(status);
            }

            //  Now we route as many client requests as we have worker capacity
            //  for. We may reroute requests from our local frontend, but not from //
            //  the cloud frontend. We reroute randomly now, just to test things
            //  out. In the next version we'll do this properly by calculating
            //  cloud capacity://

            while (localCapacity + cloudCapacity > 0) {
                PollItem secondary[] = {
                        new PollItem(localfe, Poller.POLLIN),
                        new PollItem(cloudfe, Poller.POLLIN)
                };

                if (localCapacity > 0)
                    rc = ZMQ.poll(secondary, 2, 0);
                else
                    rc = ZMQ.poll(secondary, 1, 0);

                assert (rc >= 0);

                if (secondary[0].isReadable()) {
                    msg = ZMsg.recvMsg(localfe);
                } else if (secondary[1].isReadable()) {
                    msg = ZMsg.recvMsg(cloudfe);
                } else
                    break;      //  No work, go back to backends

                if (localCapacity > 0) {
                    ZFrame frame = workers.remove(0);
                    msg.wrap(frame);
                    msg.send(localbe);
                    localCapacity--;

                } else {
                    //  Route to random broker peer
                    int random_peer = rand.nextInt(argv.length - 1) + 1;
                    msg.push(argv[random_peer]);
                    msg.send(cloudbe);
                }
            }

            //  We broadcast capacity messages to other peers; to reduce chatter
            //  we do this only if our capacity changed.

            if (localCapacity != previous) {
                //  We stick our own address onto the envelope
                statebe.sendMore(self);
                //  Broadcast new capacity
                statebe.send(String.format("%d", localCapacity), 0);
            }
        }
        //  When we're done, clean up properly
        while (workers.size() > 0) {
            ZFrame frame = workers.remove(0);
            frame.destroy();
        }

        ctx.destroy();
    }
View Full Code Here

Examples of org.zeromq.ZContext

    private static class client_task extends Thread
    {
        @Override
        public void run()
        {
            ZContext ctx = new ZContext();
            Socket client = ctx.createSocket(ZMQ.REQ);
            client.connect(String.format("ipc://%s-localfe.ipc", self));
            Socket monitor = ctx.createSocket(ZMQ.PUSH);
            monitor.connect(String.format("ipc://%s-monitor.ipc", self));
            Random rand = new Random(System.nanoTime());

            while (true) {

                try {
                    Thread.sleep(rand.nextInt(5) * 1000);
                } catch (InterruptedException e1) {
                }
                int burst = rand.nextInt(15);

                while (burst > 0) {
                    String taskId = String.format("%04X", rand.nextInt(10000));
                    //  Send request, get reply
                    client.send(taskId, 0);

                    //  Wait max ten seconds for a reply, then complain
                    PollItem pollSet[] = {new PollItem(client, Poller.POLLIN)};
                    int rc = ZMQ.poll(pollSet, 10 * 1000);
                    if (rc == -1)
                        break;          //  Interrupted

                    if (pollSet[0].isReadable()) {
                        String reply = client.recvStr(0);
                        if (reply == null)
                            break;              //  Interrupted
                        //  Worker is supposed to answer us with our task id
                        assert (reply.equals(taskId));
                        monitor.send(String.format("%s", reply), 0);
                    } else {
                        monitor.send(
                                String.format("E: CLIENT EXIT - lost task %s", taskId), 0);
                        ctx.destroy();
                        return;
                    }
                    burst--;
                }
            }
View Full Code Here

Examples of org.zeromq.ZContext

    {
        @Override
        public void run()
        {
            Random rand = new Random(System.nanoTime());
            ZContext ctx = new ZContext();
            Socket worker = ctx.createSocket(ZMQ.REQ);
            worker.connect(String.format("ipc://%s-localbe.ipc", self));

            //  Tell broker we're ready for work
            ZFrame frame = new ZFrame(WORKER_READY);
            frame.send(worker, 0);

            while (true) {
                //  Send request, get reply
                ZMsg msg = ZMsg.recvMsg(worker, 0);
                if (msg == null)
                    break;              //  Interrupted

                //  Workers are busy for 0/1 seconds
                try {
                    Thread.sleep(rand.nextInt(2) * 1000);
                } catch (InterruptedException e) {
                }

                msg.send(worker);

            }
            ctx.destroy();
        }
View Full Code Here

Examples of org.zeromq.ZContext

*
*/
public class clonesrv2 {

  public void run() {
    ZContext ctx = new ZContext();
    Socket publisher = ctx.createSocket(ZMQ.PUB);
    publisher.bind("tcp://*:5557");

    Socket updates = ZThread.fork(ctx, new StateManager());

    Random random = new Random();
        long sequence = 0;
    while (!Thread.currentThread().isInterrupted()) {
      long currentSequenceNumber = ++sequence;
      int key = random.nextInt(10000);
      int body = random.nextInt(1000000);

      ByteBuffer b = ByteBuffer.allocate(4);
      b.asIntBuffer().put(body);

      kvsimple kvMsg = new kvsimple(key + "", currentSequenceNumber, b.array());
      kvMsg.send(publisher);
      kvMsg.send(updates); // send a message to State Manager thead.

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }

        }
        System.out.printf(" Interrupted\n%d messages out\n", sequence);

        ctx.destroy();
  }
View Full Code Here

Examples of org.zeromq.ZContext

    //  Paranoid Pirate Protocol (PPP). The interesting parts here are
    //  the heartbeating, which lets the worker detect if the queue has
    //  died, and vice-versa:
   
    public static void main(String[] args) {
        ZContext ctx = new ZContext ();
        Socket worker = worker_socket (ctx);

        //  If liveness hits zero, queue is considered disconnected
        int liveness = HEARTBEAT_LIVENESS;
        int interval = INTERVAL_INIT;

        //  Send out heartbeats at regular intervals
        long heartbeat_at = System.currentTimeMillis() + HEARTBEAT_INTERVAL;

        Random rand = new Random(System.nanoTime());
        int cycles = 0;
        while (true) {
            PollItem items [] = { new PollItem( worker,  ZMQ.Poller.POLLIN ) };
            int rc = ZMQ.poll (items, HEARTBEAT_INTERVAL );
            if (rc == -1)
                break;              //  Interrupted

            if (items [0].isReadable()) {
                //  Get message
                //  - 3-part envelope + content -> request
                //  - 1-part HEARTBEAT -> heartbeat
                ZMsg msg = ZMsg.recvMsg(worker);
                if (msg == null)
                    break;          //  Interrupted

                //  To test the robustness of the queue implementation we //
                //  simulate various typical problems, such as the worker
                //  crashing, or running very slowly. We do this after a few
                //  cycles so that the architecture can get up and running
                //  first:
                if (msg.size() == 3) {
                    cycles++;
                    if (cycles > 3 && rand.nextInt(5) == 0) {
                        System.out.println ("I: simulating a crash\n");
                        msg.destroy();
                        msg = null;
                        break;
                    }
                    else
                    if (cycles > 3 && rand.nextInt (5) == 0) {
                        System.out.println ("I: simulating CPU overload\n");
                        try {
                            Thread.sleep (3000);
                        } catch (InterruptedException e) {
                            break;
                        }
                    }
                    System.out.println ("I: normal reply\n");
                    msg.send( worker);
                    liveness = HEARTBEAT_LIVENESS;
                    try {
                        Thread.sleep (1000);
                    } catch (InterruptedException e) {
                        break;
                    }              //  Do some heavy work
                }
                else
                //  When we get a heartbeat message from the queue, it means the
                //  queue was (recently) alive, so reset our liveness indicator:
                if (msg.size() == 1) {
                    ZFrame frame = msg.getFirst();
                    if (PPP_HEARTBEAT.equals(new String(frame.getData())))
                        liveness = HEARTBEAT_LIVENESS;
                    else {
                        System.out.println ("E: invalid message\n");
                        msg.dump(System.out);
                    }
                    msg.destroy();
                }
                else {
                    System.out.println ("E: invalid message\n");
                    msg.dump(System.out);
                }
                interval = INTERVAL_INIT;
            }
            else
            //  If the queue hasn't sent us heartbeats in a while, destroy the
            //  socket and reconnect. This is the simplest most brutal way of
            //  discarding any messages we might have sent in the meantime://
            if (--liveness == 0) {
                System.out.println ("W: heartbeat failure, can't reach queue\n");
                System.out.println (String.format("W: reconnecting in %zd msec\n", interval));
                try {
                    Thread.sleep(interval);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if (interval < INTERVAL_MAX)
                    interval *= 2;
                ctx.destroySocket(worker);
                worker = worker_socket (ctx);
                liveness = HEARTBEAT_LIVENESS;
            }

            //  Send heartbeat to queue if it's time
            if (System.currentTimeMillis() > heartbeat_at) {
                heartbeat_at = System.currentTimeMillis() + HEARTBEAT_INTERVAL;
                System.out.println ("I: worker heartbeat\n");
                ZFrame frame = new ZFrame (PPP_HEARTBEAT);
                frame.send(worker, 0);
            }
        }
        ctx.destroy();
    }
View Full Code Here

Examples of org.zeromq.ZContext

    //  Here are the constructor and destructor for the clone class. Note that
    //  we create a context specifically for the pipe that connects our
    //  frontend to the backend agent:
    public clone()
    {
        ctx = new ZContext();
        pipe = ZThread.fork(ctx, new CloneAgent());
    }
View Full Code Here

Examples of org.zeromq.ZContext

        }
        String self = argv[0];
        System.out.println(String.format("I: preparing broker at %s\n", self));
        Random rand = new Random(System.nanoTime());

        ZContext ctx = new ZContext();

        //  Bind state backend to endpoint
        Socket statebe = ctx.createSocket(ZMQ.PUB);
        statebe.bind(String.format("ipc://%s-state.ipc", self));

        //  Connect statefe to all peers
        Socket statefe = ctx.createSocket(ZMQ.SUB);
        statefe.subscribe("".getBytes());
        int argn;
        for (argn = 1; argn < argv.length; argn++) {
            String peer = argv[argn];
            System.out.printf("I: connecting to state backend at '%s'\n", peer);
            statefe.connect(String.format("ipc://%s-state.ipc", peer));
        }
        //  The main loop sends out status messages to peers, and collects
        //  status messages back from peers. The zmq_poll timeout defines
        //  our own heartbeat:

        while (true) {
            //  Poll for activity, or 1 second timeout
            PollItem items[] = {new PollItem(statefe, Poller.POLLIN)};
            int rc = ZMQ.poll(items, 1000);
            if (rc == -1)
                break;              //  Interrupted

            //  Handle incoming status messages
            if (items[0].isReadable()) {
                String peer_name = new String(statefe.recv(0));
                String available = new String(statefe.recv(0));
                System.out.printf("%s - %s workers free\n", peer_name, available);
            } else {
                //  Send random values for worker availability
                statebe.send(self, ZMQ.SNDMORE);
                statebe.send(String.format("%d", rand.nextInt(10)), 0);
            }
        }
        ctx.destroy();
    }
View Full Code Here

Examples of org.zeromq.ZContext

    public void test(boolean verbose)
    {
        System.out.printf(" * kvmsg: ");

        //  Prepare our context and sockets
        ZContext ctx = new ZContext();
        Socket output = ctx.createSocket(ZMQ.DEALER);
        output.bind("ipc://kvmsg_selftest.ipc");
        Socket input = ctx.createSocket(ZMQ.DEALER);
        input.connect("ipc://kvmsg_selftest.ipc");

        Map<String,kvmsg> kvmap = new HashMap<String, kvmsg>();

        //  .until
        //  Test send and receive of simple message
        kvmsg kvmsg = new kvmsg(1);
        kvmsg.setKey("getKey");
        kvmsg.setUUID();
        kvmsg.setBody("body".getBytes());
        if (verbose)
            kvmsg.dump();
        kvmsg.send(output);
        kvmsg.store(kvmap);

        kvmsg = kvmsg.recv(input);
        if (verbose)
            kvmsg.dump();
        assert (kvmsg.getKey().equals("getKey"));
        kvmsg.store(kvmap);

        //  Test send and receive of message with properties
        kvmsg = new kvmsg(2);
        kvmsg.setProp("prop1", "value1");
        kvmsg.setProp("prop2", "value1");
        kvmsg.setProp("prop2", "value2");
        kvmsg.setKey("getKey");
        kvmsg.setUUID();
        kvmsg.setBody("body".getBytes());
        assert (kvmsg.getProp("prop2").equals("value2"));
        if (verbose)
            kvmsg.dump();
        kvmsg.send(output);
        kvmsg.destroy();

        kvmsg = kvmsg.recv(input);
        if (verbose)
            kvmsg.dump();
        assert (kvmsg.key.equals("getKey"));
        assert (kvmsg.getProp("prop2").equals("value2"));
        kvmsg.destroy();

        //  .skip
        //  Shutdown and destroy all objects
        ctx.destroy();

        System.out.printf("OK\n");

    }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.