Ejemplo n.º 1
0
        CURL* add_easy_handler(StringHash url) {
                CURL* eh = curl_easy_init();
                if (NULL == eh)
                        throw MyException("@init_easy_handler@ curl_easy_init() failed");

                Conn*  conn = (Conn*)malloc(sizeof(Conn));
                init_conn(eh, url, conn);

                curl_easy_setopt(eh, CURLOPT_URL, m_psp->get_string_from_hash(url)->c_str());
                curl_easy_setopt(eh, CURLOPT_FOLLOWLOCATION, true);
                curl_easy_setopt(eh, CURLOPT_CONNECTTIMEOUT, CONNECTION_TIMEOUT);
                curl_easy_setopt(eh, CURLOPT_TIMEOUT, CONNECTION_TIMEOUT);
                curl_easy_setopt(eh, CURLOPT_SSL_VERIFYPEER, false);
                curl_easy_setopt(eh, CURLOPT_SSL_VERIFYHOST, false);
                curl_easy_setopt(eh, CURLOPT_COOKIEFILE, ""); /* enable cookie engine */
                curl_easy_setopt(eh, CURLOPT_DNS_SERVERS, DEFAULT_DNS_SERVERS);

                curl_easy_setopt(eh, CURLOPT_USERAGENT, USERAGENT);
                curl_easy_setopt(eh, CURLOPT_WRITEFUNCTION, m_write_callback);
                curl_easy_setopt(eh, CURLOPT_WRITEDATA, conn);
                curl_easy_setopt(eh, CURLOPT_PRIVATE, conn);

                m_eh_array.insert(eh);
                m_crawling_urls.insert(url);

                curl_multi_add_handle(m_handler, eh);

                return eh;
        }
Ejemplo n.º 2
0
/*
 * Allocate and initialize connection state arrays.
 *
 * Returns 0 on success and -1 on error.
 */
