Esempio n. 1
0
//  Worker using REQ socket to do load-balancing
//
static void *
worker_task(void *args)
{
	zctx_t *ctx = zctx_new();
	void *worker = zsocket_new(ctx, ZMQ_REQ);

#if (defined (WIN32))
	zsocket_connect(worker, "tcp://localhost:5673"); // backend
#else
	zsocket_connect(worker, "ipc://backend.ipc");
#endif

	//  Tell broker we're ready for work
	zframe_t *frame = zframe_new(WORKER_READY, strlen(WORKER_READY));
	zframe_send(&frame, worker, 0);

	//  Process messages as they arrive
	while (1) {
		zmsg_t *msg = zmsg_recv(worker);
		if (!msg)
			break;              //  Interrupted
		zframe_print(zmsg_last(msg), "Worker: ");
		zframe_reset(zmsg_last(msg), "OK", 2);
		zmsg_send(&msg, worker);
	}
	zctx_destroy(&ctx);
	return NULL;
}
Esempio n. 2
0
static void* 
worker_routine(void* arg)
{
  zmsg_t* msg;
  zframe_t* frame;
  zctx_t* ctx = zctx_new();
  void* worker = zsocket_new(ctx, ZMQ_REQ);
  zsocket_connect(worker, "ipc://%s-localbe.ipc", self);

  frame = zframe_new(WORKER_READY, 1);
  zframe_send(&frame, worker, 0);

  while (1) {
    msg = zmsg_recv(worker);
    if (!msg)
      break;

    zframe_print(zmsg_last(msg), "Worker: ");
    zframe_reset(zmsg_last(msg), "OK", 2);
    zmsg_send(&msg, worker);
  }

  zctx_destroy(&ctx);
  return NULL;
}
Esempio n. 3
0
static void
s_broker_client_msg(broker_t *self, zframe_t *sender, zmsg_t *msg)
{
	assert(zmsg_size(msg) >= 2);

	zframe_t *service_frame = zmsg_pop(msg);
	service_t *service = s_service_require(self, service_frame);

	zmsg_wrap(msg, zframe_dup(sender));

	if (zframe_size(service_frame) >= 4 && memcmp(zframe_data(service_frame), "mmi.", 4) == 0){
		char *return_code;
		if (zframe_streq(service_frame, "mmi.service")){
			char *name = zframe_strdup(zmsg_last(msg));
			service_t *service = (service_t *)zhash_lookup(self->services, name);
			return_code = service && service->workers ? "200" : "404";
			free(name);
		}
		else
			return_code = "501";

		zframe_reset(zmsg_last(msg), return_code, strlen(return_code));

		zframe_t *client = zmsg_unwrap(msg);
		zmsg_prepend(msg, &service_frame);
		zmsg_pushstr(msg, MDPC_CLIENT);
		zmsg_wrap(msg, client);
		zmsg_send(&msg, self->socket);
	}
	else 
		s_service_dispatch(service, msg);
	zframe_destroy(&service_frame);
}
Esempio n. 4
0
File: broker.c Progetto: tnako/DP
static void s_broker_client_msg(broker_t *self, zframe_t *sender, zmsg_t *msg)
{
    assert (zmsg_size(msg) >= 2);     //  Service name + body

    zframe_t *service_frame = zmsg_pop(msg);
    service_t *service = s_service_require(self, service_frame);
 // Не должен создавать сервис, в случаи запроса от клиента

    //  Set reply return identity to client sender
    zmsg_wrap(msg, zframe_dup(sender));

    //  If we got a MMI service request, process that internally
    if (zframe_size(service_frame) >= 4 &&  memcmp(zframe_data(service_frame), "mmi.", 4) == 0) {
        char *return_code;
		
        if (zframe_streq(service_frame, "mmi.service")) {
            char *name = zframe_strdup (zmsg_last (msg));
            service_t *service = (service_t *) zhash_lookup(self->services, name);
			if (service) {
			  if (service->workers) {
				return_code = "200";
			  } else {
				return_code = "404";
			  }
			} else {
			  return_code = "401";
			}
            free(name);
        } else {
            return_code = "501";
		}

        zframe_reset(zmsg_last(msg), return_code, strlen(return_code));

        //  Remove & save client return envelope and insert the
        //  protocol header and service name, then rewrap envelope.
        zframe_t *client = zmsg_unwrap (msg);
        zmsg_push(msg, zframe_dup(service_frame));
        zmsg_pushstr(msg, MDPC_CLIENT);
        zmsg_wrap(msg, client);
        zmsg_send(&msg, self->socket);
    } else {
        //  Else dispatch the message to the requested service
        s_service_dispatch(service, msg);
	}
	
    zframe_destroy(&service_frame);
}
Esempio n. 5
0
int main (int argc, char *argv [])
{
    int verbose = (argc > 1 && streq (argv [1], "-v"));
    mdcli_t *session = mdcli_new ("tcp://localhost:5555", verbose);
	zmsg_t *request;
	zmsg_t *reply;
    int count;

    //for (count = 0; count < 1; count++) {
        request = zmsg_new ();
        zmsg_pushstr (request, "KILL");
        reply = mdcli_send (session, "echo", &request);
        if (reply)
		{
			zframe_t * lastFrame = zmsg_last(reply);
			char* msg = zframe_strdup(lastFrame);
			printf("msg:%s\n", msg);
			printf("size:%d\n", zmsg_content_size(reply));
			//zframe_print(lastFrame,"->");
			zmsg_destroy (&reply);
		}
        //else
        //    break;              //  Interrupt or failure
    //}
    //printf ("%d requests/replies processed\n", count);
    mdcli_destroy (&session);
    return 0;
}
Esempio n. 6
0
static void *
client_task (void *args)
{
    zctx_t *ctx = zctx_new ();
    void *client = zsocket_new (ctx, ZMQ_DEALER);

    //  Set random identity to make tracing easier
    char identity [10];
    sprintf (identity, "%04X-%04X", randof (0x10000), randof (0x10000));
    zsocket_set_identity (client, identity);
    zsocket_connect (client, "tcp://localhost:5570");

    zmq_pollitem_t items [] = { { client, 0, ZMQ_POLLIN, 0 } };
    int request_nbr = 0;
    while (true) {
        //  Tick once per second, pulling in arriving messages
        int centitick;
        for (centitick = 0; centitick < 100; centitick++) {
            zmq_poll (items, 1, 10 * ZMQ_POLL_MSEC);
            if (items [0].revents & ZMQ_POLLIN) {
                zmsg_t *msg = zmsg_recv (client);
                zframe_print (zmsg_last (msg), identity);
                zmsg_destroy (&msg);
            }
        }
        zstr_send (client, "request #%d");
    }
    zctx_destroy (&ctx);
    return NULL;
}
Esempio n. 7
0
int main(int argc, char const * const *argv)
{
  int rc;

  zctx_t *context = zctx_new();
  assert(context);
  zctx_set_rcvhwm(context, 1000);
  zctx_set_linger(context, 100);

  void *socket = zsocket_new(context, ZMQ_PULL);
  assert(socket);

  zsocket_set_rcvhwm(socket, 100000);
  zsocket_set_linger(socket, 500);
  zsocket_set_reconnect_ivl(socket, 100); // 100 ms
  zsocket_set_reconnect_ivl_max(socket, 10 * 1000); // 10 s

  const char* host = "localhost";
  if (argc>1) host = argv[1];

  rc = zsocket_connect(socket, "tcp://%s:9651", host);
  assert(rc==0);

  zmsg_t *msg = NULL;

  size_t received = 0;
  size_t lost = 0;
  size_t last_num = 0;
  while (1) {
    msg = zmsg_recv(socket);
    if (zsys_interrupted)
      break;
    assert(msg);
    received++;
    // assert(zmsg_size(msg) == 3);
    // zmsg_dump(msg);
    zframe_t *last_frame = zmsg_last(msg);
    char *str = zframe_strdup(last_frame);
    size_t n = atol(str);
    free(str);
    if (n > last_num + 1 && last_num != 0) {
        lost += n - (last_num + 1);
    }
    last_num = n;
    zmsg_destroy(&msg);
  }

  zsocket_destroy(context, socket);
  zctx_destroy(&context);

  printf("\nlost:     %7zu\nreceived: %7zu\n", lost, received);

  return 0;
}
Esempio n. 8
0
int main (int argc, char *argv [])
{
	zmsg_t *reply = 0;
	mdwrk_t *session = 0;
	zframe_t * lastFrame = 0;
	char* lastMsg = 0;

    int verbose = (argc > 1 && streq (argv [1], "-v"));
	//if (argc = 2 && !streq (argv [1], "-v"))
	//{
	//	session = mdwrk_new ("tcp://localhost:5555", argv[1], verbose);
	//}
	//else if (argc = 3 && !streq (argv [2], ""))
	//{
	//	session = mdwrk_new ("tcp://localhost:5555", argv[2], verbose);
	//}
	//else
	//{
		session = mdwrk_new ("tcp://localhost:5555", "echo", verbose);
	//}
	if (!session) return 1;
	
    while (true) {
        zmsg_t *request = mdwrk_recv (session, &reply);
        if (request == NULL) break;              //  Worker was interrupted

		////////////////////////////////////加入自己的雷达逻辑//////////////////////////////////

		//解析收到的信息
		lastFrame = zmsg_last(request);
		lastMsg = zframe_strdup(lastFrame);

		printf("zmsg_t::msg:%s\n", lastMsg);
		printf("zmsg_t::size:%d\n", zmsg_content_size(request));

		//
		//
		//
		//

		//建立回复信息
		reply = zmsg_new ();
		zmsg_pushstr (reply, "Done!");

		////////////////////////////////////////////////////////////////////////////////////////

		zmsg_destroy (&request);
        //reply = request;        //  Echo is complex... :-)
    }
    mdwrk_destroy (&session);
    return 0;
}
Esempio n. 9
0
void rrtask_manager_fn(void *args, zctx_t *ctx, void *pipe)
{
    rrwrk_t *self = (rrwrk_t *)args;

    zstr_send(pipe, "READY");

    while (true) {
        zmq_pollitem_t item = {pipe, 0, ZMQ_POLLIN, 0};
        int rc = zmq_poll(&item, 1, -1);
        if (rc == -1 && errno == ETERM)
            break;    //** Context has been shut down

        zmsg_t *msg;
        if (item.revents & ZMQ_POLLIN) {

            //** Receives task input from pipe
            msg = zmsg_recv(pipe);

            zframe_t *data_in = zmsg_last(msg);

            rrtask_data_t *input = rrtask_data_new();
            rrtask_set_data(input, zframe_data(data_in), zframe_size(data_in));

            //** User callback function to perform the task
            rrtask_data_t *output = self->cb(input);
            zframe_t *data_out = zframe_new(output->data, output->len);

            //** Removes input data from message and destroy it
            zmsg_remove(msg, data_in);
            zframe_destroy(&data_in);

            //** Adds output data to the message and send it to pipe
            zmsg_add(msg, data_out);
            zmsg_send(&msg, pipe);

            //** Destroys task input and output data
            rrtask_data_destroy(&input);
            rrtask_data_destroy(&output);

            zmsg_destroy(&msg);
        }

        if (zctx_interrupted) {
            printf("I am destroying this message.\n");
            zmsg_destroy(&msg);
            break;
        }
    }
}
Esempio n. 10
0
static void
s_service_internal (broker_t *self, zframe_t *service_frame, zmsg_t *msg)
{
    char *return_code;
    if (zframe_streq (service_frame, "mmi.service")) {
        char *name = zframe_strdup (zmsg_last (msg));
        service_t *service =
            (service_t *) zhash_lookup (self->services, name);
        return_code = service && service->workers? "200": "404";
        free (name);
    }
    else
        return_code = "501";

    zframe_reset (zmsg_last (msg), return_code, strlen (return_code));

    //  Remove & save client return envelope and insert the
    //  protocol header and service name, then rewrap envelope.
    zframe_t *client = zmsg_unwrap (msg);
    zmsg_push (msg, zframe_dup (service_frame));
    zmsg_pushstr (msg, MDPC_CLIENT);
    zmsg_wrap (msg, client);
    zmsg_send (&msg, self->socket);
}
Esempio n. 11
0
static void *
worker_task (void *args)
{
    zctx_t *ctx = zctx_new ();
    void *worker = zsocket_new (ctx, ZMQ_REQ);
    zsocket_connect (worker, "ipc://%s-localbe.ipc", self);

    //  Tell broker we're ready for work
    zframe_t *frame = zframe_new (WORKER_READY, 1);
    zframe_send (&frame, worker, 0);

    //  Process messages as they arrive
    while (true) {
        zmsg_t *msg = zmsg_recv (worker);
        if (!msg)
            break;              //  Interrupted

        zframe_print (zmsg_last (msg), "Worker: ");
        zframe_reset (zmsg_last (msg), "OK", 2);
        zmsg_send (&msg, worker);
    }
    zctx_destroy (&ctx);
    return NULL;
}
Esempio n. 12
0
int main (int argc, char *argv [])
{
    int verbose = (argc > 1 && streq (argv [1], "-v"));
    mdcli_t *session = mdcli_new ("tcp://localhost:5555", verbose);

    //  1. Send 'echo' request to Titanic
    zmsg_t *request = zmsg_new ();
    zmsg_addstr (request, "echo");
    zmsg_addstr (request, "Hello world");
    zmsg_t *reply = s_service_call (
        session, "titanic.request", &request);

    zframe_t *uuid = NULL;
    if (reply) {
        uuid = zmsg_pop (reply);
        zmsg_destroy (&reply);
        zframe_print (uuid, "I: request UUID ");
    }
    //  2. Wait until we get a reply
    while (!zctx_interrupted) {
        zclock_sleep (100);
        request = zmsg_new ();
        zmsg_add (request, zframe_dup (uuid));
        zmsg_t *reply = s_service_call (
            session, "titanic.reply", &request);

        if (reply) {
            char *reply_string = zframe_strdup (zmsg_last (reply));
            printf ("Reply: %s\n", reply_string);
            free (reply_string);
            zmsg_destroy (&reply);

            //  3. Close request
            request = zmsg_new ();
            zmsg_add (request, zframe_dup (uuid));
            reply = s_service_call (session, "titanic.close", &request);
            zmsg_destroy (&reply);
            break;
        }
        else {
            printf ("I: no reply yet, trying again...\n");
            zclock_sleep (5000);     //  Try again in 5 seconds
        }
    }
    zframe_destroy (&uuid);
    mdcli_destroy (&session);
    return 0;
}
Esempio n. 13
0
/**
 * gpp_worker_set_task_done:
 * @self: A #GPPWorker.
 * @reply: (allow-none): A string that will be passed to the client.
 * @success: Whether the task was successfully handled.
 *
 * Call this function when your worker has finished handling a task.
 *
 * Returns: %TRUE if the task was marked as done, %FALSE otherwise.
 */
