Exemple #1
1
zmsg_t *
zmsg_load (zmsg_t *self, FILE *file)
{
    assert (file);
    if (!self)
        self = zmsg_new ();
    if (!self)
        return NULL;

    while (true) {
        size_t frame_size;
        size_t rc = fread (&frame_size, sizeof (frame_size), 1, file);
        if (rc == 1) {
            zframe_t *frame = zframe_new (NULL, frame_size);
            rc = fread (zframe_data (frame), frame_size, 1, file);
            if (frame_size > 0 && rc != 1) {
                zframe_destroy (&frame);
                break;          //  Unable to read properly, quit
            }
            zmsg_append (self, &frame);
        }
        else
            break;              //  Unable to read properly, quit
    }
    if (!zmsg_size (self)) {
        zmsg_destroy (&self);
        self = NULL;
    }
    return self;
}
Exemple #2
0
static int
s_agent_handle_data (agent_t *self)
{
    //  First frame is client address (hashkey)
    //  If caller sends unknown client address, we discard the message
    //  For testing, we'll abort in this case, since it cannot happen
    //  The assert disappears when we start to timeout clients...
    zmsg_t *request = zmsg_recv (self->data);
    char *hashkey = zmsg_popstr (request);
    client_t *client = (client_t *) zhash_lookup (self->clients, hashkey);
    free (hashkey);
    if (client) {
        //  Encrypt and send all frames of request
        //  Each frame is a full ZMQ message with identity frame
        while (zmsg_size (request)) {
            zframe_t *cleartext = zmsg_pop (request);
            if (zmsg_size (request))
                zframe_set_more (cleartext, 1);
            zframe_t *encrypted = curve_codec_encode (client->codec, &cleartext);
            if (encrypted) {
                zframe_send (&client->address, self->router, ZFRAME_MORE + ZFRAME_REUSE);
                zframe_send (&encrypted, self->router, 0);
            }
            else
                client_set_exception (client);
        }
    }
    zmsg_destroy (&request);
    return 0;
}
Exemple #3
0
int get_request(zsock_t *sock, struct request *req) {
    zmsg_t *msg;
    int size;
    char *str;
    int Y, m, d, H, M, S;
    struct tm tm;

    msg = zmsg_recv(sock);
    size = zmsg_size(msg);
    if (size != 2) {
        // something's wrong
        zmsg_destroy(&msg);
        return -1;
    }

    str = zmsg_popstr(msg);
    req->ip = inet_addr(str);

    str = zmsg_popstr(msg);
    sscanf(str, "%04d%02d%02d%02d%02d%02d", &Y, &m, &d, &H, &M, &S);
    tm.tm_year = Y - 1900;
    tm.tm_mon = m;
    tm.tm_mday = d;
    tm.tm_hour = H;
    tm.tm_min = M;
    tm.tm_sec = S;
    req->timestamp = mktime(&tm);

    zmsg_destroy(&msg);
    return 0;
}
Exemple #4
0
static void s_broker_worker_msg(broker_t *self, zframe_t *sender, zmsg_t *msg)
{
    assert (zmsg_size(msg) >= 1);     //  At least, command

    zframe_t *command = zmsg_pop(msg);
    char *id_string = zframe_strhex(sender);
    int worker_ready = (zhash_lookup(self->workers, id_string) != NULL);
    free (id_string);
	
    worker_t *worker = s_worker_require(self, sender);

    if (zframe_streq(command, MDPW_READY)) {
        if (worker_ready) {               //  Not first command in session
            s_worker_delete(worker, 1);
			// Додумать, по идеи синоним сердцебиения
		} else {
			if (zframe_size(sender) >= 4 &&  memcmp(zframe_data (sender), "mmi.", 4) == 0) {
				s_worker_delete(worker, 1);
				// Додумать, по идеи синоним сердцебиения
			} else {
				//  Attach worker to service and mark as idle
				zframe_t *service_frame = zmsg_pop(msg);
				worker->service = s_service_require(self, service_frame);
				worker->service->workers++;
				s_worker_waiting(worker);
				zframe_destroy(&service_frame);
			}
		}
    } else if (zframe_streq(command, MDPW_REPLY)) {
        if (worker_ready) {
            //  Remove and save client return envelope and insert the
            //  protocol header and service name, then rewrap envelope.
            zframe_t *client = zmsg_unwrap(msg);
            zmsg_pushstr(msg, worker->service->name);
            zmsg_pushstr(msg, MDPC_CLIENT);
            zmsg_wrap(msg, client);
            zmsg_send(&msg, self->socket);
            s_worker_waiting(worker);
        } else {
			// Просто обрыв связи между воркером и брокером
			// синоним сердцебиения
            s_worker_delete(worker, 1);
		}
    } else if (zframe_streq(command, MDPW_HEARTBEAT)) {
        if (worker_ready) {
            worker->expiry = zclock_time () + HEARTBEAT_EXPIRY;
		} else {
			// Просто обрыв связи между воркером и брокером
			// синоним сердцебиения
            s_worker_delete(worker, 1);
		}
    } else if (zframe_streq (command, MDPW_DISCONNECT)) {
        s_worker_delete(worker, 0);
	} else {
        zclock_log ("E: invalid input message");
        zmsg_dump (msg);
    }
    free (command);
    zmsg_destroy (&msg);
}
Exemple #5
0
int
zsock_wait (void *self)
{
    assert (self);

    //  A signal is a message containing one frame with our 8-byte magic 
    //  value. If we get anything else, we discard it and continue to look
    //  for the signal message
    while (true) {
        zmsg_t *msg = zmsg_recv (self);
        if (!msg)
            return -1;
        if (zmsg_size (msg) == 1
        &&  zmsg_content_size (msg) == 8) {
            zframe_t *frame = zmsg_first (msg);
            int64_t signal_value = *((int64_t *) zframe_data (frame));
            if ((signal_value & 0xFFFFFFFFFFFFFF00L) == 0x7766554433221100L) {
                zmsg_destroy (&msg);
                return signal_value & 255;
            }
        }
        zmsg_destroy (&msg);
    }
    return -1;
}
Exemple #6
0
static
int read_request_and_forward(zloop_t *loop, zsock_t *socket, void *callback_data)
{
    subscriber_state_t *state = callback_data;
    zmsg_t *msg = zmsg_recv(socket);
    if (msg) {
        state->message_count++;
        int n = zmsg_size(msg);
        if (n < 3 || n > 4) {
            fprintf(stderr, "[E] subscriber: (%s:%d): dropped invalid message of size %d\n", __FILE__, __LINE__, n);
            my_zmsg_fprint(msg, "[E] FRAME= ", stderr);
            return 0;
        }
        if (n == 4) {
            int is_heartbeat = process_meta_information_and_handle_heartbeat(state, msg);
            if (is_heartbeat) {
                zmsg_destroy(&msg);
                return 0;
            }
        }

        if (PUBLISH_DUPLICATES)
            subscriber_publish_duplicate(msg, state->pub_socket);

        if (!output_socket_ready(state->push_socket, 0) && !state->message_blocks++)
            fprintf(stderr, "[W] subscriber: push socket not ready. blocking!\n");

        int rc = zmsg_send_and_destroy(&msg, state->push_socket);
        if (rc) {
            if (!state->message_drops++)
                fprintf(stderr, "[E] subscriber: dropped message on push socket (%d: %s)\n", errno, zmq_strerror(errno));
        }
    }
    return 0;
}
Exemple #7
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);
}
Exemple #8
0
static void
s_engine_handle_request (engine_t *self, zmsg_t *request, zframe_t *reply_to)
{
    assert (zmsg_size (request) >= 3);

    zframe_t *operation = zmsg_pop (request);
    zframe_t *price     = zmsg_pop (request);
    zframe_t *volume    = zmsg_pop (request);

    if (zframe_streq (operation, "SELL"))
        s_engine_handle_sell_request (self, price, volume, reply_to);
    else
    if (zframe_streq (operation, "BUY"))
        s_engine_handle_buy_request (self, price, volume, reply_to);
    else {
        zclock_log ("E: invalid message: ");
        zmsg_dump (request);
    }

    zframe_destroy (&operation);
    zframe_destroy (&price);
    zframe_destroy (&volume);

    zmsg_destroy (&request);
}
Exemple #9
0
/**
 * 
 * @param foundId
 * @param foundReply
 * @return 
 */
