Esempio n. 1
0
static gboolean
afamqp_dd_connect(AMQPDestDriver *self, gboolean reconnect)
{
  int sockfd;
  amqp_rpc_reply_t ret;

  if (reconnect && self->conn)
    {
      ret = amqp_get_rpc_reply(self->conn);
      if (ret.reply_type == AMQP_RESPONSE_NORMAL)
        return TRUE;
    }

  self->conn = amqp_new_connection();
  sockfd = amqp_open_socket(self->host, self->port);
  if (sockfd < 0)
    {
      gchar *errstr = amqp_error_string(-sockfd);
      msg_error("Error connecting to AMQP server",
                evt_tag_str("driver", self->super.super.id),
                evt_tag_str("error", errstr),
                evt_tag_int("time_reopen", self->time_reopen),
                NULL);
      g_free(errstr);
      return FALSE;
    }
  amqp_set_sockfd(self->conn, sockfd);

  ret = amqp_login(self->conn, self->vhost, 0, 131072, 0,
                   AMQP_SASL_METHOD_PLAIN, self->user, self->password);
  if (!afamqp_is_ok(self, "Error during AMQP login", ret))
    return FALSE;

  amqp_channel_open(self->conn, 1);
  ret = amqp_get_rpc_reply(self->conn);
  if (!afamqp_is_ok(self, "Error during AMQP channel open", ret))
    return FALSE;

  if (self->declare)
    {
      amqp_exchange_declare(self->conn, 1, amqp_cstring_bytes(self->exchange),
                            amqp_cstring_bytes(self->exchange_type), 0, 0,
                            amqp_empty_table);
      ret = amqp_get_rpc_reply(self->conn);
      if (!afamqp_is_ok(self, "Error during AMQP exchange declaration", ret))
        return FALSE;
    }

  msg_debug ("Connecting to AMQP succeeded",
             evt_tag_str("driver", self->super.super.id),
             NULL);

  return TRUE;
}
Esempio n. 2
0
void AMQP::sockConnect() {
	cnn = amqp_new_connection();
	sockfd = amqp_open_socket(host.c_str(), port);

	if (sockfd<0){
		amqp_destroy_connection(cnn);
		throw AMQPException("AMQP cannot create socket descriptor", sockfd);
	}

	//cout << "sockfd="<< sockfd  << "  pid=" <<  getpid() <<endl;
	amqp_set_sockfd(cnn, sockfd);
}
bool initAmqp(amqp_connection_state_t &conn, amqp_socket_t *socket, int &status, amqp_bytes_t &queuename) {
	conn = amqp_new_connection();

	socket = amqp_tcp_socket_new(conn);
	if (!socket) {
		die("creating TCP socket");
		return false;
	}

	status = amqp_socket_open(socket, hostname, port);
	if (status) {
		die("opening TCP socket");
		return false;
	}

	if (!die_on_amqp_error(amqp_login(conn, "/", 0, 131072, 0, AMQP_SASL_METHOD_PLAIN, amqp_user, amqp_pass), "Logging in")) {
		return false;
	};
	amqp_channel_open(conn, 1);
	if (!die_on_amqp_error(amqp_get_rpc_reply(conn), "Opening channel")) {
		return false;
	}

	// passive 0 durable 1 auto-delete 0 internal 0 exchange
	amqp_exchange_declare_ok_t_ *er = amqp_exchange_declare(conn, 1, amqp_cstring_bytes(exchange), amqp_cstring_bytes(exchange_type), 0, 1, 0, 0, amqp_empty_table);
	if (!die_on_amqp_error(amqp_get_rpc_reply(conn), "Declaring exchange")) {
		return false;
	}

	// passive 0 durable 1 exclusive 0 auto-delete 0 queue
	amqp_queue_declare_ok_t *r = amqp_queue_declare(conn, 1, amqp_cstring_bytes(bindingkey), 0, 1, 0, 0, amqp_empty_table);
	if (!die_on_amqp_error(amqp_get_rpc_reply(conn), "Declaring queue")) {
		return false;
	}
	queuename = amqp_bytes_malloc_dup(r->queue);
	if (queuename.bytes == NULL) {
	  fprintf(stderr, "Out of memory while copying queue name");
	  return false;
	}

	amqp_queue_bind(conn, 1, queuename, amqp_cstring_bytes(exchange), amqp_cstring_bytes(bindingkey), amqp_empty_table);
	if (!die_on_amqp_error(amqp_get_rpc_reply(conn), "Binding queue")) {
		return false;
	}

	// no-local 0 no-ack 0 exclusive 0 consumer
	amqp_basic_consume(conn, 1, queuename, amqp_cstring_bytes(consumer_name), 1, 0, 0, amqp_empty_table);
	if (!die_on_amqp_error(amqp_get_rpc_reply(conn), "Consuming")) {
		return false;
	}
	
	return true;
}
Esempio n. 4
0
Channel::Channel(const std::string &host, int port, const std::string &username,
                 const std::string &password, const std::string &vhost,
                 int frame_max, const SSLConnectionParams &ssl_params)
    : m_impl(new Detail::ChannelImpl) {
  m_impl->m_connection = amqp_new_connection();
  if (NULL == m_impl->m_connection) {
    throw std::bad_alloc();
  }

  amqp_socket_t *socket = amqp_ssl_socket_new(m_impl->m_connection);
  if (NULL == socket) {
    throw std::bad_alloc();
  }
#if AMQP_VERSION >= 0x00080001
  amqp_ssl_socket_set_verify_peer(socket, ssl_params.verify_hostname);
  amqp_ssl_socket_set_verify_hostname(socket, ssl_params.verify_hostname);
#else
  amqp_ssl_socket_set_verify(socket, ssl_params.verify_hostname);
#endif

  try {
    int status =
        amqp_ssl_socket_set_cacert(socket, ssl_params.path_to_ca_cert.c_str());
    if (status) {
      throw AmqpLibraryException::CreateException(
          status, "Error setting CA certificate for socket");
    }

    if (ssl_params.path_to_client_key != "" &&
        ssl_params.path_to_client_cert != "") {
      status = amqp_ssl_socket_set_key(socket,
                                       ssl_params.path_to_client_cert.c_str(),
                                       ssl_params.path_to_client_key.c_str());
      if (status) {
        throw AmqpLibraryException::CreateException(
            status, "Error setting client certificate for socket");
      }
    }

    status = amqp_socket_open(socket, host.c_str(), port);
    if (status) {
      throw AmqpLibraryException::CreateException(
          status, "Error setting client certificate for socket");
    }

    m_impl->DoLogin(username, password, vhost, frame_max);
  } catch (...) {
    amqp_destroy_connection(m_impl->m_connection);
    throw;
  }

  m_impl->SetIsConnected(true);
}
Esempio n. 5
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;
}
Esempio n. 6
0
int main(int argc, char const *const *argv)
{
  char const *hostname;
  int port;
  amqp_socket_t *socket;
  amqp_connection_state_t conn;
  struct timeval tval;
  struct timeval *tv;

  if (argc < 3) {
    fprintf(stderr, "Usage: amqp_connect_timeout host port [timeout_sec [timeout_usec=0]]\n");
    return 1;
  }

  if (argc > 3) {
    tv = &tval;

    tv->tv_sec = atoi(argv[3]);

    if (argc > 4 ) {
      tv->tv_usec = atoi(argv[4]);
    } else {
      tv->tv_usec = 0;
    }

  } else {
    tv = NULL;
  }


  hostname = argv[1];
  port = atoi(argv[2]);

  conn = amqp_new_connection();

  socket = amqp_tcp_socket_new(conn);

  if (!socket) {
    die("creating TCP socket");
  }

  die_on_error(amqp_socket_open_noblock(socket, hostname, port, tv), "opening TCP socket");

  die_on_amqp_error(amqp_login(conn, "/", 0, 131072, 0, AMQP_SASL_METHOD_PLAIN, "guest", "guest"), "Logging in");

  die_on_amqp_error(amqp_connection_close(conn, AMQP_REPLY_SUCCESS), "Closing connection");
  die_on_error(amqp_destroy_connection(conn), "Ending connection");

  printf ("Done\n");
  return 0;
}
int main(int argc, char const * const *argv) {
  char const *hostname;
  int port;
  char const *exchange;
  char const *routingkey;
  char const *messagebody;

  int sockfd;
  amqp_connection_state_t conn;

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

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

  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, 1);
  die_on_amqp_error(amqp_get_rpc_reply(conn), "Opening channel");

  {
    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 */
    die_on_error(amqp_basic_publish(conn,
				    1,
				    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;
}
Esempio n. 8
0
static int noit_rabbimq_connect(iep_thread_driver_t *dr) {
  struct amqp_driver *driver = (struct amqp_driver *)dr;

  if(!driver->connection) {
    int sidx = driver->nconnects++ % driver->nhosts;
    struct timeval timeout;
    amqp_rpc_reply_t r, *rptr;

    noitL(noit_error, "AMQP connect: %s:%d\n",
          driver->hostname[sidx], driver->port);
    BUMPSTAT(connects);
    driver->hostidx = sidx;
    timeout.tv_sec = driver->heartbeat;
    timeout.tv_usec = 0;
    driver->sockfd = amqp_open_socket(driver->hostname[sidx], driver->port, &timeout);
    if(driver->sockfd < 0) {
      noitL(noit_error, "AMQP connect failed: %s:%d\n",
            driver->hostname[sidx], driver->port);
      return -1;
    }
    driver->has_error = 0;
    driver->connection = amqp_new_connection();
    amqp_set_basic_return_cb(driver->connection, noit_rabbitmq_brcb, driver);
    amqp_set_sockfd(driver->connection, driver->sockfd);
    r = amqp_login(driver->connection,
                   driver->vhost, 0, 131072, driver->heartbeat,
                   AMQP_SASL_METHOD_PLAIN,
                   driver->username, driver->password);
    if(r.reply_type != AMQP_RESPONSE_NORMAL) {
      noitL(noit_error, "AMQP login failed\n");
      amqp_connection_close(driver->connection, AMQP_REPLY_SUCCESS);
      amqp_destroy_connection(driver->connection);
      driver->connection = NULL;
      return -1;
    }

    amqp_channel_open(driver->connection, 1);
    rptr = amqp_get_rpc_reply();
    if(rptr->reply_type != AMQP_RESPONSE_NORMAL) {
      noitL(noit_error, "AMQP channe_open failed\n");
      amqp_connection_close(driver->connection, AMQP_REPLY_SUCCESS);
      amqp_destroy_connection(driver->connection);
      driver->connection = NULL;
      return -1;
    }
    gettimeofday(&driver->last_hb, NULL);
    return 0;
  }
  /* 1 means already connected */
  return 1;
}
Esempio n. 9
0
int main(int argc, char const *const *argv)
{
  char const *hostname;
  int port, status;
  char const *exchange;
  char const *bindingkey;
  char const *queue;
  amqp_socket_t *socket = NULL;
  amqp_connection_state_t conn;

  if (argc < 6) {
    fprintf(stderr, "Usage: amqp_bind host port exchange bindingkey queue\n");
    return 1;
  }

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

  conn = amqp_new_connection();

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

  status = amqp_socket_open(socket, hostname, port);
  if (status) {
    die("opening TCP socket");
  }

  amqp_set_socket(conn, socket);
  die_on_amqp_error(amqp_login(conn, "/", 0, 131072, 0, AMQP_SASL_METHOD_PLAIN, "guest", "guest"),
                    "Logging in");
  amqp_channel_open(conn, 1);
  die_on_amqp_error(amqp_get_rpc_reply(conn), "Opening channel");

  amqp_queue_bind(conn, 1,
                  amqp_cstring_bytes(queue),
                  amqp_cstring_bytes(exchange),
                  amqp_cstring_bytes(bindingkey),
                  amqp_empty_table);
  die_on_amqp_error(amqp_get_rpc_reply(conn), "Unbinding");

  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;
}
Esempio n. 10
0
void RabbitMQConnection::_rabbitMQConnection(const std::string& hostname, int port, const std::string& vhost,
		const std::string& user, const std::string& password) {
	this->channel_n=0;
	this->conn = amqp_new_connection();
	amqp_socket_t * socket = amqp_tcp_socket_new(conn);
	if (!socket) {
		die("creating TCP socket");
	}
	int status = amqp_socket_open(socket, hostname.c_str(), port);
	if (status) {
		die("opening TCP socket");
	}
	die_on_amqp_error(amqp_login(this->conn, vhost.c_str(), 0, 131072, 60, AMQP_SASL_METHOD_PLAIN, user.c_str(), password.c_str()),
			                    "Logging in");
}
Esempio n. 11
0
static amqp_connection_state_t get_amqp_connection(void)
{
    int         status;
    amqp_connection_state_t conn;
    amqp_rpc_reply_t    reply;
    amqp_socket_t       *socket = NULL;

    conn = amqp_new_connection();
    if (!conn) {
        fprintf(stderr, "[!] Error getting ampq connection\n");
        return NULL;
    }

    socket = amqp_tcp_socket_new(conn);
    if (!socket) {
        amqp_destroy_connection(conn);
        fprintf(stderr, "[!] Error creating the TCP socket!\n");
        return NULL;
    }

    status = amqp_socket_open(socket, "localhost", 5672);
    if (status) {
        amqp_connection_close(conn, AMQP_REPLY_SUCCESS);
        amqp_destroy_connection(conn);
        fprintf(stderr, "[!] Error opening the TCP socket!\n");
        return NULL;
    }

    reply = amqp_login(conn, "/", 0, 131072, 0, AMQP_SASL_METHOD_PLAIN,
               "guest", "guest");
    if (reply.reply_type != AMQP_RESPONSE_NORMAL) {
        amqp_connection_close(conn, AMQP_REPLY_SUCCESS);
        amqp_destroy_connection(conn);
        fprintf(stderr, "[!] Error loggging into server\n");
        return NULL;
    }

    if (!amqp_channel_open(conn, 1)) {
        amqp_channel_close(conn, 1, AMQP_REPLY_SUCCESS);
        amqp_connection_close(conn, AMQP_REPLY_SUCCESS);
        fprintf(stderr, "[!] Error opening channel 1\n");
        return NULL;
    }

    return conn;
}
Esempio n. 12
0
/**
 * 	php_amqp_connect
 *	handles connecting to amqp
 *	called by connect() and reconnect()
 */
void php_amqp_connect(amqp_connection_object *amqp_connection)
{
	char str[256];
	char ** pstr = (char **) &str;
	void * old_handler;

	/* create the connection */
	amqp_connection->conn = amqp_new_connection();

	amqp_connection->fd = amqp_open_socket(amqp_connection->host, amqp_connection->port);

	if (amqp_connection->fd < 1) {
		/* Start ignoring SIGPIPE */
		old_handler = signal(SIGPIPE, SIG_IGN);

		amqp_destroy_connection(amqp_connection->conn);

		/* End ignoring of SIGPIPEs */
		signal(SIGPIPE, old_handler);

		zend_throw_exception(amqp_connection_exception_class_entry, "Socket error: could not connect to host.", 0 TSRMLS_CC);
		return;
	}
	amqp_connection->is_connected = '\1';

	amqp_set_sockfd(amqp_connection->conn, amqp_connection->fd);

	amqp_rpc_reply_t x = amqp_login(amqp_connection->conn, amqp_connection->vhost, 0, FRAME_MAX, AMQP_HEARTBEAT, AMQP_SASL_METHOD_PLAIN, amqp_connection->login, amqp_connection->password);

	if (x.reply_type != AMQP_RESPONSE_NORMAL) {
		amqp_error(x, pstr);
		zend_throw_exception(amqp_connection_exception_class_entry, *pstr, 0 TSRMLS_CC);
		return;
	}

	amqp_channel_open(amqp_connection->conn, AMQP_CHANNEL);

	x = amqp_get_rpc_reply(amqp_connection->conn);
	if (x.reply_type != AMQP_RESPONSE_NORMAL) {
		amqp_error(x, pstr);
		zend_throw_exception(amqp_connection_exception_class_entry, *pstr, 0 TSRMLS_CC);
		return;
	}

	amqp_connection->is_channel_connected = '\1';
}
Esempio n. 13
0
static int rmq_reconnect(evi_reply_sock *sock)
{
	rmq_params_t * rmqp = (rmq_params_t *)sock->params;

	if (!rmqp || !(rmqp->flags & RMQ_PARAM_EXCH)) {
		LM_ERR("not enough socket info\n");
		return -1;
	}
//	rmq_print(sock);
	if (!(rmqp->flags & RMQ_PARAM_CONN) || !rmqp->conn) {
		/* init new connection */
		if (!(rmqp->conn = amqp_new_connection())) {
			LM_ERR("cannot create new connection\n");
			return -1;
		}
		rmqp->flags |= RMQ_PARAM_CONN;
		rmqp->sock = amqp_open_socket(sock->address.s, sock->port);
		if (rmqp->sock < 0) {
			LM_ERR("cannot opens socket\n");
			goto destroy_rmqp;
		}
		amqp_set_sockfd(rmqp->conn, rmqp->sock);

		if (rmq_error("Logging in", amqp_login(rmqp->conn,
				RMQ_DEFAULT_VHOST,
				0,
				RMQ_DEFAULT_MAX,
				0,
				AMQP_SASL_METHOD_PLAIN,
				rmqp->flags & RMQ_PARAM_USER ? rmqp->user.s : RMQ_DEFAULT_UP,
				rmqp->flags & RMQ_PARAM_PASS ? rmqp->pass.s : RMQ_DEFAULT_UP)))
			goto destroy_rmqp;
	}
	if (!(rmqp->flags & RMQ_PARAM_CHAN)) {
		rmqp->channel = 1;
		amqp_channel_open(rmqp->conn, rmqp->channel);
		rmqp->flags |= RMQ_PARAM_CHAN;
		if (rmq_error("Opening channel", amqp_get_rpc_reply(rmqp->conn)))
			goto destroy_rmqp;
	}
	return 0;
destroy_rmqp:
	rmq_destroy_param(rmqp);
	return -1;
}
Esempio n. 14
0
amqp_connection_state_t make_connection(void)
{
  int status;
  amqp_socket_t *socket = NULL;
  struct amqp_uri *uri = alloc_amqp_uri();
  amqp_connection_state_t conn;

  init_connection_info(uri);
  conn = amqp_new_connection();
  if (uri->ssl) {
#ifdef WITH_SSL
    socket = amqp_ssl_socket_new(conn);
    if (!socket) {
      die("creating SSL/TLS socket");
    }
    if (amqp_cacert) {
      amqp_ssl_socket_set_cacert(socket, amqp_cacert);
    }
    if (amqp_key) {
      amqp_ssl_socket_set_key(socket, amqp_cert, amqp_key);
    }
#else
    die("librabbitmq was not built with SSL/TLS support");
#endif
  } else {
    socket = amqp_tcp_socket_new(conn);
    if (!socket) {
      die("creating TCP socket (out of memory)");
    }
  }
  host_port_t * hp = ((host_port_t *)uri->host_port_array.elts);
  status = amqp_socket_open(socket, hp->host, hp->port);
  if (status) {
    die("opening socket to %s:%d", hp->host, hp->port);
  }
  die_rpc(amqp_login(conn, uri->vhost, 0, 131072, amqp_heartbeat,
                     AMQP_SASL_METHOD_PLAIN,
                     uri->user, uri->password),
          "logging in to AMQP server");
  if (!amqp_channel_open(conn, 1)) {
    die_rpc(amqp_get_rpc_reply(conn), "opening channel");
  }
  free_amqp_uri(uri);
  return conn;
}
Esempio n. 15
0
void AMQP::sockConnect() {
	cnn = amqp_new_connection();
	sockfd = amqp_tcp_socket_new(cnn);
	if (!sockfd)
	{
		amqp_destroy_connection(cnn);
		throw AMQPException("AMQP cannot create socket descriptor");
	}

	//cout << "sockfd="<< sockfd  << "  pid=" <<  getpid() <<endl;
	int status = amqp_socket_open(sockfd, host.c_str(), port);
	if (status != AMQP_STATUS_OK)
	{
	    amqp_connection_close(cnn, AMQP_REPLY_SUCCESS);
	    amqp_destroy_connection(cnn);
	    throw AMQPException("AMQP cannot open socket");
	}
}
Esempio n. 16
0
amqp_connection_state_t make_connection(void)
{
  int status;
  amqp_socket_t *socket = NULL;
  struct amqp_connection_info ci;
  amqp_connection_state_t conn;

  init_connection_info(&ci);
  conn = amqp_new_connection();
  if (ci.ssl) {
#ifdef WITH_SSL
    socket = amqp_ssl_socket_new();
    if (!socket) {
      die("creating SSL/TLS socket");
    }
    if (amqp_cacert) {
      amqp_ssl_socket_set_cacert(socket, amqp_cacert);
    }
    if (amqp_key) {
      amqp_ssl_socket_set_key(socket, amqp_cert, amqp_key);
    }
#else
    die("librabbitmq was not built with SSL/TLS support");
#endif
  } else {
    socket = amqp_tcp_socket_new();
    if (!socket) {
      die("creating TCP socket (out of memory)");
    }
  }
  status = amqp_socket_open(socket, ci.host, ci.port);
  if (status) {
    die("opening socket to %s:%d", ci.host, ci.port);
  }
  amqp_set_socket(conn, socket);
  die_rpc(amqp_login(conn, ci.vhost, 0, 131072, 0,
                     AMQP_SASL_METHOD_PLAIN,
                     ci.user, ci.password),
          "logging in to AMQP server");
  if (!amqp_channel_open(conn, 1)) {
    die_rpc(amqp_get_rpc_reply(conn), "opening channel");
  }
  return conn;
}
Esempio n. 17
0
int main(int argc, char const *const *argv)
{
  char const *hostname;
  int port, status;
  int rate_limit;
  int message_count;
  amqp_socket_t *socket = NULL;
  amqp_connection_state_t conn;

  if (argc < 5) {
    fprintf(stderr, "Usage: amqp_producer host port rate_limit message_count\n");
    return 1;
  }

  hostname = argv[1];
  port = atoi(argv[2]);
  rate_limit = atoi(argv[3]);
  message_count = atoi(argv[4]);

  conn = amqp_new_connection();

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

  status = amqp_socket_open(socket, hostname, port);
  if (status) {
    die("opening TCP socket");
  }

  die_on_amqp_error(amqp_login(conn, "/", 0, 131072, 0, AMQP_SASL_METHOD_PLAIN, "guest", "guest"),
                    "Logging in");
  amqp_channel_open(conn, 1);
  die_on_amqp_error(amqp_get_rpc_reply(conn), "Opening channel");

  send_batch(conn, "test queue", rate_limit, message_count);

  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;
}
Esempio n. 18
0
amqp_connection_state_t setup_connection_and_channel(void) {
  amqp_connection_state_t connection_state_ = amqp_new_connection();

  amqp_socket_t *socket = amqp_tcp_socket_new(connection_state_);
  assert(socket);

  int rc = amqp_socket_open(socket, "localhost", AMQP_PROTOCOL_PORT);
  assert(rc == AMQP_STATUS_OK);

  amqp_rpc_reply_t rpc_reply = amqp_login(
      connection_state_, "/", 1, AMQP_DEFAULT_FRAME_SIZE, AMQP_DEFAULT_HEARTBEAT,
      AMQP_SASL_METHOD_PLAIN, "guest", "guest");
  assert(rpc_reply.reply_type == AMQP_RESPONSE_NORMAL);

  amqp_channel_open_ok_t *res =
      amqp_channel_open(connection_state_, fixed_channel_id);
  assert(res != NULL);

  return connection_state_;
}
Esempio n. 19
0
/**
 * Associate a new session with this instance of the filter and opens
 * a connection to the server and prepares the exchange and the queue for use.
 *
 *
 * @param instance	The filter instance data
 * @param session	The session itself
 * @return Session specific data for this session
 */
static	void	*
newSession(FILTER *instance, SESSION *session)
{
  MQ_INSTANCE	*my_instance = (MQ_INSTANCE *)instance;
  MQ_SESSION	*my_session;
  
  if ((my_session = calloc(1, sizeof(MQ_SESSION))) != NULL){

    if((my_session->conn = amqp_new_connection()) == NULL){
      free(my_session);
      return NULL;
    }
    spinlock_acquire(my_instance->rconn_lock);  
    init_conn(my_instance,my_session);
    my_session->was_query = 0;
    my_session->uid = NULL;
    spinlock_release(my_instance->rconn_lock);      
  }

  return my_session;
}
Esempio n. 20
0
static
amqp_connection_state_t setup_amqp_connection()
{
    amqp_connection_state_t connection = amqp_new_connection();
    amqp_socket_t *socket = amqp_tcp_socket_new(connection);

#ifdef FIX_SIG_PIPE
    // why doesn't librabbitmq do this, eh?
    int sockfd = amqp_get_sockfd(connection);
    int one = 1; //
    setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof(one));
#endif

    int status = amqp_socket_open(socket, rabbit_host, rabbit_port);
    assert_x(!status, "Opening RabbitMQ socket", __FILE__, __LINE__);

    die_on_amqp_error(amqp_login(connection, "/", 0, OUR_FRAME_MAX, 0, AMQP_SASL_METHOD_PLAIN, "guest", "guest"),
                      "Logging in to RabbitMQ");
    amqp_channel_open(connection, 1);
    die_on_amqp_error(amqp_get_rpc_reply(connection), "Opening AMQP channel");

    return connection;
}
Esempio n. 21
0
Channel::Channel(const std::string &host, int port, const std::string &username,
                 const std::string &password, const std::string &vhost,
                 int frame_max)
    : m_impl(new Detail::ChannelImpl) {
  m_impl->m_connection = amqp_new_connection();

  if (NULL == m_impl->m_connection) {
    throw std::bad_alloc();
  }

  try {
    amqp_socket_t *socket = amqp_tcp_socket_new(m_impl->m_connection);
    int sock = amqp_socket_open(socket, host.c_str(), port);
    m_impl->CheckForError(sock);

    m_impl->DoLogin(username, password, vhost, frame_max);
  } catch (...) {
    amqp_destroy_connection(m_impl->m_connection);
    throw;
  }

  m_impl->SetIsConnected(true);
}
int main(int argc, char const * const *argv) {
  char const *hostname;
  int port;
  char const *exchange;
  char const *exchangetype;

  int sockfd;
  amqp_connection_state_t conn;

  if (argc < 5) {
    fprintf(stderr, "Usage: amqp_exchange_declare host port exchange exchangetype\n");
    return 1;
  }

  hostname = argv[1];
  port = atoi(argv[2]);
  exchange = argv[3];
  exchangetype = argv[4];

  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, 1);
  die_on_amqp_error(amqp_get_rpc_reply(conn), "Opening channel");

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

  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;
}
Esempio n. 23
0
void AMQP::sockConnect() {
	int status;
	cnn = amqp_new_connection();

	switch(proto) {
		case AMQPS_proto: {
			sockfd = amqp_ssl_socket_new(cnn);

			status = amqp_ssl_socket_set_cacert(sockfd, cacert_path.c_str());
			if (status) {
				throw AMQPException("AMQP cannot set CA certificate");
			}

			status = amqp_ssl_socket_set_key(sockfd, client_cert_path.c_str(), client_key_path.c_str());
			if (status) {
				throw AMQPException("AMQP cannot set client certificate or key");
			}

			amqp_ssl_socket_set_verify_peer(sockfd, verify_peer ? 1 : 0);
			amqp_ssl_socket_set_verify_hostname(sockfd, verify_hostname ? 1 : 0);
		}
		break;

		case AMQP_proto:
		default:
			sockfd = amqp_tcp_socket_new(cnn);
			break;
	}


	status = amqp_socket_open(sockfd, host.c_str(), port);

	if (status){
		amqp_destroy_connection(cnn);
		throw AMQPException("AMQP cannot create socket");
	}
}
Esempio n. 24
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;
}
RabbitMQConnection::RabbitMQConnection (const std::string &address, int port) :
  address (address), port (port)
{
  conn = amqp_new_connection();

  socket = amqp_tcp_socket_new (conn);

  if (!socket) {
    throw Glib::IOChannelError (Glib::IOChannelError::Code::FAILED,
                                "Cannot create TCP socket");
  }

  if (amqp_socket_open (socket, address.c_str(), port) ) {
    throw Glib::IOChannelError (Glib::IOChannelError::Code::FAILED,
                                "Cannot open TCP socket");
  }

  makeSocketLinger (amqp_socket_get_sockfd (socket) );

  exception_on_error (amqp_login (conn, "/", 0, 131072, 0, AMQP_SASL_METHOD_PLAIN,
                                  "guest", "guest"), "Loging in");
  amqp_channel_open (conn, 1);
  exception_on_error (amqp_get_rpc_reply (conn), "Opening channel");
}
Esempio n. 26
0
static int camqp_connect (camqp_config_t *conf) /* {{{ */
{
    amqp_rpc_reply_t reply;
    int sockfd;
    int status;

    if (conf->connection != NULL)
        return (0);

    conf->connection = amqp_new_connection ();
    if (conf->connection == NULL)
    {
        ERROR ("amqp plugin: amqp_new_connection failed.");
        return (ENOMEM);
    }

    sockfd = amqp_open_socket (CONF(conf, host), conf->port);
    if (sockfd < 0)
    {
        char errbuf[1024];
        status = (-1) * sockfd;
        ERROR ("amqp plugin: amqp_open_socket failed: %s",
                sstrerror (status, errbuf, sizeof (errbuf)));
        amqp_destroy_connection (conf->connection);
        conf->connection = NULL;
        return (status);
    }
    amqp_set_sockfd (conf->connection, sockfd);

    reply = amqp_login (conf->connection, CONF(conf, vhost),
            /* channel max = */      0,
            /* frame max   = */ 131072,
            /* heartbeat   = */      0,
            /* authentication = */ AMQP_SASL_METHOD_PLAIN,
            CONF(conf, user), CONF(conf, password));
    if (reply.reply_type != AMQP_RESPONSE_NORMAL)
    {
        ERROR ("amqp plugin: amqp_login (vhost = %s, user = %s) failed.",
                CONF(conf, vhost), CONF(conf, user));
        amqp_destroy_connection (conf->connection);
        close (sockfd);
        conf->connection = NULL;
        return (1);
    }

    amqp_channel_open (conf->connection, /* channel = */ 1);
    /* FIXME: Is checking "reply.reply_type" really correct here? How does
     * it get set? --octo */
    if (reply.reply_type != AMQP_RESPONSE_NORMAL)
    {
        ERROR ("amqp plugin: amqp_channel_open failed.");
        amqp_connection_close (conf->connection, AMQP_REPLY_SUCCESS);
        amqp_destroy_connection (conf->connection);
        close(sockfd);
        conf->connection = NULL;
        return (1);
    }

    INFO ("amqp plugin: Successfully opened connection to vhost \"%s\" "
            "on %s:%i.", CONF(conf, vhost), CONF(conf, host), conf->port);

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

    if (!conf->publish)
        return (camqp_setup_queue (conf));
    return (0);
} /* }}} int camqp_connect */
Esempio n. 27
0
static int rmq_reconnect(evi_reply_sock *sock)
{
	rmq_params_t * rmqp = (rmq_params_t *)sock->params;
#if defined AMQP_VERSION_v04
	amqp_socket_t *amqp_sock;
#endif
	int socket;

	if (!rmqp || !(rmqp->flags & RMQ_PARAM_RKEY)) {
		LM_ERR("not enough socket info\n");
		return -1;
	}
	if (!(rmqp->flags & RMQ_PARAM_CONN) || !rmqp->conn) {
		/* init new connection */
		if (!(rmqp->conn = amqp_new_connection())) {
			LM_ERR("cannot create new connection\n");
			return -1;
		}
		rmqp->flags |= RMQ_PARAM_CONN;
#if defined AMQP_VERSION_v04
		amqp_sock = amqp_tcp_socket_new(rmqp->conn);
		if (!amqp_sock) {
			LM_ERR("cannot create AMQP socket\n");
			goto destroy_rmqp;
		}
		socket = amqp_socket_open(amqp_sock, sock->address.s, sock->port);
		if (socket < 0) {
			LM_ERR("cannot open AMQP socket\n");
			goto destroy_rmqp;
		}
#else
		socket = amqp_open_socket(sock->address.s, sock->port);
		if (socket < 0) {
			LM_ERR("cannot open AMQP socket\n");
			goto destroy_rmqp;
		}
		amqp_set_sockfd(rmqp->conn, socket);
#endif

		if (rmq_error("Logging in", amqp_login(
				rmqp->conn,
				RMQ_DEFAULT_VHOST,
				0,
				RMQ_DEFAULT_MAX,
				rmqp->heartbeat,
				AMQP_SASL_METHOD_PLAIN,
				rmqp->flags & RMQ_PARAM_USER ? rmqp->user.s : RMQ_DEFAULT_UP,
				rmqp->flags & RMQ_PARAM_PASS ? rmqp->pass.s : RMQ_DEFAULT_UP)))
			goto destroy_rmqp;
	}
	if (!(rmqp->flags & RMQ_PARAM_CHAN)) {
		rmqp->channel = 1;
		amqp_channel_open(rmqp->conn, rmqp->channel);
		rmqp->flags |= RMQ_PARAM_CHAN;
		if (rmq_error("Opening channel", amqp_get_rpc_reply(rmqp->conn)))
			goto destroy_rmqp;
	}
	return 0;
destroy_rmqp:
	rmq_destroy_param(rmqp);
	return -1;
}
Esempio n. 28
0
/**
 * Create an instance of the filter for a particular service
 * within MaxScale.
 * 
 * @param options	The options for this filter
 *
 * @return The instance data for this new instance
 */
