Exemplo n.º 1
0
unsigned int rmq_send(remnode_item* remnode, pwr_sClass_RemTrans* remtrans,
    char* buf, int buf_size)
{
  int sts;
  amqp_basic_properties_t prop;
  amqp_bytes_t msg;
  char* tmpbuf;
  unsigned int tmpbuf_size;

  if (rn_rmq->DisableHeader) {
    msg.bytes = buf;
    msg.len = buf_size;
  } else {
    tmpbuf_size = sizeof(rabbit_header) + buf_size;
    tmpbuf = malloc(tmpbuf_size);
    memcpy(tmpbuf + sizeof(rabbit_header), buf, buf_size);

    ((rabbit_header*)tmpbuf)->msg_size = htons(tmpbuf_size);
    ((rabbit_header*)tmpbuf)->msg_id[0] = htons(remtrans->Address[0]);
    ((rabbit_header*)tmpbuf)->msg_id[1] = htons(remtrans->Address[1]);

    msg.bytes = tmpbuf;
    msg.len = tmpbuf_size;
  }

  if ( remtrans->Address[3] == 2)
    prop.delivery_mode = 2;
  else
    prop.delivery_mode = 1;
  prop._flags = AMQP_BASIC_DELIVERY_MODE_FLAG;

  // 0 mandatory 0 immediate
  if (!streq(ctx->op->Exchange, ""))
    sts = amqp_basic_publish(ctx->conn, ctx->channel,
        amqp_cstring_bytes(ctx->op->Exchange), amqp_cstring_bytes(""), 0, 0,
        &prop, msg);
  else
    sts = amqp_basic_publish(ctx->conn, ctx->channel,
        amqp_cstring_bytes(ctx->op->Exchange),
        amqp_cstring_bytes(ctx->op->SendQueue), 0, 0, &prop, msg);
  if (sts) {
    remtrans->ErrCount++;
    errh_Error("Send failed, queue %s, RabbitMQ status %d",
        rn_rmq->SendQueue, sts, 0);
    if (debug)
      printf("Send failed sts:%d\n", (int)sts);
  }
  if (!rn_rmq->DisableHeader)
    free(tmpbuf);

  return STATUS_OK;
}
Exemplo n.º 2
0
void Channel::publish(const std::string& exchange,const std::string& routing_key,
		const std::string& mesg ){
	amqp_basic_properties_t props;
	props._flags = AMQP_BASIC_CONTENT_TYPE_FLAG | AMQP_BASIC_DELIVERY_MODE_FLAG;
	props.content_type = amqp_cstring_bytes("text/plain");
	props.delivery_mode = 1; /* transient delivery mode */
	int x = amqp_basic_publish(this->conn_ptr->_getconn_n(),
		   								this->channel_n,
		                                amqp_cstring_bytes(exchange.c_str()),
		                                amqp_cstring_bytes(routing_key.c_str()),
		                                0,
		                                0,
										&props,
			                            amqp_cstring_bytes(mesg.c_str()));
	if(x<0){
		label_reconnet:
		//meaning error occur
		Log::log.warning("%s: %s\n", "publishing", amqp_error_string2(x));
		Log::log.warning("Channel::publish: Reconnecting to RabbitMQ\n");

		//first close all the things
		amqp_channel_close(this->conn_ptr->_getconn_n(), this->channel_n, AMQP_REPLY_SUCCESS);
		amqp_connection_close(this->conn_ptr->_getconn_n(), AMQP_REPLY_SUCCESS);
		amqp_destroy_connection(this->conn_ptr->_getconn_n());

		//reconnect to rabbitMQ server!
		this->conn_ptr->reconnnect();
		amqp_channel_open(this->conn_ptr->_getconn_n(), channel_n);
		if(amqp_get_rpc_reply(this->conn_ptr->_getconn_n()).reply_type !=AMQP_RESPONSE_NORMAL){
			Log::log.warning("Channel::publish:Opening channel_n error\n");
		}else{
			x = amqp_basic_publish(this->conn_ptr->_getconn_n(),
													this->channel_n,
													amqp_cstring_bytes(exchange.c_str()),
													amqp_cstring_bytes(routing_key.c_str()),
													0,
													0,
													&props,
													amqp_cstring_bytes(mesg.c_str()));
		}
		if(x<0){
			sleep(2);
			goto label_reconnet;
		}

	}

	//die_on_error(x, "Publishing");
}
Exemplo n.º 3
0
static void sendLeaseRequest(MsgReceiver_t *receiver) {
    int status;
    char reqLease[1024];
    amqp_basic_properties_t properties;
    
    LOG4CXX_DEBUG(logger, "createMsgClient: making a lease request");
    
    createReqLeaseMsg(&receiver->conf, reqLease);
    
    memset(&properties, 0, sizeof(amqp_basic_properties_t));
    
    properties._flags = 0;
    
    properties._flags |= AMQP_BASIC_CONTENT_TYPE_FLAG;
    properties.content_type = amqp_cstring_bytes("application/json");

    properties._flags |= AMQP_BASIC_DELIVERY_MODE_FLAG;
    properties.delivery_mode = 2; // persistent delivery mode 
    
    properties._flags |= AMQP_BASIC_CORRELATION_ID_FLAG;
    properties.correlation_id = amqp_bytes_malloc_dup(receiver->queuename);
    
    properties._flags |= AMQP_BASIC_REPLY_TO_FLAG;
    properties.reply_to = amqp_bytes_malloc_dup(receiver->queuename);
    
    // send
    status = amqp_basic_publish(receiver->conn_state, receiver->channel, amqp_cstring_bytes("bms_registrations"), amqp_cstring_bytes("bms_registrations"), 0, 0, &properties, amqp_cstring_bytes(reqLease));
    if(status != 0) {
        LOG4CXX_ERROR(logger, "request a lease : unable to send a message - status " << status << " err " << amqp_error_string2(status));
    }
}
Exemplo n.º 4
0
static gboolean
afamqp_worker_publish(AMQPDestDriver *self, LogMessage *msg)
{
    gint pos = 0, ret;
    amqp_table_t table;
    amqp_basic_properties_t props;
    gboolean success = TRUE;
    SBGString *routing_key = sb_gstring_acquire();
    SBGString *body = sb_gstring_acquire();
    amqp_bytes_t body_bytes = amqp_cstring_bytes("");

    gpointer user_data[] = { &self->entries, &pos, &self->max_entries };

    value_pairs_foreach(self->vp, afamqp_vp_foreach, msg, self->seq_num,
                        &self->template_options, user_data);

    table.num_entries = pos;
    table.entries = self->entries;

    props._flags = AMQP_BASIC_CONTENT_TYPE_FLAG
                   | AMQP_BASIC_DELIVERY_MODE_FLAG | AMQP_BASIC_HEADERS_FLAG;
    props.content_type = amqp_cstring_bytes("text/plain");
    props.delivery_mode = self->persistent;
    props.headers = table;

    log_template_format(self->routing_key_template, msg, NULL, LTZ_LOCAL,
                        self->seq_num, NULL, sb_gstring_string(routing_key));

    if (self->body_template)
    {
        log_template_format(self->body_template, msg, NULL, LTZ_LOCAL,
                            self->seq_num, NULL, sb_gstring_string(body));
        body_bytes = amqp_cstring_bytes(sb_gstring_string(body)->str);
    }

    ret = amqp_basic_publish(self->conn, 1, amqp_cstring_bytes(self->exchange),
                             amqp_cstring_bytes(sb_gstring_string(routing_key)->str),
                             0, 0, &props, body_bytes);

    sb_gstring_release(routing_key);
    sb_gstring_release(body);

    if (ret < 0)
    {
        msg_error("Network error while inserting into AMQP server",
                  evt_tag_str("driver", self->super.super.super.id),
                  evt_tag_int("time_reopen", self->super.time_reopen), NULL);
        success = FALSE;
    }

    while (--pos >= 0)
    {
        amqp_bytes_free(self->entries[pos].key);
        amqp_bytes_free(self->entries[pos].value.value.bytes);
    }

    return success;
}
Exemplo n.º 5
0
static int
noit_rabbimq_submit(iep_thread_driver_t *dr,
                    const char *payload, size_t payloadlen) {
  int rv;
  amqp_bytes_t body;
  struct amqp_driver *driver = (struct amqp_driver *)dr;
  const char *routingkey = driver->routingkey;

  body.len = payloadlen;
  body.bytes = (char *)payload;
  if(*payload == 'M' ||
     *payload == 'S' ||
     *payload == 'C' ||
     (*payload == 'H' && payload[1] == '1') ||
     (*payload == 'F' && payload[1] == '1') ||
     (*payload == 'B' && (payload[1] == '1' || payload[1] == '2'))) {
    char uuid_str[32 * 2 + 1];
    int account_id, check_id;
    if(extract_uuid_from_jlog(payload, payloadlen,
                              &account_id, &check_id, uuid_str)) {
      if(*routingkey) {
        char *replace;
        int newlen = strlen(driver->routingkey) + 1 + sizeof(uuid_str) + 2 * 32;
        replace = alloca(newlen);
        snprintf(replace, newlen, "%s.%x.%x.%d.%d%s", driver->routingkey,
                 account_id%16, (account_id/16)%16, account_id,
                 check_id, uuid_str);
        routingkey = replace;
      }
    }
  }
  rv = amqp_basic_publish(driver->connection, 1,
                          amqp_cstring_bytes(driver->exchange),
                          amqp_cstring_bytes(routingkey),
                          1, 0, NULL, body);
  if(rv < 0) {
    mtevL(mtev_error, "AMQP publish failed, disconnecting\n");
    amqp_connection_close(driver->connection, AMQP_REPLY_SUCCESS);
    amqp_destroy_connection(driver->connection);
    if(driver->sockfd >= 0) close(driver->sockfd);
    driver->sockfd = -1;
    driver->connection = NULL;
    return -1;
  }
  BUMPSTAT(publications);
  noit_rabbitmq_heartbeat(driver);
  noit_rabbitmq_read_frame(driver);
  amqp_maybe_release_buffers(driver->connection);
  if(driver->has_error) {
    amqp_connection_close(driver->connection, AMQP_REPLY_SUCCESS);
    amqp_destroy_connection(driver->connection);
    if(driver->sockfd >= 0) close(driver->sockfd);
    driver->sockfd = -1;
    driver->connection = NULL;
    return -1;
  }
  return 0;
}
int main(int argc, const char **argv) {

	const char *hostname;
	int port;
	const char *exchange;
	const char *routingkey;
	const char *messagebody;
	const char *exchangetype = "direct";

	if (argc < 6) {
		fprintf(stderr, "Usage: emit_log_direct host port exchange routingkey messagebody\n");
		return 1;
	}

	hostname = argv[1];
	port = atoi(argv[2]);
	exchange = argv[3];
	routingkey = argv[4];
	messagebody = argv[5];

	int sockfd;
	int channelid = 1;
	amqp_connection_state_t conn;
	conn = amqp_new_connection();

	die_on_error(sockfd = amqp_open_socket(hostname, port), "Opening socket");
	amqp_set_sockfd(conn, sockfd);
	die_on_amqp_error(amqp_login(conn, "/", 0, 131072, 0, AMQP_SASL_METHOD_PLAIN, "guest", "guest"),"Logging in");
	amqp_channel_open(conn, channelid);
	die_on_amqp_error(amqp_get_rpc_reply(conn), "Opening channel");

	amqp_exchange_declare(conn,channelid,amqp_cstring_bytes(exchange),amqp_cstring_bytes(exchangetype),0,1,
						  amqp_empty_table);
	die_on_amqp_error(amqp_get_rpc_reply(conn),"Declaring exchange");

	{
		amqp_basic_properties_t props;
		props._flags = AMQP_BASIC_DELIVERY_MODE_FLAG;
		/*props.content_type = amqp_cstring_bytes("text/plain");*/
		props.delivery_mode = 2; /* persistent delivery mode */
		die_on_error(amqp_basic_publish(conn,
										channelid,
										amqp_cstring_bytes(exchange),
										amqp_cstring_bytes(routingkey),
										0,
										0,
										&props,
										amqp_cstring_bytes(messagebody)),
					"Publishing");
	}

	die_on_amqp_error(amqp_channel_close(conn, 1, AMQP_REPLY_SUCCESS), "Closing channel");
	die_on_amqp_error(amqp_connection_close(conn, AMQP_REPLY_SUCCESS), "Closing connection");
	die_on_error(amqp_destroy_connection(conn), "Ending connection");
	return 0;
}
Exemplo n.º 7
0
static void do_publish(amqp_connection_state_t conn,
                       char *exchange, char *routing_key,
		       amqp_basic_properties_t *props, amqp_bytes_t body)
{
	int res = amqp_basic_publish(conn, 1,
				     cstring_bytes(exchange),
				     cstring_bytes(routing_key),
				     0, 0, props, body);
	die_amqp_error(res, "basic.publish");
}
Exemplo n.º 8
0
static void mod_amqp_command_response(mod_amqp_command_profile_t *profile, char *command, switch_stream_handle_t stream,
									  char *fs_resp_exchange, char *fs_resp_key, switch_status_t status)
{
	char *json_output = NULL;
	amqp_basic_properties_t props;
	cJSON *message = NULL;

	if (! profile->conn_active) {
		/* No connection, so we can not send the message. */
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Profile[%s] not active\n", profile->name);
		return;
	}

	/* Construct the api response */
	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Preparing api command response: [%s]\n", (char *)stream.data);
	message = cJSON_CreateObject();

	cJSON_AddItemToObject(message, "output", cJSON_CreateString((const char *) stream.data));
	cJSON_AddItemToObject(message, "command", cJSON_CreateString(command));
	cJSON_AddItemToObject(message, "status", cJSON_CreateNumber((double) status));

	json_output = cJSON_Print(message);
	cJSON_Delete(message);

	memset(&props, 0, sizeof(amqp_basic_properties_t));

	props._flags = AMQP_BASIC_CONTENT_TYPE_FLAG;
	props.content_type = amqp_cstring_bytes("text/json");

	status = amqp_basic_publish(
								profile->conn_active->state,
								1,
								amqp_cstring_bytes(fs_resp_exchange),
								amqp_cstring_bytes(fs_resp_key),
								0,
								0,
								&props,
								amqp_cstring_bytes(json_output));

	switch_safe_free(json_output);

	if (status < 0) {
		const char *errstr = amqp_error_string2(-status);
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Profile[%s] failed to send event on connection[%s]: %s\n",
						  profile->name, profile->conn_active->name, errstr);

		/* This is bad, we couldn't send the message. Clear up any connection */
		mod_amqp_connection_close(profile->conn_active);
		profile->conn_active = NULL;
		return;
	}

	return;
}
Exemplo n.º 9
0
int create_queue_item(void *buf, size_t len) {
    printf("length: %zu\n", len);

    amqp_connection_state_t conn = amqp_new_connection();
    amqp_socket_t *socket = amqp_tcp_socket_new(conn);
    if (!socket) {
        printf("Error creating TCP socket.\n");
        return -1;
    }

    int status = amqp_socket_open(socket, "localhost", 5672);
    if (status) {
        printf("Error opening TCP socket.\n");
        return -1;
    }

    // Open channel
    if (handle_amqp_error(amqp_login(conn, "/", 0, 131072, 0, AMQP_SASL_METHOD_PLAIN, "guest", "guest"), "Login")) {
        return -1;
    }
    amqp_channel_open(conn, 1);
    if (handle_amqp_error(amqp_get_rpc_reply(conn), "Get Reply")) {
        return -1;
    }

    // Send message
    {
        amqp_basic_properties_t props;
        props._flags = AMQP_BASIC_CONTENT_TYPE_FLAG | AMQP_BASIC_DELIVERY_MODE_FLAG;
        props.content_type = amqp_cstring_bytes("text/plain");
        props.delivery_mode = 2; /* persistent delivery mode */
        status = amqp_basic_publish(conn,
            1,
            amqp_cstring_bytes(""),
            amqp_cstring_bytes("test-route"),
            0,
            0,
            &props,
            amqp_cstring_bytes(buf));
        if (status < 0) {
            printf("Error publishing\n");
            return -1;
        }
        printf("Published the thingy\n");
    }


    // Close channel
    amqp_channel_close(conn, 1, AMQP_REPLY_SUCCESS);
    amqp_connection_close(conn, AMQP_REPLY_SUCCESS);
    amqp_destroy_connection(conn);
    return 0;
}
Exemplo n.º 10
0
eSquere * eSquere::SendString(std::string message,std::string routkey){
    if(this->IsError()) return this;
    int code=amqp_basic_publish(
            this->connect,
            1,amqp_cstring_bytes(this->exchange.c_str()),
            amqp_cstring_bytes(routkey.c_str()),
            0,
            0,
            &this->Proprties,
            amqp_cstring_bytes(message.c_str()));
    if(code<0) return this->ErrorOn(code,amqp_error_string2(code));
    return this->ErrorOff("Send message");
}
Exemplo n.º 11
0
void *janus_rmq_out_thread(void *data) {
	if(rmq_client == NULL) {
		JANUS_LOG(LOG_ERR, "No RabbitMQ connection??\n");
		return NULL;
	}
	JANUS_LOG(LOG_VERB, "Joining RabbitMQ out thread\n");
	while(!rmq_client->destroy && !g_atomic_int_get(&stopping)) {
		/* We send messages from here as well, not only notifications */
		janus_rabbitmq_response *response = g_async_queue_pop(rmq_client->messages);
		if(response == NULL)
			continue;
		if(response == &exit_message)
			break;
		if(!rmq_client->destroy && !g_atomic_int_get(&stopping) && response->payload) {
			janus_mutex_lock(&rmq_client->mutex);
			/* Gotcha! Convert json_t to string */
			char *payload_text = json_dumps(response->payload, json_format);
			json_decref(response->payload);
			response->payload = NULL;
			JANUS_LOG(LOG_VERB, "Sending %s API message to RabbitMQ (%zu bytes)...\n", response->admin ? "Admin" : "Janus", strlen(payload_text));
			JANUS_LOG(LOG_VERB, "%s\n", payload_text);
			amqp_basic_properties_t props;
			props._flags = 0;
			props._flags |= AMQP_BASIC_REPLY_TO_FLAG;
			props.reply_to = amqp_cstring_bytes("Janus");
			if(response->correlation_id) {
				props._flags |= AMQP_BASIC_CORRELATION_ID_FLAG;
				props.correlation_id = amqp_cstring_bytes(response->correlation_id);
			}
			props._flags |= AMQP_BASIC_CONTENT_TYPE_FLAG;
			props.content_type = amqp_cstring_bytes("application/json");
			amqp_bytes_t message = amqp_cstring_bytes(payload_text);
			int status = amqp_basic_publish(rmq_client->rmq_conn, rmq_client->rmq_channel, rmq_client->janus_exchange,
				response->admin ? rmq_client->from_janus_admin_queue : rmq_client->from_janus_queue,
				0, 0, &props, message);
			if(status != AMQP_STATUS_OK) {
				JANUS_LOG(LOG_ERR, "Error publishing... %d, %s\n", status, amqp_error_string2(status));
			}
			g_free(response->correlation_id);
			response->correlation_id = NULL;
			free(payload_text);
			payload_text = NULL;
			g_free(response);
			response = NULL;
			janus_mutex_unlock(&rmq_client->mutex);
		}
	}
	g_async_queue_unref(rmq_client->messages);
	JANUS_LOG(LOG_INFO, "Leaving RabbitMQ out thread\n");
	return NULL;
}
Exemplo n.º 12
0
/* sends the buffer */
static int rmq_sendmsg(rmq_send_t *rmqs)
{
	rmq_params_t * rmqp = (rmq_params_t *)rmqs->sock->params;

	/* all checks should be already done */
	return amqp_basic_publish(rmqp->conn,
			rmqp->channel,
			AMQP_EMPTY_BYTES,
			amqp_cstring_bytes(rmqp->exchange.s),
			0,
			0,
			0,
			amqp_cstring_bytes(rmqs->msg));
}
Exemplo n.º 13
0
eSquere * eSquere::WriteString(std::string message,std::string qname){
    if(this->IsError()) return this;
    if(qname==""){
        return this->ErrorOn("Not set Queue Name");
    }
    int code=amqp_basic_publish(
            this->connect,
            1,
            amqp_cstring_bytes(""),
            amqp_cstring_bytes(qname.c_str()),
            0,
            0,
            &this->Proprties,
            amqp_cstring_bytes(message.c_str()));
    if(code<0) return this->ErrorOn(code,amqp_error_string2(code));
    return this->ErrorOff("Write message");
}
Exemplo n.º 14
0
void Channel::BasicPublish(const std::string &exchange_name,
                           const std::string &routing_key,
                           const BasicMessage::ptr_t message, bool mandatory,
                           bool immediate) {
  m_impl->CheckIsConnected();
  amqp_channel_t channel = m_impl->GetChannel();

  m_impl->CheckForError(amqp_basic_publish(
      m_impl->m_connection, channel, amqp_cstring_bytes(exchange_name.c_str()),
      amqp_cstring_bytes(routing_key.c_str()), mandatory, immediate,
      message->getAmqpProperties(), message->getAmqpBody()));

  // If we've done things correctly we can get one of 4 things back from the
  // broker
  // - basic.ack - our channel is in confirm mode, messsage was 'dealt with' by
  // the broker
  // - basic.return then basic.ack - the message wasn't delievered, but was
  // dealt with
  // - channel.close - probably tried to publish to a non-existant exchange, in
  // any case error!
  // - connection.clsoe - something really bad happened
  const boost::array<boost::uint32_t, 2> PUBLISH_ACK = {
      {AMQP_BASIC_ACK_METHOD, AMQP_BASIC_RETURN_METHOD}};
  amqp_frame_t response;
  boost::array<amqp_channel_t, 1> channels = {{channel}};
  m_impl->GetMethodOnChannel(channels, response, PUBLISH_ACK);

  if (AMQP_BASIC_RETURN_METHOD == response.payload.method.id) {
    MessageReturnedException message_returned =
        m_impl->CreateMessageReturnedException(
            *(reinterpret_cast<amqp_basic_return_t *>(
                response.payload.method.decoded)),
            channel);

    const boost::array<boost::uint32_t, 1> BASIC_ACK = {
        {AMQP_BASIC_ACK_METHOD}};
    m_impl->GetMethodOnChannel(channels, response, BASIC_ACK);
    m_impl->ReturnChannel(channel);
    m_impl->MaybeReleaseBuffersOnChannel(channel);
    throw message_returned;
  }

  m_impl->ReturnChannel(channel);
  m_impl->MaybeReleaseBuffersOnChannel(channel);
}
Exemplo n.º 15
0
/**
 * Broadcasts a message on the message stack to the RabbitMQ server
 * and frees the allocated memory if successful.
 * @return AMQP_STATUS_OK if the broadcasting was successful
 */