bool BoomStick::ReadFromReadySocket(std::string& foundId, std::string& foundReply) {
   if (0 == mUtilizedThread) {
      mUtilizedThread = pthread_self();
   } else {
      CHECK(pthread_self() == mUtilizedThread);
   }
   if (!mChamber) {
      LOG(WARNING) << "Invalid socket";
      return false;
   }
   bool success = false;
   zmsg_t* msg = zmsg_recv(mChamber);
   if (!msg) {
      foundReply = zmq_strerror(zmq_errno());
   } else if (zmsg_size(msg) == 2) {
      char* msgChar;
      msgChar = zmsg_popstr(msg);
      foundId = msgChar;
      free(msgChar);
      msgChar = zmsg_popstr(msg);
      foundReply = msgChar;
      free(msgChar);
      success = true;
   } else {
      foundReply = "Malformed reply, expecting 2 parts";
   }

   if (msg) {

      zmsg_destroy(&msg);
   }
   return success;
}
Exemple #10
0
static void
s_worker_process (broker_t *self, zframe_t *sender, zmsg_t *msg)
{
    assert (zmsg_size (msg) >= 1);     //  At least, command

    zframe_t *command = zmsg_pop (msg);
    char *identity = zframe_strhex (sender);
    int worker_ready = (zhash_lookup (self->workers, identity) != NULL);
    free (identity);
    worker_t *worker = s_worker_require (self, sender);

    if (zframe_streq (command, MDPW_READY)) {
        if (worker_ready)               //  Not first command in session
            s_worker_delete (self, worker, 1);
        else
        if (zframe_size (sender) >= 4  //  Reserved service name
        &&  memcmp (zframe_data (sender), "mmi.", 4) == 0)
            s_worker_delete (self, worker, 1);
        else {
            //  Attach worker to service and mark as idle
            zframe_t *service_frame = zmsg_pop (msg);
            worker->service = s_service_require (self, service_frame);
            worker->service->workers++;
            s_worker_waiting (self, worker);
            zframe_destroy (&service_frame);
        }
    }
    else
    if (zframe_streq (command, MDPW_REPLY)) {
        if (worker_ready) {
            //  Remove & save client return envelope and insert the
            //  protocol header and service name, then rewrap envelope.
            zframe_t *client = zmsg_unwrap (msg);
            zmsg_pushstr (msg, worker->service->name);
            zmsg_pushstr (msg, MDPC_CLIENT);
            zmsg_wrap (msg, client);
            zmsg_send (&msg, self->socket);
            s_worker_waiting (self, worker);
        }
        else
            s_worker_delete (self, worker, 1);
    }
    else
    if (zframe_streq (command, MDPW_HEARTBEAT)) {
        if (worker_ready)
            worker->expiry = zclock_time () + HEARTBEAT_EXPIRY;
        else
            s_worker_delete (self, worker, 1);
    }
    else
    if (zframe_streq (command, MDPW_DISCONNECT))
        s_worker_delete (self, worker, 0);
    else {
        zclock_log ("E: invalid input message");
        zmsg_dump (msg);
    }
    free (command);
    zmsg_destroy (&msg);
}
Exemple #11
0
int
curve_server_send (curve_server_t *self, zmsg_t **msg_p)
{
    assert (self);
    assert (zmsg_size (*msg_p) > 0);
    zmsg_send (msg_p, self->data);
    return 0;
}
Exemple #12
0
static int
s_agent_handle_data (agent_t *self)
{
    //  Encrypt and send all frames of request
    zmsg_t *request = zmsg_recv (self->data);
    while (zmsg_size (request)) {
        zframe_t *cleartext = zmsg_pop (request);
        if (zmsg_size (request))
            zframe_set_more (cleartext, 1);
        zframe_t *encrypted = curve_codec_encode (self->codec, &cleartext);
        if (encrypted)
            zframe_send (&encrypted, self->dealer, 0);
        else
            self->state = exception;
    }
    zmsg_destroy (&request);
    return 0;
}
Exemple #13
0
static void
s_broker_worker_msg(broker_t *self, zframe_t *sender, zmsg_t *msg)
{
	assert(zmsg_size(msg) >= 1);

	zframe_t *command = zmsg_pop(msg);
	char *id_string = zframe_strhex(sender);
	int worker_ready = (zhash_lookup(self->workers, id_string) != NULL);
	free(id_string);
	worker_t *worker = s_worker_require(self, sender);

	if (zframe_streq(command, MDPW_READY)){
		if (worker_ready)
			s_worker_delete(worker, 1);
		else 
		if (zframe_size(sender) >= 4 && memcmp(zframe_data(sender), "mmi.", 4) == 0)
			s_worker_delete(worker, 1);
		else {
			zframe_t *service_frame = zmsg_pop(msg);
			worker->service = s_service_require(self, service_frame);
			worker->service->workers++;
			s_worker_waiting(worker);
			zframe_destroy(&service_frame);
		}
	}
	else
	if (zframe_streq(command, MDPW_REPLY)){
		if (worker_ready){
			zframe_t *client = zmsg_unwrap(msg);
			zmsg_pushstr(msg, worker->service->name);
			zmsg_pushstr(msg, MDPC_CLIENT);
			zmsg_wrap(msg, client);
			zmsg_send(&msg, self->socket);
			s_worker_waiting(worker);
		}
		else 
			s_worker_delete(worker, 1);
	}
	else
	if (zframe_streq(command, MDPW_HEARTBEAT)){
		if (worker_ready)
			worker->expiry = zclock_time() + HEARTBEAT_EXPIRY;
		else
			s_worker_delete(worker, 1);
	}
	else
	if (zframe_streq(command, MDPW_DISCONNECT))
		s_worker_delete(worker, 0);
	else {
		zclock_log("E: invalid input message");
		zmsg_dump(msg);
	}
	free(command);
	zmsg_destroy(&msg);

}
Exemple #14
0
static void
client_execute (client_t *self, int event)
{
    self->next_event = event;
    while (self->next_event) {
        self->event = self->next_event;
        self->next_event = 0;
        printf ("State=%s, event=%s\n",
            s_state_name [self->state], s_event_name [self->event]);
        switch (self->state) {
            case start_state:
                if (self->event == ohai_event) {
                check_credentials_action (self);
                    self->state = authenticated_state;
                }
                break;
                
            case authenticated_state:
                if (self->event == ok_event) {
                    zmsg_addstr (self->reply, "OHAI-OK");
                    self->state = ready_state;
                }
                else
                if (self->event == error_event) {
                    zmsg_addstr (self->reply, "WTF");
                    self->state = start_state;
                }
                break;
                
            case ready_state:
                if (self->event == icanhaz_event) {
                    zmsg_addstr (self->reply, "CHEEZBURGER");
                }
                else
                if (self->event == hugz_event) {
                    zmsg_addstr (self->reply, "HUGZ-OK");
                }
                else
                if (self->event == heartbeat_event) {
                    zmsg_addstr (self->reply, "HUGZ");
                }
                break;
                
            case stopped_state:
                //  Discard all events silently
                break;
        }
        if (zmsg_size (self->reply) > 1) {
            puts ("Send message to client");
            zmsg_dump (self->reply);
            zmsg_send (&self->reply, self->router);
            self->reply = zmsg_new ();
            zmsg_add (self->reply, zframe_dup (self->address));
        }
    }
}
Exemple #15
0
int main(int argc, char **argv)
{	
	zctx_t *ctx;
	zwssock_t *sock;

	char *l =  argc > 1 ? argv[1] : listen_on;

	int major, minor, patch;
	zmq_version (&major, &minor, &patch);
	printf("built with: ØMQ=%d.%d.%d czmq=%d.%d.%d\n",
	       major, minor, patch,
	       CZMQ_VERSION_MAJOR, CZMQ_VERSION_MINOR,CZMQ_VERSION_PATCH);


	ctx = zctx_new();
	sock = zwssock_new_router(ctx);

	zwssock_bind(sock, l);

	zmsg_t* msg;
	zframe_t *id;

	while (!zctx_interrupted)
	{		
		msg = zwssock_recv(sock);
		
		if (!msg)
			break;

		// first message is the routing id
		id = zmsg_pop(msg);

		while (zmsg_size(msg) != 0)
		{
			char * str = zmsg_popstr(msg);

			printf("%s\n", str);
			
			free(str);
		}

		zmsg_destroy(&msg);

		msg = zmsg_new();

		zmsg_push(msg, id);
		zmsg_addstr(msg, "hello back");

		zwssock_send(sock, &msg);
	}
	
	zwssock_destroy(&sock);
	zctx_destroy(&ctx);	
}
Exemple #16
0
void worker(void *args, zctx_t *ctx, void *pipe) {
	long mashine_number =  ((setting_t *) args)->mashine_number;
	long thread_number = ((setting_t *) args)->thread_number;	
	long auto_increment = 0;
    struct timeval tp;
	
	void *worker = zsocket_new(ctx, ZMQ_DEALER);
	zsocket_connect(worker, "inproc://zid");
	
	while (!zctx_interrupted) {
		zmsg_t *request = zmsg_recv(worker);
		
		/* drop message if its size is less than 2 */
		if (zmsg_size(request) != 2) {
			zmsg_destroy(&request);
			continue;
		}
		/* sender id */
		zframe_t *sender = zmsg_pop(request);
		
		/* number of id to generate */
		char *num = zmsg_popstr(request);
		int n = atoi(num);
		free(num);
		
		if (n > 0) {
		
			/* response message */
			zmsg_t *response = zmsg_new();
		
			int i;
			for (i = 0; i < n; i++) {
				gettimeofday(&tp, NULL);
			
				zmsg_addstrf(response, "%ld", ((mashine_number << 59) | (thread_number << 56) | (auto_increment << 45) | (tp.tv_sec << 10) | (tp.tv_usec / 1000)));
			
				auto_increment++;
				if (auto_increment == 2048) {
					auto_increment = 0;
				}
			}
		
			/* push sender id */
			zmsg_push(response, sender);
			/* send back reply */
			zmsg_send(&response, worker);
		} else {
			zframe_destroy(&sender);
		}
		
		zmsg_destroy(&request);
	}
}
Exemple #17
0
int
zmsg_signal (zmsg_t *self)
{
    if (zmsg_size (self) == 1
    &&  zmsg_content_size (self) == 8) {
        zframe_t *frame = zmsg_first (self);
        int64_t signal_value = *((int64_t *) zframe_data (frame));
        if ((signal_value & 0xFFFFFFFFFFFFFF00L) == 0x7766554433221100L)
            return signal_value & 255;
    }
    return -1;
}
Exemple #18
0
ProBInitialResponse
prob_init(prob_client_t pc, int is_por)
{
    Debugf("initializing ProB Zocket\n")
    zmsg_t *request = zmsg_new();
    zmsg_addstr(request, "init");
    zmsg_addstrf(request, "%d", pc->id_count);
    zmsg_addstrf(request, "%d", is_por);

    Debugf("sending message with length %zu, contents are:\n", zmsg_content_size(request));
#ifdef LTSMIN_DEBUG
    if (log_active(debug)) zmsg_print(request);
#endif

    if (zmsg_send(&request, pc->zocket) != 0) Abort("Could not send message");
    zmsg_destroy(&request);

    zmsg_t *response = zmsg_recv(pc->zocket);
    if (response == NULL) Abort("Did not receive valid response");

    Debugf("received message with length %zu, contents are:\n", zmsg_content_size(response));
#ifdef LTSMIN_DEBUG
    if (log_active(debug)) zmsg_print(response);
#endif


    ProBInitialResponse resp = prob_get_init_response(response);

    if (zmsg_size(response) != 0) Abort("Did not receive valid reponse size");

//    puts("transition groups:");
//    print_chunk_array(resp.transition_groups);
//    puts("variables");
//    print_chunk_array(resp.variables);
//    for (size_t i = 0; i < resp.variables.size; i++) {
//        printf("%s (%s)\n", resp.variables.chunks[i].data, resp.variable_types.chunks[i].data);
//    }
//    puts("state labels");
//    print_chunk_array(resp.state_labels);
//
//    puts("May Write Matrix:");
//    print_matrix(resp.may_write);
//    puts("Must Write Matrix:");
//    print_matrix(resp.must_write);
//    puts("Reads Action Matrix:");
//    print_matrix(resp.reads_action);
//    puts("Reads Guard Matrix:");
//    print_matrix(resp.reads_guard);

    zmsg_destroy(&response);
    return resp;
}
Exemple #19
0
void recv_sync(char * expected, void * pipe) {
  assert(pipe);
  assert(expected);
  zmsg_t * in = zmsg_recv(pipe);
  if(!in) {
    zclock_log("quitting in recv_sync handshake!");
    exit(1);
  }
  assert(zmsg_size(in) == 1);
  zframe_t* ping = zmsg_pop(in);
  assert(zframe_streq(ping, expected));
  zmsg_destroy(&in);
}
Exemple #20
0
int main(void) {
    zmsg_t *msg;
    zframe_t *frame;
    char *str;
    int i, rc;

    // create push/pull sockets
    zsock_t *push = zsock_new_push("inproc://example");
    zsock_t *pull = zsock_new_pull("inproc://example");

    // send multi-frame message
    msg = zmsg_new();
    zmsg_addmem(msg, "apple", 5);
    zmsg_addmem(msg, "banana", 6);
    zmsg_addmem(msg, "cherry", 6);
    assert(zmsg_size(msg) == 3);
    assert(zmsg_content_size(msg) == 5+6+6);
    rc = zmsg_send(&msg, push);
    assert(msg == NULL);
    assert(rc == 0);

    // receive multi-frame message
    msg = zmsg_recv(pull);
    assert(msg);
    assert(zmsg_size(msg) == 3);
    assert(zmsg_content_size(msg) == 5+6+6);
    for (i = 0; i < 3; i++) {
        str = zmsg_popstr(msg);
        puts(str);
    }
    zmsg_destroy(&msg);

    // disconnect
    zsock_destroy(&push);
    zsock_destroy(&pull);

    return 0;
}
Exemple #21
0
/**
 * Blocking call that returns when the alien has been shot.
 * @return 
 */