static int create_conn_state(int passive_sock) {
  int ret = 0;
  size_t num_conns = g_config.conns_per_worker, i;

  /* Allocate memory. */
  conns = NULL;
  pollfds = NULL;
  free_conn_stack = NULL;
  pollfd_idxs_to_conns = NULL;

  if (!(conns = malloc(num_conns * sizeof(*conns)))
      || !(pollfds = malloc((num_conns + 1) * sizeof(*pollfds)))
      || !(free_conn_stack = malloc(num_conns * sizeof(*free_conn_stack)))
      || !(pollfd_idxs_to_conns
          = calloc(num_conns, sizeof(*pollfd_idxs_to_conns)))) {
    log_perror(NULL, "Couldn't allocate connection state arrays");
    ret = -1;
    goto cleanup;
  }

  /* Initialize connection state slots and stack of pointers to free
   * connection slots. */
  free_conn_top = free_conn_stack;

  for(i = 0; i < num_conns; ++i) {
    struct conn *p_conn = conns + i;
    p_conn->conn_idx = i;
    init_conn(p_conn);
    *(free_conn_top++) = p_conn;
  }

  /* Initialize socket pollfds. */
  for (i = 0; i <= num_conns; ++i) {
    struct pollfd *p_pollfd = pollfds + i;
    p_pollfd->fd = -1;
    p_pollfd->events = 0;
    p_pollfd->revents = 0;
  }

  /* Initialize pollfd for passive socket. */
  conn_pollfds = pollfds + 1;
  p_passive_pollfd = pollfds;
  p_passive_pollfd->fd = passive_sock;

cleanup:
  if (ret) {
    free(pollfd_idxs_to_conns);
    free(free_conn_stack);
    free(pollfds);
    free(conns);
  }
  return ret;
}
Ejemplo n.º 3
0
int PlatConnMgrAsy::send(const void * buf, int len, const unsigned int uin)
{
    int ip_idx = get_ip_idx(uin);
    if (is_estab(ip_idx) != 0)
    {
        ACE_DEBUG((LM_ERROR,
            "[%D] PlatConnMgrAsy send msg failed"
            ",intf is disconn"
            ",ip_idx=%d\n"
            , ip_idx
            ));
        if (init_conn(ip_idx) !=0)
        {
            return -1;
        }
    }
    
    PriProAck *ack = NULL; // 这里实际是向后台的请求消息 req 
    ACE_Object_Que<PriProAck>::instance()->dequeue(ack);
    if ( ack == NULL )
    {
        ACE_DEBUG((LM_ERROR,
            "[%D] PlatConnMgrAsy dequeue msg failed"
            ",maybe system has no memory\n"
            ));
        return -1;
    }
    memset(ack, 0x0, sizeof(PriProAck));
    
    ack->sock_fd = conn_info_[ip_idx].sock_fd;
    ack->protocol = PROT_TCP_IP;
    ack->sock_seq = conn_info_[ip_idx].sock_seq;
    gettimeofday(&(ack->tv_time), NULL);
    ack->time = ISGWAck::instance()->get_time();
    snprintf(ack->msg, sizeof(ack->msg), "%s", buf);
    ACE_DEBUG((LM_NOTICE, "[%D] PlatConnMgrAsy send msg to ISGWAck"
        ",sock_fd=%u,protocol=%u,ip=%u,port=%u,sock_seq=%u,seq_no=%u,time=%u"
        ",msg=%s\n"
        , ack->sock_fd
        , ack->protocol
        , ack->sock_ip
        , ack->sock_port
        , ack->sock_seq
        , ack->seq_no
        , ack->time
        , ack->msg
        ));
    
    //放入回送消息管理器 负责把消息送到连接对端 (这里指跟后端的连接)
    ISGWAck::instance()->putq(ack);
    return 0;
}
static void evt_conn_complete(struct bthost *bthost, const void *data,
								uint8_t len)
{
	const struct bt_hci_evt_conn_complete *ev = data;

	if (len < sizeof(*ev))
		return;

	if (ev->status)
		return;

	init_conn(bthost, le16_to_cpu(ev->handle), ev->bdaddr, BDADDR_BREDR);
}
Ejemplo n.º 5
0
ACE_SOCK_Stream* PlatConnMgrEx::get_conn(int index, int & ip_idx) //从连接池获取一个连接
{    
    ACE_DEBUG((LM_TRACE, "[%D] PlatConnMgrEx start to get conn"
        ",index=%d,ip_idx=%d\n", index, ip_idx));
	if (index<0 || index>=POOL_CONN_MAX || ip_idx<0 || ip_idx >=IP_NUM_MAX)
    {
        ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx get conn failed, para is invalid"
            ",index=%d,ip_idx=%d\n", index, ip_idx));
        return NULL;
    }
    
    // 连接策略 
    if (use_strategy_ == 1 //使用策略
        && fail_times_[ip_idx] > max_fail_times_  //失败次数大于最大允许失败次数
        && (time(0) - last_fail_time_[ip_idx]) < recon_interval_ //时间间隔小于重连时间间隔 
    )
    {
        ACE_DEBUG((LM_TRACE, "[%D] PlatConnMgrEx get conn failed,because of strategy"
            ",index=%d"
            ",ip_idx=%d"
            ",fail_times=%d"
            ",last_fail_time=%d"
			"\n"	
            , index
            , ip_idx
            , fail_times_[ip_idx]
            , last_fail_time_[ip_idx]
            ));
        // 尝试下一个 ip 
        ip_idx = (++ip_idx)%ip_num_;
        
        // 尝试下一个的时候不做任何重连操作 直接使用 避免下一个也异常 出现频繁重连的情况
        return conn_[ip_idx][index]; // NULL; //
    }
    
    if (conn_[ip_idx][index] == NULL)
    {
        // 保证每次只有一个线程在初始化
        ACE_Guard<ACE_Thread_Mutex> guard(conn_lock_[ip_idx][index]);
        if (conn_[ip_idx][index] == NULL)
        {
            init_conn(index, ip_idx);
        }
    }
    
    return conn_[ip_idx][index];
}
Ejemplo n.º 6
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;
}
static void evt_le_conn_complete(struct bthost *bthost, const void *data,
								uint8_t len)
{
	const struct bt_hci_evt_le_conn_complete *ev = data;
	uint8_t addr_type;

	if (len < sizeof(*ev))
		return;

	if (ev->status)
		return;

	if (ev->peer_addr_type == 0x00)
		addr_type = BDADDR_LE_PUBLIC;
	else
		addr_type = BDADDR_LE_RANDOM;

	init_conn(bthost, le16_to_cpu(ev->handle), ev->peer_addr, addr_type);
}
Ejemplo n.º 8
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;
}
Ejemplo n.º 9
0
int main(int argc, char *argv[]) {
	/*initialize the connection to the freedb server */
	cddb_conn_t *conn = NULL;
	cddb_disc_t *disc;
	cddb_track_t *track;
	conn = init_conn();

	/* set track info */
	if (argc != 4) {
		fprintf(stderr, "usage: cddb_query <discid> <category> <track number>\n");
		return -1;
	}
	char *p;
	unsigned long discid = strtoul(argv[1], &p, 16);
	char *cat = argv[2];
	lowercase(cat);
	int tracknum = atoi(argv[3]);

	/* initialize the disc */
	disc = init_disc();
	cddb_disc_set_discid(disc, discid);
	cddb_disc_set_category_str(disc, cat);

	/* query the database to populate the disc info */
	read_db(conn, disc);

	/* extract the track from the disc */
	track = cddb_disc_get_track(disc, tracknum - 1);

	/* format an output track info */
	const char *title = cddb_track_get_title(track);
	const char *artist = cddb_disc_get_artist(disc);
	const char *album = cddb_disc_get_title(disc);
	unsigned int date = cddb_disc_get_year(disc);
	const char *label = "";
	const char *genre = cddb_disc_get_genre(disc);
	printf("%s\t%s\t%s\t%d\t%s\t%s\t", title, artist, album, date, label, genre);

	return 0;
}
Ejemplo n.º 10
0
CONN *establish_connection(char *addr, char *port)
{
    // Blank connection structure
    CONN *conn = malloc(sizeof (CONN));
    // Initialise connection
    init_conn(conn);
    // Load certificates
    load_certs(conn);
    // Create new SSL structure
    conn->ssl = SSL_new(conn->ctx);
    
    struct addrinfo hints, *res;
    
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    
    getaddrinfo(addr, port, &hints, &res);
    
    conn->sd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    
    // Connect to server
    if(connect(conn->sd, res->ai_addr, res->ai_addrlen) != 0) {
        perror("connection");
    }
    
    // Set BIO into SSL structure
    conn->bio = BIO_new_socket(conn->sd, BIO_NOCLOSE);
    SSL_set_bio(conn->ssl, conn->bio, conn->bio);
    
    // Perform handshake
    if(SSL_connect(conn->ssl) != 1) {
        perror("handshake\n");
    }
    
    printf("Connection Established\n");
    return conn;
}
Ejemplo n.º 11
0
void main_loop(void) 
{
  	int i,n,addr;
  	unsigned int sock_size;
  	fd_set readfds, testfds;
  	char cmd[CMD_LEN],buffer[1000];
  	struct sockaddr_in sa;

  	signal(SIGPIPE,SIG_IGN);
  	signal(SIGCHLD,waitchild);

  	/* server init */

  	printf("Starting the server ...\n");

  	if ((sd_server=socket(AF_INET,SOCK_STREAM,0)) < 0) {
    
		perror("socket");
    		exit(1);
  	}

  	sock_size=sizeof(struct sockaddr_in);
  	memset(&sa,0,sock_size);
  
  	sa.sin_family=AF_INET;
  	sa.sin_port=htons(serverport);
  	addr=INADDR_ANY;
  	memcpy(&sa.sin_addr.s_addr,&addr,sizeof(int));
  
  	if (bind(sd_server,(struct sockaddr *)&sa,sock_size)<0) {

    		perror("bind");
		exit(1);
  	}
	//printf("binded to socket\n");
  	if (listen(sd_server,5)<0) {
    
		perror("listen");
    		exit(1);
  	}
	init_conn(); 
    	//printf("OK\n");
    	//recv(sd_server,buffer,strlen(buffer),0);
	//printf("%s",buffer);
    	//prompt();

	/*FD_ZERO(&readfds);
    	FD_SET(1,&readfds);
    	FD_SET(sd_server,&readfds);
	*/
	stop = 0;
  	while (!stop) {	
			testfds = readfds;
		    	for (i = 0; i < nb_users; i++)
			{
      			if (clients[i]->sock)
				FD_SET(clients[i]->sock,&testfds);
				exec_comm(i);
			}
		//selectoin an active descriptor
       		if( 0 > (n = select(max_user_sock, &testfds, (fd_set *)0, (fd_set *)0, (struct timeval *)0))){					
      		//	if (errno!=EINTR || n != -1) 
                //		exit(1);
		}
		//reading information from clients
   		/*for (i = 0; i <= nb_users; i++) {
   			printf("clients are there\n");
      			if (clients[i]->sock) {
				//if (FD_ISSET(clients[i]->sock,&testfds))
	  			//exec_comm(i); //i - number of client in the client table
				prompt();
      			}
    		}*/
  	}
close(sd_server);
printf("server stops\n");
}
Ejemplo n.º 12
0
int main(int argc, char *argv[]) {

    struct termios tios;
    int fd;
    int ec;
    int brk_value;
    int inp_file_fd;
    int chars_read;

    // to clear Table 1 and Table 2 of datalogger
    char clearing_program[] = "MODE 1 \r"
	"SCAN RATE 0 \r"
	"1:P0 \r MODE 2 \r"
	"SCAN RATE 0 \r 1:P0 \r ";


    // Allocate memory for timestructures used as timestamps
    if((start_t = (struct timeval*)malloc(sizeof(*start_t))) == NULL) {
	fprintf(stderr,"Error in allocating memory for start timeval structure\n");
	return -1;
    }

    if((stop_t = (struct timeval*)malloc(sizeof(*stop_t))) == NULL) {
	fprintf(stderr,"Error in allocating memory for stop timeval structure\n");
	free(start_t);
	return -1;
    }

    // as temporary counters 
    int j,n; 

    assert(argc == 2);

    fd = open(argv[1], O_RDWR);
    if (fd < 0) {
        int en = errno;
        fprintf(stderr, "Error opening %s: %s\n", argv[1], strerror(en));
        assert(0);
        abort();
    }

    //connect with datalogger
    init_conn(fd);   
    printf("\n...Established connection to datalogger...\n");

    //wake up datalogger so we can enter commands
    ec = wake_up(fd);	
    assert(ec == 0);
    printf("\n...Datalogger is ready for commands...\n");

    // Added by Vinay
    // Start
    printf("Initializing connector agent...\n");
    initConnectorAgent();
    printf("Done\n");
    // End
    
    //Run clearing program command
    ec = load_blank_program(fd);
    assert(ec == 0);
    printf("\n...Program 0 (empty program) loaded successfully...\n");

    /*
    I don't see why we need this. -kec
    //Load clearing program into datalogger
    ec = load_program(fd, clearing_program);
    assert(ec == 0);
    printf("\n...Clearing program loaded and compiled successfully...\n");
    */
  
    // To clear the Input,Intermediate and Final Storage Areas of values from
    // previous programs by allocating current memory in Input Storage
    // locations again which causes all values in three storage areas to be
    // zero. Current locations for Input Storage is 1499.  By going to *A mode
    // and allocating 1499 locations to Input Storage clears Input,Intermediate
    // and Final Storage Area. I understand it is not the quite correct method
    // as if anybody manually changes number of Input Locations in *5 mode to
    // any other number than 1499 and runs this program the clearing of all
    // values in all three storage areas wont work.  Ideally I should be going
    // to *5 mode knowing the number of Input Storage Locations(say N) and then
    // doing the below steps for the number N and I need to do that in future
    // after other issues are sorted out.

    // There seems to be a bug here in some versions of the datalogger.  If 0
    // is entered for intermediate storage and program storage, before we load
    // the polling program, it fails with an E04 error.  If, however, we enter
    // some value for the program storage, like 2048, then it seems to work
    // fine. It also works fine if 0 is entered after the polling program has
    // been loaded.  We think this is a bug (rather than being designed to work
    // that way), because it seemed to work differently in some other versions.
    // -kec
    ec = allocate_memory(fd, "100\r", "500\r", "0\r", "0\r", "2048\r");
    assert(ec == 0);
    printf("\n...Memory has been allocated successfully...\n");
    
    // Load ten locations program into datalogger
    ec = load_program(fd, program_ten_locations);
    assert(ec == 0);
    printf("\n...Ten locations program loaded and compiled successfully...\n");

    //and is running, start to look for new sensorID's
    detect_new_sensors(fd);

    return 0;
}
Ejemplo n.º 13
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;
}
Ejemplo n.º 14
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;
    }
    
  }

}
Ejemplo n.º 15
0
/**
 * The routeQuery entry point. This is passed the query buffer
 * to which the filter should be applied. Once processed the
 * query is passed to the downstream component
 * (filter or router) in the filter chain.
 *
 * The function tries to extract a SQL query out of the query buffer,
 * adds a timestamp to it and publishes the resulting string on the exchange.
 * The message is tagged with an unique identifier and the clientReply will
 * use the same identifier for the reply from the backend.
 * 
 * @param instance	The filter instance data
 * @param session	The filter session
 * @param queue		The query data
 */