int sendMessage(MQ_INSTANCE *instance)
{
  int err_code;
  mqmessage *tmp;

  if(instance->conn_stat != AMQP_STATUS_OK){

    if(difftime(time(NULL),instance->last_rconn) > instance->rconn_intv){

      instance->last_rconn = time(NULL);

      if(init_conn(instance)){
	instance->rconn_intv = 1.0;
	instance->conn_stat = AMQP_STATUS_OK;	

      }else{
	instance->rconn_intv += 5.0;
	skygw_log_write(LOGFILE_ERROR,
			"Error : Failed to reconnect to the MQRabbit server ");
      }
    }
  }

  if(instance->messages){
    instance->conn_stat = amqp_basic_publish(instance->conn,instance->channel,
					     amqp_cstring_bytes(instance->exchange),
					     amqp_cstring_bytes(instance->key),
					     0,0,instance->messages->prop,amqp_cstring_bytes(instance->messages->msg));


    /**Message was sent successfully*/
    if(instance->conn_stat == AMQP_STATUS_OK){
      tmp = instance->messages;
      instance->messages = instance->messages->next;
      free(tmp->prop);
      free(tmp->msg);
      free(tmp);
    }
    
  }

  err_code = instance->conn_stat;

  return err_code;
}
Exemplo n.º 16
0
void publish(int argc, char* argv[])
{
    if (argc < 5)
    {
        help();
    }

    const int MSG_CNT = 10000;

    ex_name = argv[2];
    rt_key = argv[3];
    std::string msg = argv[4];
    int msg_cnt = MSG_CNT;
    if (argc > 5)
    {
        msg_cnt = atoi(argv[5]);
    }

    amqp_basic_properties_t props;
    props._flags = AMQP_BASIC_DELIVERY_MODE_FLAG;      
    props.delivery_mode = 2; /* persistent delivery mode */
    //props._flags = AMQP_BASIC_PRIORITY_FLAG | AMQP_BASIC_DELIVERY_MODE_FLAG;      
    //props.priority = prio;

    amqp_bytes_t message_bytes;
    message_bytes.len = msg.size();
    message_bytes.bytes = (void*)(msg.c_str());

    for (int i = 0; i < msg_cnt; ++i)
    {
        if (amqp_basic_publish(conn,                              /* state */
                    channel_id,                                   /* channel */
                    amqp_cstring_bytes(ex_name.c_str()),          /* exchange */
                    amqp_cstring_bytes(rt_key.c_str()),           /* routekey */
                    1,                                            /* mandatory */
                    0,                                            /* immediate */
                    &props,                                       /* properties */
                    message_bytes                                 /* body */
                    ) < 0) {
            std::cerr << "basic publish failed." << std::endl;
            return;
        }
    }
}
Exemplo n.º 17
0
/* XXX: You must hold "conf->lock" when calling this function! */
static int camqp_write_locked (camqp_config_t *conf, /* {{{ */
        const char *buffer, const char *routing_key)
{
    amqp_basic_properties_t props;
    int status;

    status = camqp_connect (conf);
    if (status != 0)
        return (status);

    memset (&props, 0, sizeof (props));
    props._flags = AMQP_BASIC_CONTENT_TYPE_FLAG
        | AMQP_BASIC_DELIVERY_MODE_FLAG
        | AMQP_BASIC_APP_ID_FLAG;
    if (conf->format == CAMQP_FORMAT_COMMAND)
        props.content_type = amqp_cstring_bytes("text/collectd");
    else if (conf->format == CAMQP_FORMAT_JSON)
        props.content_type = amqp_cstring_bytes("application/json");
    else if (conf->format == CAMQP_FORMAT_GRAPHITE)
        props.content_type = amqp_cstring_bytes("text/graphite");
    else
        assert (23 == 42);
    props.delivery_mode = conf->delivery_mode;
    props.app_id = amqp_cstring_bytes("collectd");

    status = amqp_basic_publish(conf->connection,
                /* channel = */ 1,
                amqp_cstring_bytes(CONF(conf, exchange)),
                amqp_cstring_bytes (routing_key),
                /* mandatory = */ 0,
                /* immediate = */ 0,
                &props,
                amqp_cstring_bytes(buffer));
    if (status != 0)
    {
        ERROR ("amqp plugin: amqp_basic_publish failed with status %i.",
                status);
        camqp_close_connection (conf);
    }

    return (status);
} /* }}} int camqp_write_locked */
Exemplo n.º 18
0
	int MQChannel::BasicPublishMessage(const std::vector<unsigned char> &data,
		const MQQueueParams &queue, const MQExchangeParams &exchange, uint32_t flags)
	{
		amqp_bytes_t bytes;
		bytes.bytes = (void *) &data[0];
		bytes.len = data.size();

		if (!(flags & SkipDeclareQueue)) {
			this->DeclareQueue(queue);
		}

		return amqp_basic_publish(
			mConn,
			mChannel,
			amqp_cstring_bytes(exchange.name.c_str()),
			amqp_cstring_bytes(queue.name.c_str()),
			0,
			0,
			NULL,
			bytes);
	}