void Alien::GetShot(const unsigned int timeout, std::vector<std::string>& bullets) {
   bullets.clear();
   if (!mBody) {
      LOG(WARNING) << "Alien attempted to GetShot but is not properly initialized";
      return;
   }

   if (zsocket_poll(mBody, timeout)) {
      zmsg_t* msg = zmsg_recv(mBody);
      if (msg && zmsg_size(msg) >= 2) {
         zframe_t* data = zmsg_pop(msg);
         if (data) {
            //remove the first frame
            zframe_destroy(&data);
         }
         int msgSize = zmsg_size(msg);
         for (int i = 0; i < msgSize; i++) {
            data = zmsg_pop(msg);
            if (data) {
               std::string bullet;
               bullet.assign(reinterpret_cast<char*> (zframe_data(data)), zframe_size(data));
               bullets.push_back(bullet);
               zframe_destroy(&data);
            }
         }
      } else {
         if (msg) {
            LOG(WARNING) << "Got Invalid bullet of size: " << zmsg_size(msg);
         }
      }
      if (msg) {
         zmsg_destroy(&msg);
      }
   }

}
Exemple #22
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;
}
Exemple #23
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);
 // Не должен создавать сервис, в случаи запроса от клиента

    //  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);
}
Exemple #24
0
zmsg_t *
mdp_client_recv (mdp_client_t *self, char **command_p, char **service_p)
{
    assert (self);

    zmsg_t *msg = zmsg_recv (self->client);
    if (msg == NULL)
        //  Interrupt
        return NULL;

    if (self->verbose) {
        zclock_log ("I: received reply:");
        zmsg_dump (msg);
    }

    //  Message format:
    //  Frame 1: empty frame (delimiter)
    //  Frame 2: "MDPCxy" (six bytes, MDP/Client x.y)
    //  Frame 3: REPORT|NAK
    //  Frame 4: Service name (printable string)
    //  Frame 5..n: Application frames

    //  We would handle malformed replies better in real code
    assert (zmsg_size (msg) >= 5);

    zframe_t *empty = zmsg_pop (msg);
    assert (zframe_streq (empty, ""));
    zframe_destroy (&empty);

    zframe_t *header = zmsg_pop (msg);
    assert (zframe_streq (header, MDPC_CLIENT));
    zframe_destroy (&header);

    zframe_t *command = zmsg_pop (msg);
    assert (zframe_streq (command, MDPC_REPORT) ||
            zframe_streq (command, MDPC_NAK));
    if (command_p)
        *command_p = zframe_strdup (command);
    zframe_destroy (&command);

    zframe_t *service = zmsg_pop (msg);
    if (service_p)
        *service_p = zframe_strdup (service);
    zframe_destroy (&service);

    return msg;     //  Success
}
Exemple #25
0
/**
 * @brief Send a message through the 0mq socket.
 *
 * This function is blocking.
 *
 * @returns The number of bytes sent.
 *
 * @param buf The data to send.
 * @param len The length of buf.
 */