static	FILTER	*
createInstance(char **options, FILTER_PARAMETER **params)
{
  MQ_INSTANCE	*my_instance;
  int paramcount = 0, parammax = 64, i = 0, x = 0, arrsize = 0;
  FILTER_PARAMETER** paramlist;  
  char** arr;
  char taskname[512];
  
  if ((my_instance = calloc(1, sizeof(MQ_INSTANCE))))
    {
      spinlock_init(&my_instance->rconn_lock);
      spinlock_init(&my_instance->msg_lock);
      uid_gen = 0;
      paramlist = malloc(sizeof(FILTER_PARAMETER*)*64);

      if((my_instance->conn = amqp_new_connection()) == NULL){


	return NULL;
      }
      my_instance->channel = 1;
      my_instance->last_rconn = time(NULL);
      my_instance->conn_stat = AMQP_STATUS_OK;
      my_instance->rconn_intv = 1;
      my_instance->port = 5672;
      my_instance->trgtype = TRG_ALL;
      my_instance->log_all = false;
      my_instance->strict_logging = true;

      for(i = 0;params[i];i++){
	if(!strcmp(params[i]->name,"hostname")){
	  my_instance->hostname = strdup(params[i]->value);
	}else if(!strcmp(params[i]->name,"username")){
	  my_instance->username = strdup(params[i]->value);
	}else if(!strcmp(params[i]->name,"password")){
	  my_instance->password = strdup(params[i]->value);
	}else if(!strcmp(params[i]->name,"vhost")){
	  my_instance->vhost = strdup(params[i]->value);
	}else if(!strcmp(params[i]->name,"port")){
	  my_instance->port = atoi(params[i]->value);
	}else if(!strcmp(params[i]->name,"exchange")){
	  my_instance->exchange = strdup(params[i]->value);  
	}else if(!strcmp(params[i]->name,"key")){
	  my_instance->key = strdup(params[i]->value);
	}else if(!strcmp(params[i]->name,"queue")){
	  my_instance->queue = strdup(params[i]->value);
	}
	else if(!strcmp(params[i]->name,"ssl_client_certificate")){

	  my_instance->ssl_client_cert = strdup(params[i]->value);
	
	}else if(!strcmp(params[i]->name,"ssl_client_key")){

	  my_instance->ssl_client_key = strdup(params[i]->value);
	  
	}else if(!strcmp(params[i]->name,"ssl_CA_cert")){

	  my_instance->ssl_CA_cert = strdup(params[i]->value);

	}else if(!strcmp(params[i]->name,"exchange_type")){

	  my_instance->exchange_type = strdup(params[i]->value);

	}else if(!strcmp(params[i]->name,"logging_trigger")){
	  
	  arr = parse_optstr(params[i]->value,",",&arrsize);

	  for(x = 0;x<arrsize;x++){
	    if(!strcmp(arr[x],"source")){
	      my_instance->trgtype |= TRG_SOURCE;
	    }else if(!strcmp(arr[x],"schema")){
	      my_instance->trgtype |= TRG_SCHEMA;
	    }else if(!strcmp(arr[x],"object")){
	      my_instance->trgtype |= TRG_OBJECT;
	    }else if(!strcmp(arr[x],"all")){
	      my_instance->trgtype = TRG_ALL;
	    }else{
	      skygw_log_write(LOGFILE_ERROR,"Error: Unknown option for 'logging_trigger':%s.",arr[x]);
	    }
	  }

	  if(arrsize > 0){
	    free(arr);
	  }
	  arrsize = 0;
	  


	}else if(strstr(params[i]->name,"logging_")){

	  if(paramcount < parammax){
	    paramlist[paramcount] = malloc(sizeof(FILTER_PARAMETER));
	    paramlist[paramcount]->name = strdup(params[i]->name);
	    paramlist[paramcount]->value = strdup(params[i]->value);
	    paramcount++;
	  }	  
	  
	}

      }

      if(my_instance->trgtype & TRG_SOURCE){

        my_instance->src_trg = (SRC_TRIG*)malloc(sizeof(SRC_TRIG));
        my_instance->src_trg->user = NULL;
        my_instance->src_trg->host = NULL;
        my_instance->src_trg->usize = 0;
	my_instance->src_trg->hsize = 0;	

      }

      if(my_instance->trgtype & TRG_SCHEMA){

        my_instance->shm_trg = (SHM_TRIG*)malloc(sizeof(SHM_TRIG));
        my_instance->shm_trg->objects = NULL;
        my_instance->shm_trg->size = 0;

      }

      if(my_instance->trgtype & TRG_OBJECT){

        my_instance->obj_trg = (OBJ_TRIG*)malloc(sizeof(OBJ_TRIG));
        my_instance->obj_trg->objects = NULL;
        my_instance->obj_trg->size = 0;

      }

      for(i = 0;i<paramcount;i++){

	if(!strcmp(paramlist[i]->name,"logging_source_user")){
	    
	  if(my_instance->src_trg){
	    my_instance->src_trg->user = parse_optstr(paramlist[i]->value,",",&arrsize);
	    my_instance->src_trg->usize = arrsize;
	    arrsize = 0;
	  }

	}else if(!strcmp(paramlist[i]->name,"logging_source_host")){
	    
	  if(my_instance->src_trg){
	    my_instance->src_trg->host = parse_optstr(paramlist[i]->value,",",&arrsize);
	    my_instance->src_trg->hsize = arrsize;
	    arrsize = 0;
	  }

	}else if(!strcmp(paramlist[i]->name,"logging_schema")){
	    
	  if(my_instance->shm_trg){
	    my_instance->shm_trg->objects = parse_optstr(paramlist[i]->value,",",&arrsize);
	    my_instance->shm_trg->size = arrsize;
	    arrsize = 0;
	  }

	}else if(!strcmp(paramlist[i]->name,"logging_object")){
	    
	  if(my_instance->obj_trg){
	    my_instance->obj_trg->objects = parse_optstr(paramlist[i]->value,",",&arrsize);
	    my_instance->obj_trg->size = arrsize;
	    arrsize = 0;
	  }

	}else if(!strcmp(paramlist[i]->name,"logging_log_all")){
	  if(config_truth_value(paramlist[i]->value)){
	    my_instance->log_all = true;
	  }
	}else if(!strcmp(paramlist[i]->name,"logging_strict")){
	  if(!config_truth_value(paramlist[i]->value)){
	    my_instance->strict_logging = false;
	  }
	}
	free(paramlist[i]->name);
	free(paramlist[i]->value);
	free(paramlist[i]);
      }

      free(paramlist);
      
      if(my_instance->hostname == NULL){
	my_instance->hostname = strdup("localhost");	
      }
      if(my_instance->username == NULL){
	my_instance->username = strdup("guest");	
      }
      if(my_instance->password == NULL){
	my_instance->password = strdup("guest");	
      }
      if(my_instance->vhost == NULL){
	my_instance->vhost = strdup("/");	
      }
      if(my_instance->exchange == NULL){
	my_instance->exchange = strdup("default_exchange");	
      }
      if(my_instance->key == NULL){
	my_instance->key = strdup("key");
      }
      if(my_instance->exchange_type == NULL){
	my_instance->exchange_type = strdup("direct");
      }

      if(my_instance->ssl_client_cert != NULL &&
	 my_instance->ssl_client_key != NULL &&
	 my_instance->ssl_CA_cert != NULL){
	my_instance->use_ssl = true;
      }else{
	my_instance->use_ssl = false;
      }
      
      if(my_instance->use_ssl){
	amqp_set_initialize_ssl_library(0);/**Assume the underlying SSL library is already initialized*/
      }
      
      /**Connect to the server*/
      init_conn(my_instance);

      snprintf(taskname,511,"mqtask%d",atomic_add(&hktask_id,1));
      hktask_add(taskname,sendMessage,(void*)my_instance,5);

    }
  return (FILTER *)my_instance;
}
Esempio n. 29
0
int main(int argc, char const *const *argv)
{
  char const *hostname;
  int port, status;
  char const *queuename;
  amqp_socket_t *socket;
  amqp_connection_state_t conn;

  if (argc < 4) {
    fprintf(stderr, "Usage: amqps_listenq host port queuename "
            "[cacert.pem [key.pem cert.pem]]\n");
    return 1;
  }

  hostname = argv[1];
  port = atoi(argv[2]);
  queuename = argv[3];

  conn = amqp_new_connection();

  socket = amqp_ssl_socket_new();
  if (!socket) {
    die("creating SSL/TLS socket");
  }

  if (argc > 4) {
    status = amqp_ssl_socket_set_cacert(socket, argv[4]);
    if (status) {
      die("setting CA certificate");
    }
  }

  if (argc > 6) {
    status = amqp_ssl_socket_set_key(socket, argv[6], argv[5]);
    if (status) {
      die("setting client cert");
    }
  }

  status = amqp_socket_open(socket, hostname, port);
  if (status) {
    die("opening SSL/TLS connection");
  }

  amqp_set_socket(conn, socket);
  die_on_amqp_error(amqp_login(conn, "/", 0, 131072, 0, AMQP_SASL_METHOD_PLAIN, "guest", "guest"),
                    "Logging in");
  amqp_channel_open(conn, 1);
  die_on_amqp_error(amqp_get_rpc_reply(conn), "Opening channel");

  amqp_basic_consume(conn, 1, amqp_cstring_bytes(queuename), amqp_empty_bytes, 0, 0, 0, amqp_empty_table);
  die_on_amqp_error(amqp_get_rpc_reply(conn), "Consuming");

  {
    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;
        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;
      }

      amqp_basic_ack(conn, 1, d->delivery_tag, 0);
    }
  }

  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;
}
Esempio n. 30
0
static int camqp_connect (camqp_config_t *conf) /* {{{ */
{
    static time_t last_connect_time = 0;

    amqp_rpc_reply_t reply;
    int status;
#ifdef HAVE_AMQP_TCP_SOCKET
    amqp_socket_t *socket;
#else
    int sockfd;
#endif

    if (conf->connection != NULL)
        return (0);

    time_t now = time(NULL);
    if (now < (last_connect_time + conf->connection_retry_delay))
    {
        DEBUG("amqp plugin: skipping connection retry, "
            "ConnectionRetryDelay: %d", conf->connection_retry_delay);
        return(1);
    }
    else
    {
        DEBUG ("amqp plugin: retrying connection");
        last_connect_time = now;
    }

    conf->connection = amqp_new_connection ();
    if (conf->connection == NULL)
    {
        ERROR ("amqp plugin: amqp_new_connection failed.");
        return (ENOMEM);
    }

#ifdef HAVE_AMQP_TCP_SOCKET
# define CLOSE_SOCKET() /* amqp_destroy_connection() closes the socket for us */
    /* TODO: add support for SSL using amqp_ssl_socket_new
     *       and related functions */
    socket = amqp_tcp_socket_new (conf->connection);
    if (! socket)
    {
        ERROR ("amqp plugin: amqp_tcp_socket_new failed.");
        amqp_destroy_connection (conf->connection);
        conf->connection = NULL;
        return (ENOMEM);
    }

    status = amqp_socket_open (socket, CONF(conf, host), conf->port);
    if (status < 0)
    {
        char errbuf[1024];
        status *= -1;
        ERROR ("amqp plugin: amqp_socket_open failed: %s",
                sstrerror (status, errbuf, sizeof (errbuf)));
        amqp_destroy_connection (conf->connection);
        conf->connection = NULL;
        return (status);
    }
#else /* HAVE_AMQP_TCP_SOCKET */
# define CLOSE_SOCKET() close(sockfd)
    /* this interface is deprecated as of rabbitmq-c 0.4 */
    sockfd = amqp_open_socket (CONF(conf, host), conf->port);
    if (sockfd < 0)
    {
        char errbuf[1024];
        status = (-1) * sockfd;
        ERROR ("amqp plugin: amqp_open_socket failed: %s",
                sstrerror (status, errbuf, sizeof (errbuf)));
        amqp_destroy_connection (conf->connection);
        conf->connection = NULL;
        return (status);
    }
    amqp_set_sockfd (conf->connection, sockfd);
#endif

    reply = amqp_login (conf->connection, CONF(conf, vhost),
            /* channel max = */      0,
            /* frame max   = */ 131072,
            /* heartbeat   = */      0,
            /* authentication = */ AMQP_SASL_METHOD_PLAIN,
            CONF(conf, user), CONF(conf, password));
    if (reply.reply_type != AMQP_RESPONSE_NORMAL)
    {
        ERROR ("amqp plugin: amqp_login (vhost = %s, user = %s) failed.",
                CONF(conf, vhost), CONF(conf, user));
        amqp_destroy_connection (conf->connection);
        CLOSE_SOCKET ();
        conf->connection = NULL;
        return (1);
    }

    amqp_channel_open (conf->connection, /* channel = */ 1);
    /* FIXME: Is checking "reply.reply_type" really correct here? How does
     * it get set? --octo */
    if (reply.reply_type != AMQP_RESPONSE_NORMAL)
    {
        ERROR ("amqp plugin: amqp_channel_open failed.");
        amqp_connection_close (conf->connection, AMQP_REPLY_SUCCESS);
        amqp_destroy_connection (conf->connection);
        CLOSE_SOCKET ();
        conf->connection = NULL;
        return (1);
    }

    INFO ("amqp plugin: Successfully opened connection to vhost \"%s\" "
            "on %s:%i.", CONF(conf, vhost), CONF(conf, host), conf->port);

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

    if (!conf->publish)
        return (camqp_setup_queue (conf));
    return (0);
} /* }}} int camqp_connect */