static	int	
routeQuery(FILTER *instance, void *session, GWBUF *queue)
{
  MQ_SESSION	*my_session = (MQ_SESSION *)session;
  MQ_INSTANCE	*my_instance = (MQ_INSTANCE *)instance;
  char		*ptr, t_buf[128], *combined;
  int		length, err_code = AMQP_STATUS_OK;
  amqp_basic_properties_t prop;
  spinlock_acquire(my_instance->rconn_lock);
  if(my_instance->conn_stat != AMQP_STATUS_OK){

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

      my_instance->last_rconn = time(NULL);

      if(init_conn(my_instance,my_session)){
	my_instance->rconn_intv = 1.0;
	my_instance->conn_stat = AMQP_STATUS_OK;	

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

  if(modutil_is_SQL(queue)){

    if(my_session->uid == NULL){

      my_session->uid = calloc(33,sizeof(char));

      if(!my_session->uid){
	skygw_log_write(LOGFILE_ERROR,"Error : Out of memory.");
      }else{
	genkey(my_session->uid,32);
      }

    }
    
  }

  if (err_code == AMQP_STATUS_OK){

    if(modutil_extract_SQL(queue, &ptr, &length)){

      my_session->was_query = 1;

      prop._flags = AMQP_BASIC_CONTENT_TYPE_FLAG |
	AMQP_BASIC_DELIVERY_MODE_FLAG |
	AMQP_BASIC_MESSAGE_ID_FLAG | 
	AMQP_BASIC_CORRELATION_ID_FLAG;
      prop.content_type = amqp_cstring_bytes("text/plain");
      prop.delivery_mode = AMQP_DELIVERY_PERSISTENT;
      prop.correlation_id = amqp_cstring_bytes(my_session->uid);
      prop.message_id = amqp_cstring_bytes("query");

      memset(t_buf,0,128);      
      sprintf(t_buf, "%lu|",(unsigned long)time(NULL));

      int qlen = length + strnlen(t_buf,128);
      if((combined = malloc((qlen+1)*sizeof(char))) == NULL){
	skygw_log_write_flush(LOGFILE_ERROR,
			      "Error : Out of memory");
      }
      strcpy(combined,t_buf);
      strncat(combined,ptr,length);
      
      if((err_code = amqp_basic_publish(my_session->conn,my_session->channel,
					amqp_cstring_bytes(my_instance->exchange),
					amqp_cstring_bytes(my_instance->key),
					0,0,&prop,amqp_cstring_bytes(combined))
	  ) != AMQP_STATUS_OK){
	spinlock_acquire(my_instance->rconn_lock);  
	my_instance->conn_stat = err_code;
	spinlock_release(my_instance->rconn_lock);

	skygw_log_write_flush(LOGFILE_ERROR,
			      "Error : Failed to publish message to MQRabbit server: "
			      "%s",amqp_error_string2(err_code));
	
      } 

    }

  }
  /** Pass the query downstream */
  return my_session->down.routeQuery(my_session->down.instance,
				     my_session->down.session, queue);
}
Ejemplo n.º 16
0
void remove_catalogs(void)
{
	init_conn(&db_connection1);
	init_conn(&db_connection2);

	printf ("\n\nConnected to %s.\n\n", connect_string);

	puts ("Removing Vigilert's catalogs will delete your Vigilert triggers,");
	puts ("triggersets, data sources, pending mail, pending OS commands, and pending notices.");
	printf ("Are you sure you want to do this (Y/N)? ");
	fgets (yesno, sizeof (yesno), stdin);
    yesno[strlen (yesno) - 1] = '\0';  // Remove trailing \n.

	if (stricmp (yesno, "y") != 0)
	{
		exit (EXIT_SUCCESS);
	}

	puts ("");
	
	remove_update_queue_tables_and_native_triggers();

	exec_sql_stmt("drop sequence mail_seq");
	puts("mail_seq");

	exec_sql_stmt("drop sequence exec_seq");
	puts("exec_seq");

	exec_sql_stmt("drop sequence notice_seq");
	puts("notice_seq");

	exec_sql_stmt("drop sequence ds_id");
	puts("ds_id");

	exec_sql_stmt("drop table vl_DataSrcAtb"),
	puts ("vl_datasrcatb");

	exec_sql_stmt("drop table vl_DataSrc");
	puts ("vl_DataSrc");

	exec_sql_stmt("drop table vl_IDTable");
	puts ("vl_idtable");

	exec_sql_stmt("drop table vl_Trigger");
	puts ("vl_Trigger");

	exec_sql_stmt("drop table vl_TriggerSet");
	puts ("vl_TriggerSet");

	exec_sql_stmt("drop table vl_TrigDataSrcReln");
	puts ("vl_TrigDataSrcReln");

	exec_sql_stmt("drop table vl_mail");
	puts ("vl_mail");

	exec_sql_stmt("drop table vl_osexec");
	puts ("vl_osexec");

	exec_sql_stmt("drop table vl_notice");
	puts ("vl_notice");

	exec_sql_stmt("drop table vl_DataSrcMtb");
	puts ("vl_DataSrcMtb");

	exec_sql_stmt("drop table vl_null_tbl");
	puts ("vl_null_tbl");

	exec_sql_stmt("drop table vl_mon_watch");
	puts ("vl_mon_watch");

	exec_sql_stmt("drop table vl_mon_update");
	puts ("vl_mon_update");

	exec_sql_stmt("drop table vl_ext_fcn_tbl");
	puts ("vl_ext_fcn_tbl");

	close_conn(db_connection1);
	close_conn(db_connection2);
}
Ejemplo n.º 17
0
int PlatConnMgrAsy::init(const char *section)
{
    ACE_Guard<ACE_Thread_Mutex> guard(conn_mgr_lock_); 
    if (section != NULL)
    {
        strncpy(section_, section, sizeof(section_));
    }
    
    if ((SysConf::instance()->get_conf_int(section_, "ip_num", &ip_num_) != 0)
        || (ip_num_ > IP_NUM_MAX))
    {
        ip_num_ = IP_NUM_MAX;
    }
    
    int time_out = SOCKET_TIME_OUT;
    if (SysConf::instance()->get_conf_int(section_, "time_out", &time_out) == 0)
    {
        time_out_.set(time_out);
    }
    
	//获取 ip 列表 
	char ip_str[16];
	for(int i=0; i<ip_num_; i++)
    {
        memset(ip_str, 0x0, sizeof(ip_str));
        snprintf(ip_str, sizeof(ip_str), "ip_%d", i);
        
        if (SysConf::instance()
            ->get_conf_str(section_, ip_str, ip_[i], sizeof(ip_[i])) != 0)
        {
            ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrAsy get config failed"
                ",section=%s,ip_%d\n", section_, i));
            ip_num_ = i; //实际成功获取到的 ip 数量 
            break;
        }
    }
    
    if (ip_num_ == 0) //一个ip都没有 
    {
        ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrAsy init failed"
            ",section=%s,ip_num=%d\n", section_, ip_num_));
        ip_num_ = IP_NUM_DEF; //设回为默认值 
        return -1;
    }
    
    if (SysConf::instance()->get_conf_int(section_, "port", &port_) != 0)
    {
        ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrAsy get port config failed"
            ",section=%s\n", section_)); 
        return -1;
    }
    
    ACE_DEBUG((LM_INFO, "[%D] PlatConnMgrAsy start to init conn"
        ",ip_num=%d"
        "\n"
        , ip_num_
        )); 
    for(int i=0; i<ip_num_; i++)
    {
        if (init_conn(i) !=0)
        {
            //某个连接不上 不退出程序 
            //return -1;
        }
    }

    //初始化一下 stat 保证不使用框架的模块使用也正常
    Stat::instance()->init("");
    return 0;
}
Ejemplo n.º 18
0
int main(int argc, char *argv[]) {

    int ec;

#if 0
    static char buf[100000];

    int fd = open("dump-4.bd", O_RDONLY);
    assert(fd > 0);
    int len = read(fd, buf, sizeof buf);

    int n_arrays;
    const Cdl_Array *arrays = decode_binary_dump(buf, len, &n_arrays);

    for (int i = 0; i < n_arrays; i++) {
        const Cdl_Array *a = &arrays[i];
        printf("array id: %d, n: %d\n", a->id, a->length);
        for (int j = 0; j < a->length; j++) {
            Cdl_Element *e = &a->elements[j];
            switch (e->type) {
                case CDL_ET_LO_RES:
                case CDL_ET_HI_RES:
                    printf("element %d: %f\n", j, e->value.dble);
                    break;
                case CDL_ET_STRING:
                    printf("element %d: %s\n", j, e->value.strng);
                    break;
                default:
                    assert(0);
                    abort();
            }
        }
    }

    for (int i = 0; i < n_arrays; i++) {
        const Cdl_Array *a = &arrays[i];
        Cdl_Array__dtor(a);
    }
    free((void*) arrays);
#endif

    assert(argc == 2);

    int fd = open(argv[1], O_RDWR);
    if (fd < 0) {
        int en = errno;
        fprintf(stderr, "Error opening %s: %s\n", argv[1], strerror(en));
        assert(0);
        abort();
    }

    //connect with datalogger
    init_conn(fd);   
    printf("\n...Established connection to datalogger...\n");

    //wake up datalogger so we can enter commands
    ec = wake_up(fd);	
    assert(ec == 0);
    printf("\n...Datalogger is ready for commands...\n");

    //Run clearing program command
    ec = load_blank_program(fd);
    assert(ec == 0);
    printf("\n...Program 0 (empty program) loaded successfully...\n");

    // Load program to ...
    Cdl_Program prog;

    Cdl_Program__ctor(&prog, 5);
    // Internal temp: input_loc
    Cdl_Program__p17(&prog, 0);
    // Sample: reps, input_loc
    Cdl_Program__p70(&prog, 1, 0);


    load_Program(fd, 1, &prog);

    Cdl_Program__dtor(&prog);

    return 0;
}
Ejemplo n.º 19
0
/**
 * The clientReply entry point. This is passed the response buffer
 * to which the filter should be applied. Once processed the
 * query is passed to the upstream component
 * (filter or router) in the filter chain.
 *
 * The function tries to extract a SQL query response out of the response buffer,
 * adds a timestamp to it and publishes the resulting string on the exchange.
 * The message is tagged with the same identifier that the query was.
 * 
 * @param instance	The filter instance data
 * @param session	The filter session
 * @param reply		The response data
 */