gboolean
gpp_worker_set_task_done (GPPWorker *self, const gchar *reply, gboolean success)
{
  GPPWorkerPrivate *priv = GET_PRIV (self);
  zframe_t *request_frame = zmsg_last (priv->current_task);

  if (!priv->current_task)
    return FALSE;

  if (!success) {
    zframe_reset (request_frame, PPP_KO, 1);
  } else {
    zframe_reset (request_frame, reply, strlen (reply) + 1);
  }

  zmsg_send (&priv->current_task, priv->frontend);
  priv->current_task = NULL;
  check_socket_activity (priv->frontend_channel, G_IO_IN, self);
  return TRUE;
}
Esempio n. 14
0
static void
handle_frontend (GPPWorker *self)
{
  GPPWorkerPrivate *priv = GET_PRIV (self);
  GPPWorkerClass *klass = GPP_WORKER_GET_CLASS (self);
  zmsg_t *msg = zmsg_recv (priv->frontend);
  if (!msg)
    return;

  if (zmsg_size (msg) == 3) {
    char *request = zframe_strdup (zmsg_last (msg));
    g_info ("I: normal reply\n");
    priv->liveness = HEARTBEAT_LIVENESS;
    priv->current_task = msg;
    if (!klass->handle_request (self, request))
      gpp_worker_set_task_done (self, NULL, FALSE);
    free (request);
  } else {
    if (zmsg_size (msg) == 1) {
      zframe_t *frame = zmsg_first (msg);
      if (memcmp (zframe_data (frame), PPP_HEARTBEAT, 1) == 0) {
        priv->liveness = HEARTBEAT_LIVENESS;
        g_debug ("got heartbeat from queue !\n");
      } else {
        g_warning ("E: invalid message\n");
        zmsg_dump (msg);
      }
      zmsg_destroy (&msg);
    }
    else {
      g_warning ("E: invalid message\n");
      zmsg_dump (msg);
    }
  }
  priv->interval = INTERVAL_INIT;
}
Esempio n. 15
0
zmsg_t* PrimeWorker::ReceiveRequest(proto::Request& req, void* socket) {
	
	zmsg_t* msg = zmsg_recv(socket);
	zframe_t* frame = zmsg_last(msg);
	zmsg_remove(msg, frame);
	size_t fsize = zframe_size(frame);
	const byte* fbytes = zframe_data(frame);
	
	bool ok = req.ParseFromArray(fbytes, fsize);
	zframe_destroy(&frame);
	
	bool valid = false;
	while(ok){
		
		if(!proto::Request::Type_IsValid(req.type()))
			break;
		
		if(!req.has_reqnonce())
			break;
		
		if(CheckVersion(req.version()) <= 0)
			break;
		
		uint256 reqnonce;
		{
			const std::string& nonce = req.reqnonce();
			if(nonce.length() != sizeof(uint256))
				break;
			memcpy(reqnonce.begin(), nonce.c_str(), sizeof(uint256));
		}
		
		if(!CheckReqNonce(reqnonce) || !mReqNonces.insert(reqnonce).second)
			break;
		
		if(req.has_stats()){
			
			const proto::ClientStats& stats = req.stats();
			if(!isValidUTF8(stats.addr()))
				break;
			if(!isValidUTF8(stats.name()))
				break;
			if(stats.cpd() < 0 || stats.cpd() > 150. || stats.cpd() != stats.cpd())
				break;
			
		}
		
		if(req.has_share()){
			
			const proto::Share& share = req.share();
			if(!isValidUTF8(share.addr()))
				break;
			if(!isValidUTF8(share.name()))
				break;
			if(!isValidUTF8(share.hash()))
				break;
			if(!isValidUTF8(share.merkle()))
				break;
			if(!isValidUTF8(share.multi()))
				break;
			if(share.has_blockhash() && !isValidUTF8(share.blockhash()))
				break;
			
		}
		
		valid = true;
		break;
	}
	
	if(valid)
		return msg;
	else{
		mInvCount++;
		zmsg_destroy(&msg);
		return 0;
	}
	
}
Esempio n. 16
0
void
zmsg_test (bool verbose)
{
    printf (" * zmsg: ");

    int rc = 0;
    //  @selftest
    //  Create two PAIR sockets and connect over inproc
    zsock_t *output = zsock_new_pair ("@inproc://zmsg.test");
    assert (output);
    zsock_t *input = zsock_new_pair (">inproc://zmsg.test");
    assert (input);

    //  Test send and receive of single-frame message
    zmsg_t *msg = zmsg_new ();
    assert (msg);
    zframe_t *frame = zframe_new ("Hello", 5);
    assert (frame);
    zmsg_prepend (msg, &frame);
    assert (zmsg_size (msg) == 1);
    assert (zmsg_content_size (msg) == 5);
    rc = zmsg_send (&msg, output);
    assert (msg == NULL);
    assert (rc == 0);

    msg = zmsg_recv (input);
    assert (msg);
    assert (zmsg_size (msg) == 1);
    assert (zmsg_content_size (msg) == 5);
    zmsg_destroy (&msg);

    //  Test send and receive of multi-frame message
    msg = zmsg_new ();
    assert (msg);
    rc = zmsg_addmem (msg, "Frame0", 6);
    assert (rc == 0);
    rc = zmsg_addmem (msg, "Frame1", 6);
    assert (rc == 0);
    rc = zmsg_addmem (msg, "Frame2", 6);
    assert (rc == 0);
    rc = zmsg_addmem (msg, "Frame3", 6);
    assert (rc == 0);
    rc = zmsg_addmem (msg, "Frame4", 6);
    assert (rc == 0);
    rc = zmsg_addmem (msg, "Frame5", 6);
    assert (rc == 0);
    rc = zmsg_addmem (msg, "Frame6", 6);
    assert (rc == 0);
    rc = zmsg_addmem (msg, "Frame7", 6);
    assert (rc == 0);
    rc = zmsg_addmem (msg, "Frame8", 6);
    assert (rc == 0);
    rc = zmsg_addmem (msg, "Frame9", 6);
    assert (rc == 0);
    zmsg_t *copy = zmsg_dup (msg);
    assert (copy);
    rc = zmsg_send (&copy, output);
    assert (rc == 0);
    rc = zmsg_send (&msg, output);
    assert (rc == 0);

    copy = zmsg_recv (input);
    assert (copy);
    assert (zmsg_size (copy) == 10);
    assert (zmsg_content_size (copy) == 60);
    zmsg_destroy (&copy);

    msg = zmsg_recv (input);
    assert (msg);
    assert (zmsg_size (msg) == 10);
    assert (zmsg_content_size (msg) == 60);

    // create empty file for null test
    FILE *file = fopen ("zmsg.test", "w");
    assert (file);
    fclose (file);

    file = fopen ("zmsg.test", "r");
    zmsg_t *null_msg = zmsg_load (NULL, file);
    assert (null_msg == NULL);
    fclose (file);
    remove ("zmsg.test");

    //  Save to a file, read back
    file = fopen ("zmsg.test", "w");
    assert (file);
    rc = zmsg_save (msg, file);
    assert (rc == 0);
    fclose (file);

    file = fopen ("zmsg.test", "r");
    rc = zmsg_save (msg, file);
    assert (rc == -1);
    fclose (file);
    zmsg_destroy (&msg);

    file = fopen ("zmsg.test", "r");
    msg = zmsg_load (NULL, file);
    assert (msg);
    fclose (file);
    remove ("zmsg.test");
    assert (zmsg_size (msg) == 10);
    assert (zmsg_content_size (msg) == 60);

    //  Remove all frames except first and last
    int frame_nbr;
    for (frame_nbr = 0; frame_nbr < 8; frame_nbr++) {
        zmsg_first (msg);
        frame = zmsg_next (msg);
        zmsg_remove (msg, frame);
        zframe_destroy (&frame);
    }
    //  Test message frame manipulation
    assert (zmsg_size (msg) == 2);
    frame = zmsg_last (msg);
    assert (zframe_streq (frame, "Frame9"));
    assert (zmsg_content_size (msg) == 12);
    frame = zframe_new ("Address", 7);
    assert (frame);
    zmsg_prepend (msg, &frame);
    assert (zmsg_size (msg) == 3);
    rc = zmsg_addstr (msg, "Body");
    assert (rc == 0);
    assert (zmsg_size (msg) == 4);
    frame = zmsg_pop (msg);
    zframe_destroy (&frame);
    assert (zmsg_size (msg) == 3);
    char *body = zmsg_popstr (msg);
    assert (streq (body, "Frame0"));
    free (body);
    zmsg_destroy (&msg);

    //  Test encoding/decoding
    msg = zmsg_new ();
    assert (msg);
    byte *blank = (byte *) zmalloc (100000);
    assert (blank);
    rc = zmsg_addmem (msg, blank, 0);
    assert (rc == 0);
    rc = zmsg_addmem (msg, blank, 1);
    assert (rc == 0);
    rc = zmsg_addmem (msg, blank, 253);
    assert (rc == 0);
    rc = zmsg_addmem (msg, blank, 254);
    assert (rc == 0);
    rc = zmsg_addmem (msg, blank, 255);
    assert (rc == 0);
    rc = zmsg_addmem (msg, blank, 256);
    assert (rc == 0);
    rc = zmsg_addmem (msg, blank, 65535);
    assert (rc == 0);
    rc = zmsg_addmem (msg, blank, 65536);
    assert (rc == 0);
    rc = zmsg_addmem (msg, blank, 65537);
    assert (rc == 0);
    free (blank);
    assert (zmsg_size (msg) == 9);
    byte *buffer;
    size_t buffer_size = zmsg_encode (msg, &buffer);
    zmsg_destroy (&msg);
    msg = zmsg_decode (buffer, buffer_size);
    assert (msg);
    free (buffer);
    zmsg_destroy (&msg);

    //  Test submessages
    msg = zmsg_new ();
    assert (msg);
    zmsg_t *submsg = zmsg_new ();
    zmsg_pushstr (msg, "matr");
    zmsg_pushstr (submsg, "joska");
    rc = zmsg_addmsg (msg, &submsg);
    assert (rc == 0);
    assert (submsg == NULL);
    submsg = zmsg_popmsg (msg);
    assert (submsg == NULL);   // string "matr" is not encoded zmsg_t, so was discarded
    submsg = zmsg_popmsg (msg);
    assert (submsg);
    body = zmsg_popstr (submsg);
    assert (streq (body, "joska"));
    free (body);
    zmsg_destroy (&submsg);
    frame = zmsg_pop (msg);
    assert (frame == NULL);
    zmsg_destroy (&msg);

    //  Test comparison of two messages
    msg = zmsg_new ();
    zmsg_addstr (msg, "One");
    zmsg_addstr (msg, "Two");
    zmsg_addstr (msg, "Three");
    zmsg_t *msg_other = zmsg_new ();
    zmsg_addstr (msg_other, "One");
    zmsg_addstr (msg_other, "Two");
    zmsg_addstr (msg_other, "One-Hundred");
    zmsg_t *msg_dup = zmsg_dup (msg);
    zmsg_t *empty_msg = zmsg_new ();
    zmsg_t *empty_msg_2 = zmsg_new ();
    assert (zmsg_eq (msg, msg_dup));
    assert (!zmsg_eq (msg, msg_other));
    assert (zmsg_eq (empty_msg, empty_msg_2));
    assert (!zmsg_eq (msg, NULL));
    assert (!zmsg_eq (NULL, empty_msg));
    assert (!zmsg_eq (NULL, NULL));
    zmsg_destroy (&msg);
    zmsg_destroy (&msg_other);
    zmsg_destroy (&msg_dup);
    zmsg_destroy (&empty_msg);
    zmsg_destroy (&empty_msg_2);

    //  Test signal messages
    msg = zmsg_new_signal (0);
    assert (zmsg_signal (msg) == 0);
    zmsg_destroy (&msg);
    msg = zmsg_new_signal (-1);
    assert (zmsg_signal (msg) == 255);
    zmsg_destroy (&msg);

    //  Now try methods on an empty message
    msg = zmsg_new ();
    assert (msg);
    assert (zmsg_size (msg) == 0);
    assert (zmsg_unwrap (msg) == NULL);
    assert (zmsg_first (msg) == NULL);
    assert (zmsg_last (msg) == NULL);
    assert (zmsg_next (msg) == NULL);
    assert (zmsg_pop (msg) == NULL);
    //  Sending an empty message is valid and destroys the message
    assert (zmsg_send (&msg, output) == 0);
    assert (!msg);

    zsock_destroy (&input);
    zsock_destroy (&output);

    //  @end
    printf ("OK\n");
}
Esempio n. 17
0
void
curve_server_test (bool verbose)
{
    printf (" * curve_server: ");

    //  @selftest
    //  Create temporary directory for test files
    srand (time (NULL));
    zsys_dir_create (TESTDIR);
    
    zcert_t *server_cert = zcert_new ();
    zcert_save (server_cert, TESTDIR "/server.cert");

    //  Install the authenticator
    zctx_t *ctx = zctx_new ();
    zauth_t *auth = zauth_new (ctx);
    assert (auth);
    zauth_set_verbose (auth, verbose);
    zauth_configure_curve (auth, "*", TESTDIR);

    //  We'll run a set of clients as background tasks, and the
    //  server in this foreground thread. Don't pass verbose to
    //  the clients as the results are unreadable.
    int live_clients;
    for (live_clients = 0; live_clients < 5; live_clients++)
        zthread_new (client_task, &verbose);

    curve_server_t *server = curve_server_new (ctx, &server_cert);
    curve_server_set_verbose (server, verbose);
    curve_server_bind (server, "tcp://127.0.0.1:9006");
    
    while (live_clients > 0) {
        zmsg_t *msg = curve_server_recv (server);
        if (memcmp (zframe_data (zmsg_last (msg)), "END", 3) == 0)
            live_clients--;
        curve_server_send (server, &msg);
    }

    //  Try an invalid client/server combination
    byte bad_server_key [32] = { 0 };
    zcert_t *unknown = zcert_new ();
    curve_client_t *client = curve_client_new (&unknown);
    curve_client_set_verbose (client, true);
    curve_client_connect (client, "tcp://127.0.0.1:9006", bad_server_key);
    curve_client_sendstr (client, "Hello, World");

    //  Expect no reply after 250msec
    zmq_pollitem_t pollitems [] = {
        { curve_client_handle (client), 0, ZMQ_POLLIN, 0 }
    };
    assert (zmq_poll (pollitems, 1, 250) == 0);
    curve_client_destroy (&client);

    //  Delete all test files
    zdir_t *dir = zdir_new (TESTDIR, NULL);
    zdir_remove (dir, true);
    zdir_destroy (&dir);

    curve_server_destroy (&server);
    zauth_destroy (&auth);
    zctx_destroy (&ctx);
    //  @end
   
    //  Ensure client threads have exited before we do
    zclock_sleep (100);
    printf ("OK\n");
}
Esempio n. 18
0
File: qzmq.c Progetto: jaeheum/qzmq
Z K1(zmsglast){PC(x); P(zmsg_size(VSK(x))>0, ptr(zmsg_last(VSK(x)))); R krr("empty");}
Esempio n. 19
0
int main(int argc, char **argv) {

    /* SETUP */
    
    // logging
    setlogmask(LOG_UPTO(LOG_DEBUG));
    openlog(PROGRAM_NAME, LOG_CONS | LOG_PID | LOG_PERROR, LOG_USER);
    syslog(LOG_INFO, "worker starting up");
    
    // load transit data from disk
    tdata_t tdata;
    tdata_load(RRRR_INPUT_FILE, &tdata);
    
    // initialize router
    router_t router;
    router_setup(&router, &tdata);
    //tdata_dump(&tdata); // debug timetable file format
    
    // establish zmq connection
    zctx_t *zctx = zctx_new ();
    void *zsock = zsocket_new(zctx, ZMQ_REQ);
    uint32_t zrc = zsocket_connect(zsock, WORKER_ENDPOINT);
    if (zrc != 0) exit(1);
    
    // signal to the broker/load balancer that this worker is ready
    zframe_t *frame = zframe_new (WORKER_READY, 1);
    zframe_send (&frame, zsock, 0);
    syslog(LOG_INFO, "worker sent ready message to load balancer");

    /* MAIN LOOP */
    uint32_t request_count = 0;
    char result_buf[OUTPUT_LEN];
    while (true) {
        zmsg_t *msg = zmsg_recv (zsock);
        if (!msg) // interrupted (signal)
            break; 
        if (++request_count % 100 == 0)
            syslog(LOG_INFO, "worker received %d requests\n", request_count);
        // only manipulate the last frame, then send the recycled message back to the broker
        zframe_t *frame = zmsg_last (msg);
        if (zframe_size (frame) == sizeof (router_request_t)) {
            router_request_t *preq;
            preq = (router_request_t*) zframe_data (frame);
            router_request_t req = *preq; // protective copy, since we're going to reverse it
            D printf ("Searching with request: \n");
            I router_request_dump (&router, &req);
            router_route (&router, &req);
            // repeat search in reverse to compact transfers
            uint32_t n_reversals = req.arrive_by ? 1 : 2;
            //n_reversals = 0; // DEBUG turn off reversals
            for (uint32_t i = 0; i < n_reversals; ++i) {
                router_request_reverse (&router, &req); // handle case where route is not reversed
                D printf ("Repeating search with reversed request: \n");
                D router_request_dump (&router, &req);
                router_route (&router, &req);
            }
            // uint32_t result_length = router_result_dump(&router, &req, result_buf, OUTPUT_LEN);
            struct plan plan;
            router_result_to_plan (&plan, &router, &req);
            plan.req.time = preq->time; // restore the original request time
            uint32_t result_length = render_plan_json (&plan, router.tdata, result_buf, OUTPUT_LEN);

            zframe_reset (frame, result_buf, result_length);
        } else {
            syslog (LOG_WARNING, "worker received reqeust with wrong length");
            zframe_reset (frame, "ERR", 3);
        }
        // send response to broker, thereby requesting more work
        zmsg_send (&msg, zsock);
    }
    
    /* TEAR DOWN */
    syslog(LOG_INFO, "worker terminating");
    // frame = zframe_new (WORKER_LEAVING, 1);
    // zframe_send (&frame, zmq_sock, 0);
    // syslog(LOG_INFO, "departure message sent to load balancer");
    // zmsg_t *msg = zmsg_recv (zmq_sock);
    router_teardown(&router);
    tdata_close(&tdata);
    zctx_destroy (&zctx); //zmq_close(socket) necessary before context destroy?
    exit(EXIT_SUCCESS);
}
Esempio n. 20
0
static void
s_broker_client_msg (broker_t *self, zframe_t *sender, zmsg_t *msg)
{
    assert (zmsg_size (msg) >= 2);     //  Service name + body

    zframe_t *service_frame = zmsg_pop (msg);
    service_t *service = s_service_require (self, service_frame);

    //  If we got a MMI service request, process that internally
    if (zframe_size (service_frame) >= 4
    &&  memcmp (zframe_data (service_frame), "mmi.", 4) == 0) {
        char *return_code;
        if (zframe_streq (service_frame, "mmi.service")) {
            char *name = zframe_strdup (zmsg_last (msg));
            service_t *service =
                (service_t *) zhash_lookup (self->services, name);
            return_code = service && service->workers? "200": "404";
            free (name);
        }
        else
        // The filter service that can be used to manipulate
        // the command filter table.
        if (zframe_streq (service_frame, "mmi.filter")
        && zmsg_size (msg) == 3) {
            zframe_t *operation = zmsg_pop (msg);
            zframe_t *service_frame = zmsg_pop (msg);
            zframe_t *command_frame = zmsg_pop (msg);
            char *command_str = zframe_strdup (command_frame);

            if (zframe_streq (operation, "enable")) {
                service_t *service = s_service_require (self, service_frame);
                s_service_enable_command (service, command_str);
                return_code = "200";
            }
            else
            if (zframe_streq (operation, "disable")) {
                service_t *service = s_service_require (self, service_frame);
                s_service_disable_command (service, command_str);
                return_code = "200";
            }
            else
                return_code = "400";

            zframe_destroy (&operation);
            zframe_destroy (&service_frame);
            zframe_destroy (&command_frame);
            free (command_str);
            //  Add an empty frame; it will be replaced by the return code.
            zmsg_pushstr (msg, "");
        }
        else
            return_code = "501";

        zframe_reset (zmsg_last (msg), return_code, strlen (return_code));

        //  Insert the protocol header and service name, then rewrap envelope.
        zmsg_push (msg, zframe_dup (service_frame));
        zmsg_pushstr (msg, MDPC_REPORT);
        zmsg_pushstr (msg, MDPC_CLIENT);
        zmsg_wrap (msg, zframe_dup (sender));
        zmsg_send (&msg, self->socket);
    }
    else {
        int enabled = 1;
        if (zmsg_size (msg) >= 1) {
            zframe_t *cmd_frame = zmsg_first (msg);
            char *cmd = zframe_strdup (cmd_frame);
            enabled = s_service_is_command_enabled (service, cmd);
            free (cmd);
        }

        //  Forward the message to the worker.
        if (enabled) {
            zmsg_wrap (msg, zframe_dup (sender));
            zlist_append (service->requests, msg);
            s_service_dispatch (service);
        }
        //  Send a NAK message back to the client.
        else {
            zmsg_push (msg, zframe_dup (service_frame));
            zmsg_pushstr (msg, MDPC_NAK);
            zmsg_pushstr (msg, MDPC_CLIENT);
            zmsg_wrap (msg, zframe_dup (sender));
            zmsg_send (&msg, self->socket);
        }
    }

    zframe_destroy (&service_frame);
}
Esempio n. 21
0
///
//  Return the last frame. If there are no frames, returns NULL.
QmlZframe *QmlZmsg::last () {
    QmlZframe *retQ_ = new QmlZframe ();
    retQ_->self = zmsg_last (self);
    return retQ_;
};
Esempio n. 22
0
///
//  Return the last frame. If there are no frames, returns NULL.
QZframe * QZmsg::last ()
{
    QZframe *rv = new QZframe (zmsg_last (self));
    return rv;
}