Exemplo n.º 19
0
void basic_publish(amqp_connection_state_t connectionState_,
                   const char *message_) {
  amqp_bytes_t message_bytes = amqp_cstring_bytes(message_);

  amqp_basic_properties_t properties;
  properties._flags = 0;

  properties._flags |= AMQP_BASIC_DELIVERY_MODE_FLAG;
  properties.delivery_mode = AMQP_DELIVERY_NONPERSISTENT;

  int retval = amqp_basic_publish(
      connectionState_, fixed_channel_id, amqp_cstring_bytes(""),
      amqp_cstring_bytes(test_queue_name),
      /* mandatory=*/1,
      /* immediate=*/0,  /* RabbitMQ 3.x does not support the "immediate" flag
                           according to
                           https://www.rabbitmq.com/specification.html */
      &properties, message_bytes);

  assert(retval == 0);
}
Exemplo n.º 20
0
/* sends the buffer */
static int rmq_sendmsg(rmq_send_t *rmqs)
{
	rmq_params_t * rmqp = (rmq_params_t *)rmqs->sock->params;
	int ret;

	if (!(rmqp->flags & RMQ_PARAM_CONN))
		return 0;
	
	/* all checks should be already done */
	ret = amqp_basic_publish(rmqp->conn,
			rmqp->channel,
			rmqp->flags&RMQ_PARAM_EKEY?
		 		amqp_cstring_bytes(rmqp->exchange.s) :
				AMQP_EMPTY_BYTES ,
			amqp_cstring_bytes(rmqp->routing_key.s),
			0,
			0,
			0,
			amqp_cstring_bytes(rmqs->msg));

	return amqp_check_status(rmqp, ret);
}
Exemplo n.º 21
0
/* This should only be called in a single threaded context from the logging profile send thread */
switch_status_t mod_amqp_logging_send(mod_amqp_logging_profile_t *profile, mod_amqp_message_t *msg)
{
	amqp_basic_properties_t props;
	int status;

	if (! profile->conn_active) {
		/* No connection, so we can not send the message. */
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Profile[%s] not active\n", profile->name);
		return SWITCH_STATUS_NOT_INITALIZED;
	}
	memset(&props, 0, sizeof(amqp_basic_properties_t));

	props._flags = AMQP_BASIC_CONTENT_TYPE_FLAG;
	props.content_type = amqp_cstring_bytes("application/json");

	status = amqp_basic_publish(
								profile->conn_active->state,
								1,
								amqp_cstring_bytes(profile->exchange),
								amqp_cstring_bytes(msg->routing_key),
								0,
								0,
								&props,
								amqp_cstring_bytes(msg->pjson));

	if (status < 0) {
		const char *errstr = amqp_error_string2(-status);
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Profile[%s] failed to send event on connection[%s]: %s\n",
						  profile->name, profile->conn_active->name, errstr);

		/* This is bad, we couldn't send the message. Clear up any connection */
		mod_amqp_connection_close(profile->conn_active);
		profile->conn_active = NULL;
		return SWITCH_STATUS_SOCKERR;
	}

	return SWITCH_STATUS_SUCCESS;
}
Exemplo n.º 22
0
static int send(struct stats_buffer *sf)
{
  int status;
  char const *exchange;
  char const *routingkey;
  amqp_socket_t *socket = NULL;
  amqp_connection_state_t conn;
  exchange = "amq.direct";
  routingkey = "tacc_stats";
  conn = amqp_new_connection();
  socket = amqp_tcp_socket_new(conn);
  status = amqp_socket_open(socket, sf->sf_host, atoi(sf->sf_port));
  amqp_login(conn, "/", 0, 131072, 0, AMQP_SASL_METHOD_PLAIN, 
	     "guest", "guest");
  amqp_channel_open(conn, 1);
  amqp_get_rpc_reply(conn);

  {
    amqp_basic_properties_t props;
    props._flags = AMQP_BASIC_CONTENT_TYPE_FLAG | AMQP_BASIC_DELIVERY_MODE_FLAG;
    props.content_type = amqp_cstring_bytes("text/plain");
    props.delivery_mode = 2; /* persistent delivery mode */
    amqp_basic_publish(conn,
		       1,
		       amqp_cstring_bytes(exchange),
		       amqp_cstring_bytes(routingkey),
		       0,
		       0,
		       &props,
		       amqp_cstring_bytes(sf->sf_data));
  }
  amqp_channel_close(conn, 1, AMQP_REPLY_SUCCESS);
  amqp_connection_close(conn, AMQP_REPLY_SUCCESS);
  amqp_destroy_connection(conn); 

  return 0;
}
void
RabbitMQConnection::sendMessage (const amqp_bytes_t &message,
                                 const amqp_bytes_t &exchange, const amqp_bytes_t &routingKey,
                                 const amqp_bytes_t &correlationID)
{
  amqp_basic_properties_t props;
  int ret;

  props._flags = AMQP_BASIC_CONTENT_TYPE_FLAG | AMQP_BASIC_DELIVERY_MODE_FLAG;
  props.content_type = amqp_cstring_bytes ("text/plain");
  props.delivery_mode = 2; /* persistent delivery mode */

  if (correlationID.len > 0) {
    props._flags |= AMQP_BASIC_CORRELATION_ID_FLAG;
    props.correlation_id = correlationID;
  }

  ret = amqp_basic_publish (conn, 1, exchange,
                            routingKey, /* mandatory */ false, /* inmediate */ false, &props, message);

  if (ret != AMQP_STATUS_OK) {
    GST_ERROR ("Error ret value: %d", ret);
  }
}
Exemplo n.º 24
0
void send_msg_to_rabbitmq(char const * msg){
    int status;
    amqp_basic_properties_t props;
    props._flags = AMQP_BASIC_CONTENT_TYPE_FLAG | AMQP_BASIC_DELIVERY_MODE_FLAG;
    props.content_type = amqp_cstring_bytes("text/plain");
    props.delivery_mode = 2; /* persistent delivery mode */
    
    status = amqp_basic_publish(
            mq_conn,
            1,
            amqp_cstring_bytes((rabbitmq_exchange==NULL)?"nagios":rabbitmq_exchange),
            amqp_cstring_bytes((rabbitmq_routingkey==NULL)?"nagios":rabbitmq_routingkey),
            0,
            0,
            &props,
            amqp_cstring_bytes(msg)
    );
    if(!(status==0))
    {
        printf("RabbitMQ send error...\n");
    }else{
        printf("RabbitMQ send Success... %s\n", msg);
    }
}
Exemplo n.º 25
0
static void send_batch(amqp_connection_state_t conn,
		       char const *queue_name,
		       int rate_limit,
		       int message_count)
{
  uint64_t start_time = now_microseconds();
  int i;
  int sent = 0;
  int previous_sent = 0;
  uint64_t previous_report_time = start_time;
  uint64_t next_summary_time = start_time + SUMMARY_EVERY_US;

  char message[256];
  amqp_bytes_t message_bytes;

  for (i = 0; i < (int)sizeof(message); i++) {
    message[i] = i & 0xff;
  }

  message_bytes.len = sizeof(message);
  message_bytes.bytes = message;

  for (i = 0; i < message_count; i++) {
    uint64_t now = now_microseconds();

    die_on_error(amqp_basic_publish(conn,
				    1,
				    amqp_cstring_bytes("amq.direct"),
				    amqp_cstring_bytes(queue_name),
				    0,
				    0,
				    NULL,
				    message_bytes),
		 "Publishing");
    sent++;
    if (now > next_summary_time) {
      int countOverInterval = sent - previous_sent;
      double intervalRate = countOverInterval / ((now - previous_report_time) / 1000000.0);
      printf("%d ms: Sent %d - %d since last report (%d Hz)\n",
	     (int)(now - start_time) / 1000, sent, countOverInterval, (int) intervalRate);

      previous_sent = sent;
      previous_report_time = now;
      next_summary_time += SUMMARY_EVERY_US;
    }

    while (((i * 1000000.0) / (now - start_time)) > rate_limit) {
      microsleep(2000);
      now = now_microseconds();
    }
  }

  {
    uint64_t stop_time = now_microseconds();
    int total_delta = stop_time - start_time;

    printf("PRODUCER - Message count: %d\n", message_count);
    printf("Total time, milliseconds: %d\n", total_delta / 1000);
    printf("Overall messages-per-second: %g\n", (message_count / (total_delta / 1000000.0)));
  }
}
Exemplo n.º 26
0
void rpc_run(struct status *status)
{
    int ret;

    DEBUG(2, ("[*] Running RPC command\n"));

    /* Init command control */
    if (!control_init(status)) {
        return;
    }

    /* Enter control loop */
    while (rpc_check_run_flag(status)) {
        amqp_rpc_reply_t    result;
        amqp_envelope_t     envelope;
        amqp_basic_properties_t response_header;
        amqp_bytes_t        response_body;

        response_header._flags = 0;
        amqp_maybe_release_buffers(status->conn);
        result = amqp_consume_message(status->conn, &envelope, NULL, 0);
        if (result.reply_type != AMQP_RESPONSE_NORMAL) {
            if (AMQP_RESPONSE_LIBRARY_EXCEPTION == result.reply_type &&
                AMQP_STATUS_UNEXPECTED_STATE == result.library_error)
            {
                amqp_frame_t    frame;

                if (AMQP_STATUS_OK != amqp_simple_wait_frame(status->conn, &frame)) {
                    DEBUG(0, ("[!] Error consuming message\n"));
                    control_abort(status);
                    break;
                }
                if (AMQP_FRAME_METHOD == frame.frame_type) {
                    switch (frame.payload.method.id) {
                    case AMQP_BASIC_ACK_METHOD:
                        /* if we've turned publisher confirms on, and we've published a message
                         * here is a message being confirmed
                         */
                        break;
                    case AMQP_BASIC_RETURN_METHOD:
                        /* if a published message couldn't be routed and the mandatory flag was set
                         * this is what would be returned. The message then needs to be read.
                         */
                    {
                        amqp_message_t  message;

                        result = amqp_read_message(status->conn, frame.channel, &message, 0);
                        if (AMQP_RESPONSE_NORMAL != result.reply_type) {
                            control_abort(status);
                            return;
                        }
                        amqp_destroy_message(&message);
                    }
                    break;
                    case AMQP_CHANNEL_CLOSE_METHOD:
                        /* a channel.close method happens when a channel exception occurs, this
                         * can happen by publishing to an exchange that doesn't exist for example
                         *
                         * In this case you would need to open another channel redeclare any queues
                         * that were declared auto-delete, and restart any consumers that were attached
                         * to the previous channel
                         */
                        return;
                    case AMQP_CONNECTION_CLOSE_METHOD:
                        /* a connection.close method happens when a connection exception occurs,
                         * this can happen by trying to use a channel that isn't open for example.
                         *
                         * In this case the whole connection must be restarted.
                         */
                        return;
                    default:
                        DEBUG(0, ("[!] An unexpected method was received %d\n", frame.payload.method.id));
                        return;
                    }
                    continue;
                }
                continue;
            }
            DEBUG(0, ("[!] Error consuming message\n"));
            control_abort(status);
            break;
        }

        DEBUG(2, ("Delivery %u, exchange %.*s routingkey %.*s\n",
              (unsigned) envelope.delivery_tag,
              (int) envelope.exchange.len, (char *) envelope.exchange.bytes,
              (int) envelope.routing_key.len, (char *) envelope.routing_key.bytes));

        if (envelope.message.properties._flags & AMQP_BASIC_CONTENT_TYPE_FLAG) {
            DEBUG(2, ("Content-type: %.*s\n",
                  (int) envelope.message.properties.content_type.len,
                  (char *) envelope.message.properties.content_type.bytes));
        }
        if (envelope.message.properties._flags & AMQP_BASIC_REPLY_TO_FLAG) {
            response_header._flags |= AMQP_BASIC_REPLY_TO_FLAG;
            response_header.reply_to = amqp_bytes_malloc_dup(envelope.message.properties.reply_to);
            DEBUG(2, ("Reply-to: %.*s\n",
                  (int) envelope.message.properties.reply_to.len,
                  (char *) envelope.message.properties.reply_to.bytes));
        }
        if (envelope.message.properties._flags & AMQP_BASIC_CORRELATION_ID_FLAG) {
            response_header._flags |= AMQP_BASIC_CORRELATION_ID_FLAG;
            response_header.correlation_id = amqp_bytes_malloc_dup(envelope.message.properties.correlation_id);
            DEBUG(2, ("Correlation-id: %.*s\n",
                  (int) envelope.message.properties.correlation_id.len,
                  (char *) envelope.message.properties.correlation_id.bytes));
        }

        /* Handle the request */
        response_body = control_handle(status, envelope.message.body);
        DEBUG(2, ("[*] Sending response '%s'\n", (char*)response_body.bytes));

        /* Send the response */
        response_header._flags |= AMQP_BASIC_CONTENT_TYPE_FLAG;
        response_header.content_type = amqp_cstring_bytes("text/plain");

        response_header._flags |= AMQP_BASIC_DELIVERY_MODE_FLAG;
        response_header.delivery_mode = 1;
        ret = amqp_basic_publish(status->conn, 1,
                     amqp_empty_bytes,
                     amqp_bytes_malloc_dup(envelope.message.properties.reply_to),
                     0, /* Mandatory */
                     0, /* Inmediate */
                     &response_header,
                     response_body);
        if (ret != AMQP_STATUS_OK) {
            DEBUG(0, ("[!] Error publishing command response: %s\n", amqp_error_string2(ret)));
        }

        //* Free memory */
        amqp_destroy_envelope(&envelope);
    }

    /* Clean up control */
    control_free(status);
}
Exemplo n.º 27
0
/**
 * Broadcasts a message on the message stack to the RabbitMQ server
 * and frees the allocated memory if successful. This function is only called by
 * the housekeeper thread.
 * @param data MQfilter instance
 */