static int clientReply(FILTER* instance, void *session, GWBUF *reply)
{
  MQ_SESSION		*my_session = (MQ_SESSION *)session;
  MQ_INSTANCE		*my_instance = (MQ_INSTANCE *)instance;
  char			t_buf[128],*combined;
  unsigned int		err_code = AMQP_STATUS_OK,
    pkt_len = pktlen(reply->sbuf->data), offset = 0;
  amqp_basic_properties_t prop;

  spinlock_acquire(my_instance->rconn_lock);

  if(my_instance->conn_stat != AMQP_STATUS_OK){

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

      my_instance->last_rconn = time(NULL);

      if(init_conn(my_instance,my_session)){
	my_instance->rconn_intv = 1.0;
	my_instance->conn_stat = AMQP_STATUS_OK;	

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

  spinlock_release(my_instance->rconn_lock);

  if (err_code == AMQP_STATUS_OK && my_session->was_query){

    int packet_ok = 0, was_last = 0;

    my_session->was_query = 0;

    if(pkt_len > 0){
      prop._flags = AMQP_BASIC_CONTENT_TYPE_FLAG |
	AMQP_BASIC_DELIVERY_MODE_FLAG |
	AMQP_BASIC_MESSAGE_ID_FLAG | 
	AMQP_BASIC_CORRELATION_ID_FLAG;
      prop.content_type = amqp_cstring_bytes("text/plain");
      prop.delivery_mode = AMQP_DELIVERY_PERSISTENT;
      prop.correlation_id = amqp_cstring_bytes(my_session->uid);
      prop.message_id = amqp_cstring_bytes("reply");
      if(!(combined = calloc(GWBUF_LENGTH(reply) + 256,sizeof(char)))){
	skygw_log_write_flush(LOGFILE_ERROR,
			      "Error : Out of memory");
      }

      memset(t_buf,0,128);
      sprintf(t_buf,"%lu|",(unsigned long)time(NULL));
      
      
      memcpy(combined + offset,t_buf,strnlen(t_buf,40));
      offset += strnlen(t_buf,40);

      if(*(reply->sbuf->data + 4) == 0x00){ /**OK packet*/
	unsigned int aff_rows = 0, l_id = 0, s_flg = 0, wrn = 0;
	unsigned char *ptr = (unsigned char*)(reply->sbuf->data + 5);
	pkt_len = pktlen(reply->sbuf->data);
	aff_rows = consume_leitoi(&ptr);
	l_id = consume_leitoi(&ptr);
	s_flg |= *ptr++;
	s_flg |= (*ptr++ << 8);
	wrn |= *ptr++;
	wrn |= (*ptr++ << 8);
	sprintf(combined + offset,"OK - affected_rows: %d "
		" last_insert_id: %d "
		" status_flags: %#0x "
		" warnings: %d ",		
		aff_rows,l_id,s_flg,wrn);
	offset += strnlen(combined,GWBUF_LENGTH(reply) + 256) - offset;

	if(pkt_len > 7){
	  int plen = consume_leitoi(&ptr);
	  if(plen > 0){
	    sprintf(combined + offset," message: %.*s\n",plen,ptr);
	  }
	}

	packet_ok = 1;
	was_last = 1;

      }else if(*(reply->sbuf->data + 4) == 0xff){ /**ERR packet*/

	sprintf(combined + offset,"ERROR - message: %.*s",
		(int)(reply->end - ((void*)(reply->sbuf->data + 13))),
		(char *)reply->sbuf->data + 13);
	packet_ok = 1;
	was_last = 1;
    
      }else if(*(reply->sbuf->data + 4) == 0xfb){ /**LOCAL_INFILE request packet*/
      
	unsigned char	*rset = (unsigned char*)reply->sbuf->data;
	strcpy(combined + offset,"LOCAL_INFILE: ");
	strncat(combined + offset,(const char*)rset+5,pktlen(rset));
	packet_ok = 1;
	was_last = 1;
      
      }else{ /**Result set*/
      
	unsigned char	*rset = (unsigned char*)(reply->sbuf->data + 4);
	char		*tmp;
	unsigned int	col_cnt = consume_leitoi(&rset);

	tmp = calloc(256,sizeof(char));
	sprintf(tmp,"Columns: %d",col_cnt);
	memcpy(combined + offset,tmp,strnlen(tmp,256));
	offset += strnlen(tmp,256);
	memcpy(combined + offset,"\n",1);
	offset++;
	free(tmp);
       
	packet_ok = 1;
	was_last = 1;
	
      }
      if(packet_ok){
	if((err_code = amqp_basic_publish(my_session->conn,my_session->channel,
					  amqp_cstring_bytes(my_instance->exchange),
					  amqp_cstring_bytes(my_instance->key),
					  0,0,&prop,amqp_cstring_bytes(combined))
	    ) != AMQP_STATUS_OK){
	  spinlock_acquire(my_instance->rconn_lock);  
	  my_instance->conn_stat = err_code;
	  spinlock_release(my_instance->rconn_lock);

	  skygw_log_write_flush(LOGFILE_ERROR,
				"Error : Failed to publish message to MQRabbit server: "
				"%s",amqp_error_string2(err_code));
	
	}else if(was_last){

	  /**Successful reply received and sent, releasing uid*/
	  
	  free(my_session->uid);
	  my_session->uid = NULL;

	} 
      }
      free(combined);
    }

  }  

  return my_session->up.clientReply(my_session->up.instance,
				    my_session->up.session, reply);
}
Ejemplo n.º 20
0
int PlatConnMgrEx::send_recv(const void * send_buf, int send_len
    , void * recv_buf, int recv_len, const unsigned int uin)
{
    int ip_idx = get_ip_idx(uin);
    int index = get_index(ip_idx, uin);
    ACE_SOCK_Stream* conn = get_conn(index, ip_idx);
    if (conn == NULL)
    {
        ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx get conn failed"
            ",can't get a useful conn"
            ",index=%d,ip_idx=%d,uin=%u\n"
            , index, ip_idx, uin
            ));
        return -1;
    }
    ACE_Guard<ACE_Thread_Mutex> guard(conn_lock_[ip_idx][index]);// 加锁需要放在获取的后面 
    if (conn_[ip_idx][index] == NULL) // 加锁后增加一次非法判断 
    {
        ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx send_recv failed"
            ",conn is null"
            ",index=%d,ip_idx=%d,uin=%u\n"
            , index, ip_idx, uin
            ));
        return -1;
    }
    conn_use_flag_[ip_idx][index] = 1;
    
    //清除原缓冲 add by awayfang 2010-03-02 
    ACE_Time_Value zero;
    zero.set(0);
    int max_recv_len = recv_len;
    int tmp_ret = conn_[ip_idx][index]->recv(recv_buf, max_recv_len, &zero);//不等待直接返返回
    // 检测到连接关闭时, 重建连接
    if((tmp_ret < 0 && errno != ETIME)   // 连接上无数据的情况,会返回超时,不需重连 
        || tmp_ret == 0)                 // 连接已经被对端关闭, 处于close wait状态
    {
        ACE_DEBUG((LM_INFO, "[%D] PlatConnMgrEx send_recv connection close detected,"
            "uin=%u,ip=%s,index=%d\n", uin, ip_[ip_idx], index));
        init_conn(index, ip_idx);
	 if(conn_[ip_idx][index] == NULL)
        {
            ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx send_recv reconnect failed,"
                "index=%d,ip_idx=%d\n", index, ip_idx));
            return -1;
        }
    }
    
    ACE_DEBUG((LM_TRACE, "[%D] PlatConnMgrEx send_recv msg"
        ",index=%d,ip_idx=%d,uin=%u\n", index, ip_idx, uin));
    int ret = conn_[ip_idx][index]->send(send_buf, send_len, &time_out_);
    if (ret <= 0) //异常或者对端关闭
    {
        ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx send_recv send msg failed"
            ",index=%d,ip_idx=%d,ret=%d,uin=%u,errno=%d\n", index, ip_idx, ret, uin, errno));
        //关闭连接
        fini(index, ip_idx);
        Stat::instance()->incre_stat(STAT_CODE_SEND_FAIL);
        return ret;
    }
	// 
    ret = conn_[ip_idx][index]->recv(recv_buf, recv_len, &time_out_);
    if (ret <= 0) //异常或者对端关闭
    {
        ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx send_recv recv msg failed"
            ",index=%d,ip_idx=%d,ret=%d,uin=%u,errno=%d\n", index, ip_idx, ret, uin, errno));
        //关闭连接
        fini(index, ip_idx);
        Stat::instance()->incre_stat(STAT_CODE_RECV_FAIL);
        return ret;
    }

    ACE_DEBUG((LM_TRACE, "[%D] PlatConnMgrEx send_recv msg succ"
        ",index=%d,ip_idx=%d,ret=%d,uin=%u\n", index, ip_idx, ret, uin));
        
    conn_use_flag_[ip_idx][index] = 0;//退出前清理使用状态
    return ret;
    
}
Ejemplo n.º 21
0
int PlatConnMgrEx::init(const char *section, const std::vector<std::string> *ip_vec)
{
    ACE_Guard<ACE_Thread_Mutex> guard(conn_mgr_lock_); 
    if (section != NULL)
    {
        strncpy(section_, section, sizeof(section_));
    }

    // 默认使用用户指定的ip
    if(ip_vec != NULL && !ip_vec->empty())
    {
        ip_num_ = static_cast<int>(ip_vec->size());
        if(ip_num_ > IP_NUM_MAX) ip_num_ = IP_NUM_MAX;
        for(int i = 0;i < ip_num_;i++)
        {
            snprintf(ip_[i], sizeof(ip_[i]), "%s", (*ip_vec)[i].c_str());
        }
    }
    else /* 未指定ip则使用配置的ip */
    {
        if ((SysConf::instance()->get_conf_int(section_, "ip_num", &ip_num_) != 0)
    		|| (ip_num_ > IP_NUM_MAX))
    	{
    		ip_num_ = IP_NUM_DEF;
    	}
        
        //获取 ip 列表 
    	char ip_str[16];
    	for(int i=0; i<ip_num_; i++)
    	{
    		memset(ip_str, 0x0, sizeof(ip_str));
    		snprintf(ip_str, sizeof(ip_str), "ip_%d", i);
    		
    		if (SysConf::instance()
    			->get_conf_str(section_, ip_str, ip_[i], sizeof(ip_[i])) != 0)
    		{
    			ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx get config failed"
    				",section=%s,ip_%d\n", section_, i));
    			ip_num_ = i; //实际成功获取到的 ip 数量 
    			break;
    		}
    	}
    }
    
	if (ip_num_ == 0) //一个ip都没有 
	{
		ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx init failed"
			",section=%s,ip_num=%d\n", section_, ip_num_));
		ip_num_ = IP_NUM_DEF; //设回为默认值 
		return -1;
	}
	
	if (SysConf::instance()->get_conf_int(section_, "conn_nums", &conn_nums_) != 0)
	{
		conn_nums_ = POOL_CONN_DEF;
	}
	else if(conn_nums_ > POOL_CONN_MAX)
	{
		conn_nums_ = POOL_CONN_MAX;
	}
	
	int time_out = SOCKET_TIME_OUT;
	if (SysConf::instance()->get_conf_int(section_, "time_out", &time_out) == 0)
	{
		time_out_.set(time_out/1000, (time_out%1000)*1000);
	}

	if (SysConf::instance()->get_conf_int(section_, "port", &port_) != 0)
	{
		ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx get port config failed"
			",section=%s\n", section_)); 
		return -1;
	}

	if (SysConf::instance()->get_conf_int(section_, "use_strategy", &use_strategy_) == 0)
	{
		//使用连接策略
		ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx get use_strategy config succ,use strategy"
			",section=%s\n", section_));
		SysConf::instance()->get_conf_int(section_, "max_fail_times", &max_fail_times_);
		SysConf::instance()->get_conf_int(section_, "recon_interval", &recon_interval_);        
	}

    ACE_DEBUG((LM_INFO, "[%D] PlatConnMgrEx start to init conn"
        ",ip_num=%d"
        ",conn_nums=%d"
        "\n"
        , ip_num_
        , conn_nums_
        )); 
    for(int i=0; i<ip_num_; i++)
    {
        for(int j=0; j<conn_nums_; j++)
        {
            if (init_conn(j, i) !=0)
            {
                //某个连接不上 不退出程序 
                //return -1;
            }
        }
    }
    
    //初始化一下 stat 保证不使用框架的模块使用也正常
    Stat::instance()->init();
    return 0;
}
Ejemplo n.º 22
0
int main()
{
    char pkt_arr[] = {0, 0, 0}; // {damage, health, stun}
    unsigned char i = 0;
    
    // Initialize PIC
    init_pic();
    //init_uart();
    
    // Initialize teammates' code
    init_ir();
    init_accel();
    init_leds();
    init_isr();
    init_conn();
    
    /*
    RC4 = 1;
    __delay_ms(250);
    RC4 = 0;
    __delay_ms(250);
    RC4 = 1;
    __delay_ms(250);
    RC4 = 0;
    __delay_ms(250);
    RC4 = 1;
    __delay_ms(250);
    RC4 = 0;
    */
    
    // main loop
    while(1)
    {
#if _ALPHA_BLADE
        display_health();
        if(damage_received)
        {
            display_blade_lights(_LIGHT_MODE_DAMAGE_RECEIVED);
            damage_received = 0;
        }
        
        if( determine_sword_was_swung() && ( ( health > 0) || determine_omega_mode_active() ) )
        {

            if(!determine_omega_mode_active())
            {
                display_blade_lights(_LIGHT_MODE_INDIVIDUAL_SWING);
                
                determine_packets_to_send(&pkt_arr);
                
                for(i = 3; i > 0; --i)
                {
                    if(pkt_arr[i-1] > 0)
                    {
                        GIE = 0;
                        output_ir(i-1, pkt_arr[i-1]);
                        GIE = 1;
                    }
                }
            }
            else
            {
                display_blade_lights(_LIGHT_MODE_OMEGA_SWING);
            }
        }
        
        
        GIE = 0;
        while( ( stun_counter > 0 ) && !determine_omega_mode_active() )
        {
            GIE = 1;
            
            //****************Turn full blue
            //Green to 0%
            PSMC2DCH  = 0xFF;//PSMC2 Duty Cycle High-byte
            PSMC2DCL  = 0xFF;//PSMC2 Duty Cycle Low-byte
            PSMC2LD = 1; //PSMC 2 Load		
            //Blue to 0%
            PSMC3DCH  = 0x00;//PSMC3 Duty Cycle High-byte
            PSMC3DCL  = 0x00;//PSMC3 Duty Cycle Low-byte
            PSMC3LD = 1; //PSMC 3 Load
            //Red to 100%
            PSMC4DCH  = 0xFF;//PSMC4 Duty Cycle High-byte
            PSMC4DCL  = 0x00;//PSMC4 Duty Cycle Low-byte
            PSMC4LD = 1; //PSMC 4 Load		
            //Set Load Bit to load duty cycle values
            PSMC2LD = 1; //PSMC 2 Load
            PSMC3LD = 1; //PSMC 3 Load
            PSMC4LD = 1; //PSMC 4 Load

            __delay_ms(50);

            //****************Turn off
            //Green to 0%
            PSMC2DCH  = 0x00;//PSMC2 Duty Cycle High-byte
            PSMC2DCL  = 0x00;//PSMC2 Duty Cycle Low-byte
            PSMC2LD = 1; //PSMC 2 Load		
            //Blue to 0%
            PSMC3DCH  = 0x00;//PSMC3 Duty Cycle High-byte
            PSMC3DCL  = 0x00;//PSMC3 Duty Cycle Low-byte
            PSMC3LD = 1; //PSMC 3 Load
            //Red to 0%
            PSMC4DCH  = 0x00;//PSMC4 Duty Cycle High-byte
            PSMC4DCL  = 0x00;//PSMC4 Duty Cycle Low-byte
            PSMC4LD = 1; //PSMC 4 Load		
            //Set Load Bit to load duty cycle values
            PSMC2LD = 1; //PSMC 2 Load
            PSMC3LD = 1; //PSMC 3 Load
            PSMC4LD = 1; //PSMC 4 Load

            __delay_ms(50);
            
            GIE = 0;
            --stun_counter;
        }
        GIE = 1;
        
    
#elif _BETA_BLADE
        display_health();
        if( determine_sword_was_swung() )
        {
            if(!determine_omega_mode_active())
            {
                play_sound(_SOUND_TYPE_INDIVIDUAL);
                display_blade_lights(_LIGHT_MODE_INDIVIDUAL_SWING);
                
                determine_packets_to_send(&pkt_arr);

                for(i = 3; i > 0; --i)
                {
                    if(pkt_arr[i-1] > 0)
                    {
                        GIE = 0;
                        output_ir(i-1, pkt_arr[i-1]);
                        GIE = 1;
                    }
                }
            }
            else
            {
                play_sound(_SOUND_TYPE_OMEGA);
                display_blade_lights(_LIGHT_MODE_OMEGA_SWING);
            }
        }
    
#elif _DELTA_BLADE
        display_health();
        if(damage_received)
        {
            display_blade_lights(_LIGHT_MODE_DAMAGE_RECEIVED);
            damage_received = 0;
        }
        
        if( determine_sword_was_swung() && ( ( health > 0) || determine_omega_mode_active() ) )
        {
            if(!determine_omega_mode_active())
            {
                display_blade_lights(_LIGHT_MODE_INDIVIDUAL_SWING);
            }
            else
            {
                display_blade_lights(_LIGHT_MODE_OMEGA_SWING);
            }
            
            determine_packets_to_send(&pkt_arr);

            for(i = 3; i > 0; --i)
            {
                if(pkt_arr[i-1] > 0)
                {
                    GIE = 0;
                    output_ir(i-1, pkt_arr[i-1]);
                    GIE = 1;
                }
            }
        }

        GIE = 0;
        while( ( stun_counter > 0 ) && !determine_omega_mode_active() )
        {
            GIE = 1;
            
            //****************Turn full blue
            //Green to 0%
            PSMC2DCH  = 0xFF;//PSMC2 Duty Cycle High-byte
            PSMC2DCL  = 0xFF;//PSMC2 Duty Cycle Low-byte
            PSMC2LD = 1; //PSMC 2 Load		
            //Blue to 0%
            PSMC3DCH  = 0x00;//PSMC3 Duty Cycle High-byte
            PSMC3DCL  = 0x00;//PSMC3 Duty Cycle Low-byte
            PSMC3LD = 1; //PSMC 3 Load
            //Red to 100%
            PSMC4DCH  = 0xFF;//PSMC4 Duty Cycle High-byte
            PSMC4DCL  = 0x00;//PSMC4 Duty Cycle Low-byte
            PSMC4LD = 1; //PSMC 4 Load		
            //Set Load Bit to load duty cycle values
            PSMC2LD = 1; //PSMC 2 Load
            PSMC3LD = 1; //PSMC 3 Load
            PSMC4LD = 1; //PSMC 4 Load

            __delay_ms(50);

            //****************Turn off
            //Green to 0%
            PSMC2DCH  = 0x00;//PSMC2 Duty Cycle High-byte
            PSMC2DCL  = 0x00;//PSMC2 Duty Cycle Low-byte
            PSMC2LD = 1; //PSMC 2 Load		
            //Blue to 0%
            PSMC3DCH  = 0x00;//PSMC3 Duty Cycle High-byte
            PSMC3DCL  = 0x00;//PSMC3 Duty Cycle Low-byte
            PSMC3LD = 1; //PSMC 3 Load
            //Red to 0%
            PSMC4DCH  = 0x00;//PSMC4 Duty Cycle High-byte
            PSMC4DCL  = 0x00;//PSMC4 Duty Cycle Low-byte
            PSMC4LD = 1; //PSMC 4 Load		
            //Set Load Bit to load duty cycle values
            PSMC2LD = 1; //PSMC 2 Load
            PSMC3LD = 1; //PSMC 3 Load
            PSMC4LD = 1; //PSMC 4 Load

            __delay_ms(50);
            
            GIE = 0;
            --stun_counter;
        }
        GIE = 1;

#elif _GAMMA_BLADE
        display_health();
        if(damage_received)
        {
            display_blade_lights(_LIGHT_MODE_DAMAGE_RECEIVED);
            damage_received = 0;
        }
        
        if( determine_sword_was_swung() && ( ( health > 0) || determine_omega_mode_active() ) )
        {
            if(!determine_omega_mode_active())
            {
                display_blade_lights(_LIGHT_MODE_INDIVIDUAL_SWING);
                
                determine_packets_to_send(&pkt_arr);

                for(i = 3; i > 0; --i)
                {
                    if(pkt_arr[i-1] > 0)
                    {
                        GIE = 0;
                        output_ir(i-1, pkt_arr[i-1]);
                        GIE = 1;
                    }
                }
            }
            else
            {
                display_blade_lights(_LIGHT_MODE_OMEGA_SWING);
            }
        }

        GIE = 0;
        
        while( ( stun_counter > 0 ) && !determine_omega_mode_active() )
        {
            GIE = 1;
            
            //****************Turn full blue
            //Green to 0%
            PSMC2DCH  = 0xFF;//PSMC2 Duty Cycle High-byte
            PSMC2DCL  = 0xFF;//PSMC2 Duty Cycle Low-byte
            PSMC2LD = 1; //PSMC 2 Load		
            //Blue to 0%
            PSMC3DCH  = 0x00;//PSMC3 Duty Cycle High-byte
            PSMC3DCL  = 0x00;//PSMC3 Duty Cycle Low-byte
            PSMC3LD = 1; //PSMC 3 Load
            //Red to 100%
            PSMC4DCH  = 0xFF;//PSMC4 Duty Cycle High-byte
            PSMC4DCL  = 0x00;//PSMC4 Duty Cycle Low-byte
            PSMC4LD = 1; //PSMC 4 Load		
            //Set Load Bit to load duty cycle values
            PSMC2LD = 1; //PSMC 2 Load
            PSMC3LD = 1; //PSMC 3 Load
            PSMC4LD = 1; //PSMC 4 Load

            __delay_ms(50);

            //****************Turn off
            //Green to 0%
            PSMC2DCH  = 0x00;//PSMC2 Duty Cycle High-byte
            PSMC2DCL  = 0x00;//PSMC2 Duty Cycle Low-byte
            PSMC2LD = 1; //PSMC 2 Load		
            //Blue to 0%
            PSMC3DCH  = 0x00;//PSMC3 Duty Cycle High-byte
            PSMC3DCL  = 0x00;//PSMC3 Duty Cycle Low-byte
            PSMC3LD = 1; //PSMC 3 Load
            //Red to 0%
            PSMC4DCH  = 0x00;//PSMC4 Duty Cycle High-byte
            PSMC4DCL  = 0x00;//PSMC4 Duty Cycle Low-byte
            PSMC4LD = 1; //PSMC 4 Load		
            //Set Load Bit to load duty cycle values
            PSMC2LD = 1; //PSMC 2 Load
            PSMC3LD = 1; //PSMC 3 Load
            PSMC4LD = 1; //PSMC 4 Load

            __delay_ms(50);
            
            GIE = 0;
            --stun_counter;
        }
        
        GIE = 1;
        
#endif
        
    }
}
Ejemplo n.º 23
0
// 支持指定接收的结束符来接收数据 add by awayfang 2010-03-02 
int PlatConnMgrEx::send_recv_ex(const void * send_buf, int send_len
    , void * recv_buf, int recv_len, const char * separator, const unsigned int uin)
{
    int ip_idx = get_ip_idx(uin); // ip 默认根据 uin 轮询 
    int index = get_index(ip_idx, uin); 
    ACE_SOCK_Stream* conn = get_conn(index, ip_idx);
    if (conn == NULL)
    {
        ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx get conn failed"
            ",can't get a useful conn"
            ",index=%d,ip_idx=%d,uin=%u\n"
            , index, ip_idx, uin
            ));
        return -1;
    }
    
    // 因为 ip_idx 可能被修改,加锁需要放在获取的后面 
    ACE_Guard<ACE_Thread_Mutex> guard(conn_lock_[ip_idx][index]); 
    // 加锁后增加一次非法判断 不然有可能被其他线程释放连接对象
    if (conn_[ip_idx][index] == NULL) 
    {
        ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx send_recv_ex failed"
            ",conn is null"
            ",index=%d,ip_idx=%d,uin=%u\n"
            , index, ip_idx, uin
            ));
        return -1;
    }
    conn_use_flag_[ip_idx][index] = 1;

    //清除原缓冲 add by awayfang 2010-03-02 
    ACE_Time_Value zero;
    zero.set(0);
    int max_recv_len = recv_len;
    int tmp_ret = conn_[ip_idx][index]->recv(recv_buf, max_recv_len, &zero);//不等特直接返返回
    // 检测到连接关闭时, 重建连接
    // 在对面进程重启时, 有可能发生
    if((tmp_ret < 0 && errno != ETIME)   // 连接上无数据的情况,会返回超时,不需重连 
        || tmp_ret == 0)                 // 连接已经被对端关闭, 处于close wait状态
    {
        ACE_DEBUG((LM_INFO, "[%D] PlatConnMgrEx send_recv_ex connection close detected,"
            "uin=%u,ip=%s,index=%d\n", uin, ip_[ip_idx], index));
        init_conn(index, ip_idx);
    	if(conn_[ip_idx][index] == NULL)
    	{
    		ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx send_recv_ex reconnect failed,"
                "index=%d,ip_idx=%d\n", index, ip_idx));
    		return -1;
    	}
    }

    ACE_DEBUG((LM_TRACE, "[%D] PlatConnMgrEx send_recv_ex msg"
        ",index=%d,ip_idx=%d,uin=%u\n", index, ip_idx, uin));
    int ret = conn_[ip_idx][index]->send_n(send_buf, send_len, &time_out_);
    if (ret <= 0) //异常或者对端关闭
    {
        ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx send_recv_ex send msg failed"
            ",index=%d,ip_idx=%d,ret=%d,uin=%u,errno=%d\n", index, ip_idx, ret, uin, errno));
        //关闭连接,清理状态
        fini(index, ip_idx);
        Stat::instance()->incre_stat(STAT_CODE_SEND_FAIL);
        return ret;
    }
    ACE_DEBUG((LM_TRACE, "[%D] PlatConnMgrEx send_recv_ex send msg succ"
        ",index=%d,ip_idx=%d,ret=%d,uin=%u\n", index, ip_idx, ret, uin));
	// 
    ret = conn_[ip_idx][index]->recv(recv_buf, recv_len, &time_out_);
    if (ret <= 0) //异常或者对端关闭
    {
        ACE_DEBUG((LM_ERROR, "[%D] PlatConnMgrEx send_recv_ex recv msg failed"
            ",index=%d,ip_idx=%d,ret=%d,uin=%u,errno=%d\n", index, ip_idx, ret, uin, errno));
        //关闭连接,清理状态
        fini(index, ip_idx);
        Stat::instance()->incre_stat(STAT_CODE_RECV_FAIL);
        return ret;
    }

    // 判断结束符 
    if (separator != NULL)
    {
        int tmp_recv_len = ret;
        //判断消息是否结束
        while (strstr((const char*)recv_buf, separator) == NULL 
            && tmp_recv_len < max_recv_len) //未结束,继续接收
        {
            ret = conn_[ip_idx][index]->recv((char*)recv_buf + tmp_recv_len
                , max_recv_len - tmp_recv_len, &time_out_);
            if (ret <= 0) //异常或者对端关闭
            {
                ACE_DEBUG((LM_ERROR, "[%D] [%N,%l]PlatConnMgrEx send_recv_ex"
                    " recv msg failed"
                    ",index=%d,ip_idx=%d,ret=%d,uin=%u,errno=%d\n", index, ip_idx, ret, uin, errno));
                //关闭连接,清理状态
                fini(index, ip_idx);
                Stat::instance()->incre_stat(STAT_CODE_RECV_FAIL);
                return ret;
            }
            tmp_recv_len += ret;
            ACE_DEBUG((LM_TRACE, "[%D] PlatConnMgrEx send_recv_ex msg"
                ",index=%d,ip_idx=%d,ret=%d,uin=%u\n", index, ip_idx, ret, uin));
        }
        ret = tmp_recv_len;
    }

    ACE_DEBUG((LM_TRACE, "[%D] PlatConnMgrEx send_recv_ex msg succ"
        ",index=%d,ip_idx=%d,ret=%d,uin=%u\n", index, ip_idx, ret, uin));
    
    conn_use_flag_[ip_idx][index] = 0;//退出前清理使用状态
    return ret;
}