int mux_0mq_send_msg(void *buf, size_t len)
{
    zmsg_t *msg = zmsg_new();

    mux_printf("Now attempting to send message!");
    zmsg_addstr(msg, display->uuid);
    zmsg_addmem(msg, buf, len);

    if (zmsg_size(msg) != 2) {
        mux_printf_error("Something went wrong building zmsg");
        return -1;
    }

    zmsg_send(&msg, display->zmq.socket); // TODO: figure out how return code works for this

    return len;
}
Exemple #26
0
static void
s_client_process (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 address to client sender
    zmsg_wrap (msg, zframe_dup (sender));
    if (zframe_size (service_frame) >= 4
    &&  memcmp (zframe_data (service_frame), "mmi.", 4) == 0)
        s_service_internal (self, service_frame, msg);
    else
        s_service_dispatch (self, service, msg);
    zframe_destroy (&service_frame);
}
Exemple #27
0
static bpm_client_err_e _bpm_data_acquire (bpm_client_t *self, char *service,
        acq_req_t *acq_req)
{
    assert (self);
    assert (service);
    assert (acq_req);

    bpm_client_err_e err = BPM_CLIENT_SUCCESS;
    ACQ_OPCODE_TYPE operation = ACQ_OPCODE_DATA_ACQUIRE;

    /* Message is:
     * frame 0: operation code
     * frame 1: number of samples
     * frame 2: channel             */
    zmsg_t *request = zmsg_new ();
    zmsg_addmem (request, &operation, sizeof (operation));
    zmsg_addmem (request, &acq_req->num_samples, sizeof (acq_req->num_samples));
    zmsg_addmem (request, &acq_req->chan, sizeof (acq_req->chan));
    mdp_client_send (self->mdp_client, service, &request);

    /* Receive report */
    zmsg_t *report = mdp_client_recv (self->mdp_client, NULL, NULL);
    ASSERT_TEST(report != NULL, "Report received is NULL", err_null_report);
    assert (zmsg_size (report) == 1);

    /* Message is:
     * frame 0: error code      */
    zframe_t *err_code = zmsg_pop(report);
    ASSERT_TEST(err_code != NULL, "Could not receive error code", err_null_code);
    if ( *(ACQ_REPLY_TYPE *) zframe_data(err_code) != ACQ_OK) {
        DBE_DEBUG (DBG_LIB_CLIENT | DBG_LVL_TRACE, "[libclient] bpm_data_acquire: "
                "Data acquire was not required correctly\n");
        err = BPM_CLIENT_ERR_AGAIN;
        goto err_data_acquire;
    }
    DBE_DEBUG (DBG_LIB_CLIENT | DBG_LVL_TRACE, "[libclient] bpm_data_acquire: "
            "Data acquire was successfully required\n");

err_data_acquire:
    zframe_destroy (&err_code);
err_null_code:
    zmsg_destroy (&report);
err_null_report:
    return err;
}
Exemple #28
0
int main (int argc, char *argv [])
{
    int verbose = (argc > 1 && streq (argv [1], "-v"));
    mdp_client_t *client = mdp_client_new ("tcp://localhost:5555", verbose);

    //  Send 100 sell orders
    int count;
    for (count = 0; count < 5; count++) {
        zmsg_t *request = zmsg_new ();
        zmsg_pushstr (request, "8");                // volume
        zmsg_pushstr (request, "%d", count + 1000); // price
        zmsg_pushstr (request, "SELL");
        mdp_client_send (client, "NYSE", &request);
    }

    //  Send 1 buy order.
    //  This order will match all sell orders.
    zmsg_t *request = zmsg_new ();
    zmsg_pushstr (request, "800");      // volume
    zmsg_pushstr (request, "2000");     // price
    zmsg_pushstr (request, "BUY");
    mdp_client_send (client, "NYSE", &request);

    //  Wait for all trading reports
    while (1) {
        char *service = NULL;
        zmsg_t *report = mdp_client_recv (client, &service);
        if (report == NULL)
            break;
        assert (zmsg_size (report) >= 2);
        zframe_t *report_type = zmsg_pop (report);
        char *report_type_str = zframe_strdup (report_type);
        zframe_t *volume = zmsg_pop (report);
        char *volume_str = zframe_strdup (volume);

        printf ("%s: %s %s shares\n", service, report_type_str, volume_str);

        free (service);
        free (report_type_str);
        free (volume_str);
    }

    mdp_client_destroy (&client);
    return 0;
}
Exemple #29
0
zmsg_t *
mdcli_recv (mdcli_t *self)
{
    assert (self);

    //  Poll socket for a reply, with timeout
    zmq_pollitem_t items [] = { { self->client, 0, ZMQ_POLLIN, 0 } };
    int rc = zmq_poll (items, 1, self->timeout * ZMQ_POLL_MSEC);
    if (rc == -1)
        return NULL;            //  Interrupted

    //  If we got a reply, process it
    if (items [0].revents & ZMQ_POLLIN) {
        zmsg_t *msg = zmsg_recv (self->client);
        if (self->verbose) {
            zclock_log ("I: received reply:");
            zmsg_dump (msg);
        }
        //  Don't try to handle errors, just assert noisily
        assert (zmsg_size (msg) >= 4);

        zframe_t *empty = zmsg_pop (msg);
        assert (zframe_streq (empty, ""));
        zframe_destroy (&empty);

        zframe_t *header = zmsg_pop (msg);
        assert (zframe_streq (header, MDPC_CLIENT));
        zframe_destroy (&header);

        zframe_t *service = zmsg_pop (msg);
        zframe_destroy (&service);

        return msg;     //  Success
    }
    if (zctx_interrupted)
        printf ("W: interrupt received, killing client...\n");
    else
    if (self->verbose)
        zclock_log ("W: permanent error, abandoning request");

    return NULL;
}
Exemple #30
0
int messages_push(char *msgid, zmsg_t *arguments)
{
	int ret;
  char filename[MAX_STRING_LEN];
	zframe_t *param = NULL;
  uint8_t *data = NULL;
  int size = 0;

  assert(msgid);
	assert(arguments);

  param = zmsg_pop(arguments);
  if (param == NULL) goto s_msg_push_parseerror;
  data = zframe_data(param);
  size = zframe_size(param);

  if (zmsg_size(arguments) > 0) {
    char *file = zmsg_popstr(arguments);
    ret = utils_write_file(file,(char*)data,size);
    free(file);
  } else {
    sprintf(filename, "/tmp/%s", msgid);
    ret = utils_write_file(filename,(char*)data,size);
  }

  if (ret != STATUS_OK) goto s_msg_push_execerror;

	ret = MSG_ANSWER_COMPLETED;

s_msg_push_end:
	if (param)
		free(param);
	return ret;

s_msg_push_execerror:
	ret = MSG_ANSWER_EXECERROR;
	goto s_msg_push_end;

s_msg_push_parseerror:
	ret = MSG_ANSWER_PARSEERROR;
	goto s_msg_push_end;
}