void sendMessage(void* data)
{
    MQ_INSTANCE *instance = (MQ_INSTANCE*)data;
  mqmessage *tmp;
  int err_num;
  
  spinlock_acquire(&instance->rconn_lock);
  if(instance->conn_stat != AMQP_STATUS_OK){

    if(difftime(time(NULL),instance->last_rconn) > instance->rconn_intv){

      instance->last_rconn = time(NULL);

      if(init_conn(instance)){
	instance->rconn_intv = 1.0;
	instance->conn_stat = AMQP_STATUS_OK;	

      }else{
	instance->rconn_intv += 5.0;
	skygw_log_write(LOGFILE_ERROR,
			"Error : Failed to reconnect to the MQRabbit server ");
      }
    }
    err_num = instance->conn_stat;
  }
  spinlock_release(&instance->rconn_lock);
  
  if(err_num != AMQP_STATUS_OK)
  {
      /** No connection to the broker */
      return;
  }
  
  spinlock_acquire(&instance->msg_lock);
  tmp = instance->messages;
  
  if(tmp == NULL)
  {
      spinlock_release(&instance->msg_lock);
      return;
  }
  
  instance->messages = instance->messages->next;
  spinlock_release(&instance->msg_lock);
  
  while(tmp){
      
    err_num = amqp_basic_publish(instance->conn,instance->channel,
					     amqp_cstring_bytes(instance->exchange),
					     amqp_cstring_bytes(instance->key),
					     0,0,tmp->prop,amqp_cstring_bytes(tmp->msg));

    spinlock_acquire(&instance->rconn_lock);
    instance->conn_stat = err_num;
    spinlock_release(&instance->rconn_lock);
    
    if(err_num == AMQP_STATUS_OK){
	/**Message was sent successfully*/
      free(tmp->prop);
      free(tmp->msg);
      free(tmp);
      
      atomic_add(&instance->stats.n_sent,1);
      atomic_add(&instance->stats.n_queued,-1);
      spinlock_acquire(&instance->msg_lock);
      tmp = instance->messages;
      
      if(tmp == NULL)
      {
	  spinlock_release(&instance->msg_lock);
	  return;
      }
      
      instance->messages = instance->messages->next;
      spinlock_release(&instance->msg_lock);
    }
    else
    {
	spinlock_acquire(&instance->msg_lock);
	tmp->next = instance->messages;	
	instance->messages = tmp;
	spinlock_release(&instance->msg_lock);
	return;
    }
    
  }

}
Exemplo n.º 28
0
int lc_bus_publish_unicast(const char *buf, int buf_len, uint32_t queue_id)
{
    amqp_connection_state_t *conn = NULL;
    amqp_bytes_t body = { len: buf_len, bytes: (void *)buf };
    amqp_basic_properties_t props;
    int res = 0;

    if (!buf || queue_id >= NUM_LC_BUS_QUEUE) {
        return LC_BUS_ERR;
    }

    conn = lc_bus_get_connection();
    if (!conn) {
        return LC_BUS_ERR;
    }

    memset(&props, 0, sizeof props);
    props._flags = AMQP_BASIC_DELIVERY_MODE_FLAG;
    props.delivery_mode = 2; /* persistent delivery mode */

    res = amqp_basic_publish(
            *conn,
            LC_BUS_CHANNEL,
            amqp_cstring_bytes(lc_bus_exchange[LC_BUS_EXCHANGE_DIRECT][0]),
            amqp_cstring_bytes(lc_bus_queue[queue_id]),
            0, /* mandatory */
            0, /* immediate */
            &props,
            body
            );
    if (res) {
        LB_SYSLOG(LOG_ERR, "failed channel=%u queue=%u ret=%d\n",
                LC_BUS_CHANNEL, queue_id, res);
        return LC_BUS_ERR;
    } else {
        LB_SYSLOG(LOG_INFO, "succeed channel=%u queue=%u\n",
                LC_BUS_CHANNEL, queue_id);
    }

    return LC_BUS_OK;
}

int lc_bus_publish_broadcast(const char *buf, int buf_len)
{
    /* TODO */
    return LC_BUS_OK;
}

int lc_bus_publish_multicast(const char *buf, int buf_len)
{
    /* TODO */
    return LC_BUS_OK;
}

static int consumer_queueids[NUM_LC_BUS_QUEUE];

static int lc_bus_init_consumer_atomic(amqp_connection_state_t *conn,
        uint32_t flag, uint32_t queue_id)
{
    amqp_basic_consume_ok_t *res_consume = NULL;
    amqp_rpc_reply_t ret;

    if (queue_id >= NUM_LC_BUS_QUEUE) {
        return LC_BUS_ERR;
    }

#if 0
    amqp_basic_qos_ok_t *res_qos = NULL;

    if (count > 0 && count <= 65535 &&
        !(res_qos = amqp_basic_qos(
            *conn,
            1,
            0,
            count,
            0
            ))) {
        die_rpc(amqp_get_rpc_reply(*conn), "basic.qos");
        return LC_BUS_ERR;
    }
#endif

    res_consume = amqp_basic_consume(
            *conn,
            LC_BUS_CHANNEL,
            amqp_cstring_bytes(lc_bus_queue[queue_id]),
            amqp_empty_bytes, /* consumer_tag */
            0,                /* no_local */
            (flag & LC_BUS_CONSUME_WITH_ACK) ? 0 : 1, /* no_ack */
            0,                /* exclusive */
            amqp_empty_table  /* arguments */
            );
    if (!res_consume) {
        ret = amqp_get_rpc_reply(*conn);
        if (ret.reply_type != AMQP_RESPONSE_NORMAL) {
            LB_SYSLOG(LOG_ERR, "[%s] failed, channel=%u %s\n",
                    lc_bus_queue[queue_id], LC_BUS_CHANNEL,
                    amqp_rpc_reply_string(&ret));
            return LC_BUS_ERR;
        }
    }

    consumer_queueids[queue_id] = 1;
    LB_SYSLOG(LOG_INFO, "[%s] succeed channel=%u.\n",
            lc_bus_queue[queue_id], LC_BUS_CHANNEL);
    return LC_BUS_OK;
}
Exemplo n.º 29
0
int main(int argc, char *argv[])
{
  char const *hostname;
  int port, status;
  char const *exchange;
  char const *routingkey;
  char const *messagebody;
  amqp_socket_t *socket = NULL;
  amqp_connection_state_t conn;
  amqp_bytes_t reply_to_queue;

  if (argc < 6) { /* minimum number of mandatory arguments */
    fprintf(stderr, "usage:\namqp_rpc_sendstring_client host port exchange routingkey messagebody\n");
    return 1;
  }

  hostname = argv[1];
  port = atoi(argv[2]);
  exchange = argv[3];
  routingkey = argv[4];
  messagebody = argv[5];

  /*
     establish a channel that is used to connect RabbitMQ server
  */

  conn = amqp_new_connection();

  socket = amqp_tcp_socket_new(conn);
  if (!socket) {
    printf("creating TCP socket");
  }

  status = amqp_socket_open(socket, hostname, port);
  if (status) {
    printf("opening TCP socket");
  }
    printf("established connection!\n");
  amqp_login(conn, "/", 0, 131072, 0, AMQP_SASL_METHOD_PLAIN, "guest", "guest");//                    "Logging in");
  amqp_channel_open(conn, 1);
  amqp_get_rpc_reply(conn);//, "Opening channel");
  printf("open channel!\n");
  /*
     create private reply_to queue
  */

  {
    amqp_queue_declare_ok_t *r = amqp_queue_declare(conn, 1, amqp_empty_bytes, 0, 0, 0, 1, amqp_empty_table);
    amqp_get_rpc_reply(conn);//, "Declaring queue");
    printf("declare queue!\n");
    reply_to_queue = amqp_bytes_malloc_dup(r->queue);
    if (reply_to_queue.bytes == NULL) {
      fprintf(stderr, "Out of memory while copying queue name");
      return 1;
    }
  }

  /*
     send the message
  */

  {
    /*
      set properties
    */
    amqp_basic_properties_t props;
    props._flags = AMQP_BASIC_CONTENT_TYPE_FLAG |
                   AMQP_BASIC_DELIVERY_MODE_FLAG |
                   AMQP_BASIC_REPLY_TO_FLAG |
                   AMQP_BASIC_CORRELATION_ID_FLAG;
    props.content_type = amqp_cstring_bytes("text/plain");
    props.delivery_mode = 2; /* persistent delivery mode */
    props.reply_to = amqp_bytes_malloc_dup(reply_to_queue);
    if (props.reply_to.bytes == NULL) {
      fprintf(stderr, "Out of memory while copying queue name");
      return 1;
    }
    props.correlation_id = amqp_cstring_bytes("1");

    /*
      publish
    */
    amqp_basic_publish(conn,
                                    1,
                                    amqp_cstring_bytes(exchange),
                                    amqp_cstring_bytes(routingkey),
                                    0,
                                    0,
                                    &props,
                                    amqp_cstring_bytes(messagebody));
    //             "Publishing");

    amqp_bytes_free(props.reply_to);
  }

  /*
    wait an answer
  */
    printf("waiting answer!\n");
  {
    amqp_basic_consume(conn, 1, reply_to_queue, amqp_empty_bytes, 0, 1, 0, amqp_empty_table);
    amqp_get_rpc_reply(conn);//, "Consuming");
    amqp_bytes_free(reply_to_queue);

    {
      amqp_frame_t frame;
      int result;

      amqp_basic_deliver_t *d;
      amqp_basic_properties_t *p;
      size_t body_target;
      size_t body_received;

      while (1) {
        amqp_maybe_release_buffers(conn);
        result = amqp_simple_wait_frame(conn, &frame);
        printf("Result: %d\n", result);
        if (result < 0) {
          break;
        }

        printf("Frame type: %d channel: %d\n", frame.frame_type, frame.channel);
        if (frame.frame_type != AMQP_FRAME_METHOD) {
          continue;
        }

        printf("Method: %s\n", amqp_method_name(frame.payload.method.id));
        if (frame.payload.method.id != AMQP_BASIC_DELIVER_METHOD) {
          continue;
        }

        d = (amqp_basic_deliver_t *) frame.payload.method.decoded;
        printf("Delivery: %u exchange: %.*s routingkey: %.*s\n",
               (unsigned) d->delivery_tag,
               (int) d->exchange.len, (char *) d->exchange.bytes,
               (int) d->routing_key.len, (char *) d->routing_key.bytes);

        result = amqp_simple_wait_frame(conn, &frame);
        if (result < 0) {
          break;
        }

        if (frame.frame_type != AMQP_FRAME_HEADER) {
          fprintf(stderr, "Expected header!");
          abort();
        }
        p = (amqp_basic_properties_t *) frame.payload.properties.decoded;
        if (p->_flags & AMQP_BASIC_CONTENT_TYPE_FLAG) {
          printf("Content-type: %.*s\n",
                 (int) p->content_type.len, (char *) p->content_type.bytes);
        }
        printf("----\n");

        body_target = frame.payload.properties.body_size;
        body_received = 0;

        while (body_received < body_target) {
          result = amqp_simple_wait_frame(conn, &frame);
          if (result < 0) {
            break;
          }

          if (frame.frame_type != AMQP_FRAME_BODY) {
            fprintf(stderr, "Expected body!");
            abort();
          }

          body_received += frame.payload.body_fragment.len;
          printf("len -> %d \n",frame.payload.body_fragment.len);
          assert(body_received <= body_target);

          amqp_dump(frame.payload.body_fragment.bytes,
                    frame.payload.body_fragment.len);
        }

        if (body_received != body_target) {
          /* Can only happen when amqp_simple_wait_frame returns <= 0 */
          /* We break here to close the connection */
          break;
        }

        /* everything was fine, we can quit now because we received the reply */
        break;
      }

    }
  }

  /*
     closing
  */

  amqp_channel_close(conn, 1, AMQP_REPLY_SUCCESS);//, "Closing channel");
  amqp_connection_close(conn, AMQP_REPLY_SUCCESS);//, "Closing connection");
  amqp_destroy_connection(conn);//, "Ending connection");

  return 0;
}
Exemplo n.º 30
0
void AMQPExchange::sendPublishCommand(const char * message, const char * key) {
	amqp_bytes_t exchangeByte = amqp_cstring_bytes(name.c_str());
	amqp_bytes_t keyrouteByte = amqp_cstring_bytes(key);
	amqp_bytes_t messageByte = amqp_cstring_bytes(message);

	amqp_basic_properties_t props;

	if (sHeaders.find("Content-type")!= sHeaders.end())
		props.content_type = amqp_cstring_bytes(sHeaders["Content-type"].c_str());
	else
		props.content_type = amqp_cstring_bytes("text/plain");

	if (iHeaders.find("Delivery-mode")!= iHeaders.end())
		props.delivery_mode = (uint8_t)iHeaders["Delivery-mode"];
	else
		props.delivery_mode = 2; // persistent delivery mode

	props._flags = AMQP_BASIC_CONTENT_TYPE_FLAG | AMQP_BASIC_DELIVERY_MODE_FLAG;

	if (sHeaders.find("Content-encoding")!= sHeaders.end()) {
		props.content_encoding = amqp_cstring_bytes(sHeaders["Content-encoding"].c_str());
		props._flags += AMQP_BASIC_CONTENT_ENCODING_FLAG;
	}

	if (sHeaders.find("message_id")!= sHeaders.end()) {
		props.message_id = amqp_cstring_bytes(sHeaders["message_id"].c_str());
		props._flags += AMQP_BASIC_MESSAGE_ID_FLAG;
	}

	if (sHeaders.find("user_id")!= sHeaders.end()) {
		props.user_id = amqp_cstring_bytes(sHeaders["user_id"].c_str());
		props._flags += AMQP_BASIC_USER_ID_FLAG;
	}

	if (sHeaders.find("app_id")!= sHeaders.end()) {
		props.app_id = amqp_cstring_bytes(sHeaders["app_id"].c_str());
		props._flags += AMQP_BASIC_APP_ID_FLAG;
	}

	if (sHeaders.find("cluster_id")!= sHeaders.end()) {
		props.cluster_id = amqp_cstring_bytes(sHeaders["cluster_id"].c_str());
		props._flags += AMQP_BASIC_CLUSTER_ID_FLAG;
	}

	if (sHeaders.find("correlation_id")!= sHeaders.end()) {
		props.correlation_id = amqp_cstring_bytes(sHeaders["correlation_id"].c_str());
		props._flags += AMQP_BASIC_CORRELATION_ID_FLAG;
	}

	if (iHeaders.find("priority")!= iHeaders.end()) {
		props.priority = (uint8_t) iHeaders["priority"];
		props._flags += AMQP_BASIC_PRIORITY_FLAG;
	}

	if (iHeaders.find("timestamp")!= iHeaders.end()) {
		props.timestamp = (uint64_t) iHeaders["timestamp"];
		props._flags += AMQP_BASIC_TIMESTAMP_FLAG;
	}

	if (sHeaders.find("Expiration")!= sHeaders.end()) {
		props.expiration = amqp_cstring_bytes(sHeaders["Expiration"].c_str());
		props._flags += AMQP_BASIC_EXPIRATION_FLAG;
	}

	if (sHeaders.find("type")!= sHeaders.end()) {
		props.type = amqp_cstring_bytes(sHeaders["type"].c_str());
		props._flags += AMQP_BASIC_TYPE_FLAG;
	}

	if (sHeaders.find("Reply-to")!= sHeaders.end()) {
		props.reply_to = amqp_cstring_bytes(sHeaders["Reply-to"].c_str());
		props._flags += AMQP_BASIC_REPLY_TO_FLAG;
	}

	props.headers.num_entries = sHeadersSpecial.size();
	amqp_table_entry_t_ entries[props.headers.num_entries];

	int i = 0;
	map<string, string>::iterator it;
	for (it = sHeadersSpecial.begin(); it != sHeadersSpecial.end(); it++) {
		entries[i].key = amqp_cstring_bytes((*it).first.c_str());
		entries[i].value.kind = AMQP_FIELD_KIND_UTF8;
		entries[i].value.value.bytes = amqp_cstring_bytes((*it).second.c_str());
		i++;
	}
	props.headers.entries = entries;
	props._flags += AMQP_BASIC_HEADERS_FLAG;

	short mandatory = (parms & AMQP_MANDATORY) ? 1:0;
	short immediate = (parms & AMQP_IMMIDIATE) ? 1:0;

	int res = amqp_basic_publish(
		*cnn,
		1,
		exchangeByte,
		keyrouteByte,
		mandatory,
		immediate,
		&props,
		messageByte
	);

        if ( 0 > res ) {
		throw AMQPException("AMQP Publish Fail." );
	}
}