static void
transport_stop(void)
{
  event_base_loopexit(event_base, 0);
}
Ejemplo n.º 2
0
static void
sigint(int sig, short why, void * data) {
    event_base_loopexit(data, NULL);
}
Ejemplo n.º 3
0
int event_loopexit (struct timeval *tv)
{
  return event_base_loopexit (ev_x_cur, tv);
}
Ejemplo n.º 4
0
static void int_handler(int sig) {
    printf("\nShutting down...\n");
    event_base_loopexit(base, NULL);
}
/**
 * @author sohu-inc.com
 * event-handler thread,主要是完成后端检测
 * @param detect_thread
 */
void *backend_detect_thread_loop(backend_detect_thread_t *detect_thread) {
	/**
	 * @note 需要完成如下事情:
	 * 1. 创建socket,建立连接
	 * 2. 设置socket的状态为:ZABBIX_CON_STATE_WRITE_HEAD,意味着接下来向zabbix_agent端写数据
	 * 3. 调用network_zabbix_con_handle,开始与zabbix的交互.(由于network_zabbix_con_handle为异步处理,因而可能会中途返回)
	 * 4. 根据socket中状态机是否结束的标志及退出状态机的状态确定,确定接下来的动作。(若状态机没有退出,则不作特殊处理;若状态机退出,分情况处理)
	 * 5. 在认定后端down的情况下,需要另起一个线程对backend状态更新及已有连接处理。(因而最好保存一个检测的backend的指针!!!)
	 */

	g_assert(detect_thread);

	// 设置初始的状态,设置检测的状态机检测成功
	// 需要增加一个状态判定检测是不是成功

	/* 死循环 */
	while (!chassis_is_shutdown()) {
		GTimeVal begin_time;
		GTimeVal end_time;
		guint interval_seconds = 0;

		detection_task *task = NULL;
		network_backend_t *backend = NULL;
		chassis *chas = NULL;
		zabbix_socket *detect_socket = NULL;

		g_assert(detect_thread->task);
		g_assert(detect_thread->backend);
		g_assert(detect_thread->chas);
		g_assert(detect_thread->task->sock);

		task = detect_thread->task;
		backend = detect_thread->backend;
		chas = detect_thread->chas;
		detect_socket = task->sock;

		g_get_current_time(&begin_time);

		/* 状态pending的不需要检查 */
		if (backend->state == BACKEND_STATE_PENDING) {
			adjust_backend(BACKEND_STATE_PENDING, chas, backend);
			goto SLEEP;
		}

		/* 根据当前状态,取不同的间隔时间 */
		if (backend->state == BACKEND_STATE_DOWN) {
			interval_seconds = backend->health_check.fastdowninter;
		} else {
			interval_seconds = backend->health_check.inter;
		}
		//g_debug("timeout is set to %d seconds", interval_seconds);

		/**
		 * 初始化:
		 * 1. 设置需要检测的backend的ip,port
		 * 2. 创建与zabbix agent 的socket连接
		 * 3. 设置event_base, backend指针
		 */
		zabbix_socket_reset(detect_socket); // 初始化连接的标志信息
		/*设置套接字读写超时时间*/
		zabbix_socket_set_timeout(detect_socket, interval_seconds);
		network_zabbix_con_handle(-1, 0, detect_socket); // 开始与zabbix的通信过程

		/* 等待与zabbix通信完成,直到超时 */
		g_get_current_time(&end_time);
//		g_debug("begin_time: %ld.%06ld, end_time: %ld.%06ld", begin_time.tv_sec,
//				begin_time.tv_usec, end_time.tv_sec, end_time.tv_usec);
		while ((begin_time.tv_sec + interval_seconds > end_time.tv_sec)
				&& !chassis_is_shutdown()) {
			struct timeval timeout;
			int rr;
			/*0.1秒*/
			timeout.tv_sec = 0;
			timeout.tv_usec = 100000;
			g_assert(
					event_base_loopexit(detect_thread->event_base,
							&timeout) == 0);
			rr = event_base_dispatch(detect_thread->event_base);
			if (rr == -1) {
#ifdef WIN32
				errno = WSAGetLastError();
#endif
				if (errno == EINTR)
					continue;
				g_critical(
						"%s: leaving network_detection_thread_loop sleep early, errno != EINTR was: %s (%d)",
						G_STRLOC, g_strerror(errno), errno);
				break;
			}
			g_get_current_time(&end_time);
//			g_debug("begin_time: %ld.%06ld, end_time: %ld.%06ld", begin_time.tv_sec,
//					begin_time.tv_usec, end_time.tv_sec, end_time.tv_usec);

			if (detect_socket->is_over == TRUE) {
				break;
			}
		}
		/* (超时情况下)network_zabbix_con_handle可能注册了READ/WRITE事件,删除之 */
		event_del(&detect_socket->event);

		//接下来我们会判断返回的结果确定backend的状态
		task->backend_check_state = network_zabbix_status_check(task, task->detect_thread->backend);

		/**调整后端状态*/
		adjust_backend(task->backend_check_state, chas, task->detect_thread->backend);

SLEEP:
		/* 等待超过检查时间间隔后,再继续循环,否则一直等待 */
		if (backend->state == BACKEND_STATE_DOWN) {
			interval_seconds = backend->health_check.fastdowninter;
		} else if (backend->state == BACKEND_STATE_PENDING) {
			interval_seconds = backend->health_check.fastdowninter;
		} else {
			interval_seconds = backend->health_check.inter;
		}
		//g_debug("sleeptime is set to %d seconds", interval_seconds);
		g_get_current_time(&end_time);
		while ((begin_time.tv_sec + interval_seconds > end_time.tv_sec)
				&& !chassis_is_shutdown()) {
			struct timeval timeout;
			int rr;
			/*0.2秒*/
			timeout.tv_sec = 0;
			timeout.tv_usec = 200000;
			g_assert(
					event_base_loopexit(detect_thread->event_base,
							&timeout) == 0);
			rr = event_base_dispatch(detect_thread->event_base);
			if (rr == -1) {
#ifdef WIN32
				errno = WSAGetLastError();
#endif
				if (errno == EINTR)
					continue;
				g_critical(
						"%s: leaving network_detection_thread_loop sleep early, errno != EINTR was: %s (%d)",
						G_STRLOC, g_strerror(errno), errno);
				break;
			}
			g_get_current_time(&end_time);
//			g_debug("begin_time: %ld.%06ld, end_time: %ld.%06ld", begin_time.tv_sec,
//					begin_time.tv_usec, end_time.tv_sec, end_time.tv_usec);
		}

	} /* end of while() */

	g_message("detection thread is shutdown");
	return NULL;
}
Ejemplo n.º 6
0
static void
dns_gethostbyname_cb(int result, char type, int count, int ttl,
    void *addresses, void *arg)
{
	dns_ok = dns_err = 0;

	if (result == DNS_ERR_TIMEOUT) {
		printf("[Timed out] ");
		dns_err = result;
		goto out;
	}

	if (result != DNS_ERR_NONE) {
		printf("[Error code %d] ", result);
		goto out;
	}

	TT_BLATHER(("type: %d, count: %d, ttl: %d: ", type, count, ttl));

	switch (type) {
	case DNS_IPv6_AAAA: {
#if defined(_EVENT_HAVE_STRUCT_IN6_ADDR) && defined(_EVENT_HAVE_INET_NTOP) && defined(INET6_ADDRSTRLEN)
		struct in6_addr *in6_addrs = addresses;
		char buf[INET6_ADDRSTRLEN+1];
		int i;
		/* a resolution that's not valid does not help */
		if (ttl < 0)
			goto out;
		for (i = 0; i < count; ++i) {
			const char *b = inet_ntop(AF_INET6, &in6_addrs[i], buf,sizeof(buf));
			if (b)
				TT_BLATHER(("%s ", b));
			else
				TT_BLATHER(("%s ", strerror(errno)));
		}
#endif
		break;
	}
	case DNS_IPv4_A: {
		struct in_addr *in_addrs = addresses;
		int i;
		/* a resolution that's not valid does not help */
		if (ttl < 0)
			goto out;
		for (i = 0; i < count; ++i)
			TT_BLATHER(("%s ", inet_ntoa(in_addrs[i])));
		break;
	}
	case DNS_PTR:
		/* may get at most one PTR */
		if (count != 1)
			goto out;

		TT_BLATHER(("%s ", *(char **)addresses));
		break;
	default:
		goto out;
	}

	dns_ok = type;

out:
	if (arg == NULL)
		event_loopexit(NULL);
	else
		event_base_loopexit((struct event_base *)arg, NULL);
}
Ejemplo n.º 7
0
int
ub_event_base_loopexit(struct ub_event_base* base)
{
	return event_base_loopexit(AS_EVENT_BASE(base), NULL);
}
Ejemplo n.º 8
0
static void signal_cb(evutil_socket_t fd,short what,void*arg)
{
  struct event_base *base=arg;
  printf("stop\n");
  event_base_loopexit(base,NULL);
}
Ejemplo n.º 9
0
void NetServer::ServerAcceptError(evconnlistener* listener, void* ctx) {
	event_base_loopexit(net_evbase, 0);
}
Ejemplo n.º 10
0
void handle_sigint(int sig, short ev, void* arg)
{
	struct event_base* base = arg;
	printf("Caught signal %d\n", sig);
	event_base_loopexit(base, NULL);
}
Ejemplo n.º 11
0
	void Conn::stop()
	{
		event_base_loopexit(this->pEvbase, NULL);
	}
Ejemplo n.º 12
0
static void do_exit(void *eb) {
  log_info(("All interfaces have exited: stopping event loop"));
  event_base_loopexit((struct event_base *)eb,0);
}
Ejemplo n.º 13
0
static void pkt_loop_signal(evutil_socket_t in_fd, short what, void *vctx)
{
	struct packet_loop_ctx *ctx = vctx;
	event_base_loopexit(ctx->event_base, NULL);
}
Ejemplo n.º 14
0
static void
generic_handler(struct evhttp_request *req, void *arg)
{
  struct evkeyvalq args;
  thd_data *thd = arg;

  if (!loop) {
    event_base_loopexit(thd->base, NULL);
    return;
  }
  if (!req->uri) { return; }

  {
    char *uri = evhttp_decode_uri(req->uri);
    evhttp_parse_query(uri, &args);
    free(uri);
  }

  {
    struct evbuffer *res_buf;
    if (!(res_buf = evbuffer_new())) {
      err(1, "failed to create response buffer");
    }

    evhttp_add_header(req->output_headers,
      "Content-Type", "text/javascript; charset=UTF-8");
    evhttp_add_header(req->output_headers, "Connection", "close");

    {
      int content_length = log_send(res_buf, thd, &args);
      if (content_length >= 0) {
        char num_buf[16];
        snprintf(num_buf, 16, "%d", content_length);
        evhttp_add_header(req->output_headers, "Content-Length", num_buf);
      }
    }
    evhttp_send_reply(req, HTTP_OK, "OK", res_buf);
    evbuffer_free(res_buf);
    /* logging */
    {
      if (thd->log_path) {
        if (!thd->log_file) {
          time_t n;
          struct tm *t_st;
          char p[PATH_MAX + 1];

          time(&n);
          t_st = localtime(&n);

          snprintf(p, PATH_MAX, "%s%04d%02d%02d%02d%02d%02d-%02d",
            thd->log_path,
            t_st->tm_year + 1900, t_st->tm_mon + 1, t_st->tm_mday,
            t_st->tm_hour, t_st->tm_min, t_st->tm_sec, thd->thread_id);

          if (!(thd->log_file = fopen(p, "a"))) {
            print_error("cannot open log_file %s.", p);
          } else {
            thd->log_count = 0;
          }
        }
        if (thd->log_file) {
          fprintf(thd->log_file, "%s\n", req->uri);
          if (++thd->log_count >= LOG_SPLIT_LINES) {
            fclose(thd->log_file);
            thd->log_file = NULL;
          }
        }
      }
    }
  }
  evhttp_clear_headers(&args);
}
Ejemplo n.º 15
0
static void
http_request_done(struct evhttp_request *req, void *ctx) {
    char buffer[256];
    ev_ssize_t nread;
    struct evkeyval *header;


    if (req == NULL) {
        /* If req is NULL, it means an error occurred, but
         * sadly we are mostly left guessing what the error
         * might have been.  We'll do our best... */
        struct bufferevent *bev = (struct bufferevent *) ctx;


        int errcode = EVUTIL_SOCKET_ERROR();
        fprintf(stderr, "some request failed - no idea which one though!\n");
        /* Print out the OpenSSL error queue that libevent
         * squirreled away for us, if any. */

        /* If the OpenSSL error queue was empty, maybe it was a
         * socket error; let's try printing that. */

        fprintf(stderr, "socket error = %s (%d)\n",
                evutil_socket_error_to_string(errcode),
                errcode);
        return;
    }

    /*fprintf(stderr, "Response line: %d %s\n",
            evhttp_request_get_response_code(req),
            evhttp_request_get_response_code_line(req));

    struct evkeyvalq *headers = evhttp_request_get_input_headers(req);
    if (NULL != headers) {
        fprintf(stderr, "Response headers:\n");

        TAILQ_FOREACH(header, headers, next) {
            fprintf(stderr, "%s: %s\r\n",
                    header->key, header->value);
        }

        fprintf(stderr, "\n");
    }*/


    const int http_code = evhttp_request_get_response_code(req);
    struct evhttp_connection *evcon = evhttp_request_get_connection(req);


    if (HTTP_MOVEPERM == http_code || HTTP_MOVETEMP == http_code) {

        const char *location = evhttp_find_header(evhttp_request_get_input_headers(req), "Location");
        if (NULL != location) {
            //fprintf(stderr, "Location: %s\n", location);

            create_request(location);
        }
    }

    if (HTTP_OK == http_code) {

        struct evbuffer *input_buffer = evhttp_request_get_input_buffer(req);

        int found = 0;
        while ((nread = evbuffer_remove(input_buffer, buffer, sizeof (buffer))) > 0) {
            if (0 == search_find(&search_list, buffer, nread)) {
                found = 1;
                break;
            }
        }

        fprintf(stderr, "%s: %d\n", evhttp_find_header(evhttp_request_get_output_headers(req), "Host"), found);


    }


    if (--n_pending_requests == 0)
        event_base_loopexit(base, NULL);
}
Ejemplo n.º 16
0
void activity(int fd, short events, void* data) {
	struct event_base* event = (struct event_base*) data;

	event_base_loopexit(event, NULL);
}
Ejemplo n.º 17
0
void Master::MasterExitSignal(evutil_socket_t signo, short event, void *arg)
{	
	//kill(0, SIGINT); //终端下是不需要的,因为所以子进程跟终端关联,所以都会收到INT
	event_base_loopexit((struct event_base*)arg, NULL);
}
Ejemplo n.º 18
0
void HttpService::Stop()
{
    event_base_loopexit(base_, NULL);
    //event_base_loopbreak(base_);
    LOG_INFO("event_base_loopexit called");
}
Ejemplo n.º 19
0
static int
test_ratelimiting(void)
{
	struct event_base *base;
	struct sockaddr_in sin;
	struct evconnlistener *listener;

	struct sockaddr_storage ss;
	ev_socklen_t slen;

	int i;

	struct timeval tv;

	ev_uint64_t total_received;
	double total_sq_persec, total_persec;
	double variance;
	double expected_total_persec = -1.0, expected_avg_persec = -1.0;
	int ok = 1;
	struct event_config *base_cfg;
	struct event *periodic_level_check;
	struct event *group_drain_event=NULL;

	memset(&sin, 0, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
	sin.sin_port = 0; /* unspecified port */

	if (0)
		event_enable_debug_mode();

	base_cfg = event_config_new();

#ifdef _WIN32
	if (cfg_enable_iocp) {
		evthread_use_windows_threads();
		event_config_set_flag(base_cfg, EVENT_BASE_FLAG_STARTUP_IOCP);
	}
#endif

	base = event_base_new_with_config(base_cfg);
	event_config_free(base_cfg);
	if (! base) {
		fprintf(stderr, "Couldn't create event_base");
		return 1;
	}

	listener = evconnlistener_new_bind(base, echo_listenercb, base,
	    LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE, -1,
	    (struct sockaddr *)&sin, sizeof(sin));
	if (! listener) {
		fprintf(stderr, "Couldn't create listener");
		return 1;
	}

	slen = sizeof(ss);
	if (getsockname(evconnlistener_get_fd(listener), (struct sockaddr *)&ss,
		&slen) < 0) {
		perror("getsockname");
		return 1;
	}

	if (cfg_connlimit > 0) {
		conn_bucket_cfg = ev_token_bucket_cfg_new(
			cfg_connlimit, cfg_connlimit * 4,
			cfg_connlimit, cfg_connlimit * 4,
			&cfg_tick);
		assert(conn_bucket_cfg);
	}

	if (cfg_grouplimit > 0) {
		group_bucket_cfg = ev_token_bucket_cfg_new(
			cfg_grouplimit, cfg_grouplimit * 4,
			cfg_grouplimit, cfg_grouplimit * 4,
			&cfg_tick);
		group = ratelim_group = bufferevent_rate_limit_group_new(
			base, group_bucket_cfg);
		expected_total_persec = cfg_grouplimit - (cfg_group_drain / seconds_per_tick);
		expected_avg_persec = cfg_grouplimit / cfg_n_connections;
		if (cfg_connlimit > 0 && expected_avg_persec > cfg_connlimit)
			expected_avg_persec = cfg_connlimit;
		if (cfg_min_share >= 0)
			bufferevent_rate_limit_group_set_min_share(
				ratelim_group, cfg_min_share);
	}

	if (expected_avg_persec < 0 && cfg_connlimit > 0)
		expected_avg_persec = cfg_connlimit;

	if (expected_avg_persec > 0)
		expected_avg_persec /= seconds_per_tick;
	if (expected_total_persec > 0)
		expected_total_persec /= seconds_per_tick;

	bevs = calloc(cfg_n_connections, sizeof(struct bufferevent *));
	states = calloc(cfg_n_connections, sizeof(struct client_state));
	if (bevs == NULL || states == NULL) {
		printf("Unable to allocate memory...\n");
		return 1;
	}

	for (i = 0; i < cfg_n_connections; ++i) {
		bevs[i] = bufferevent_socket_new(base, -1,
		    BEV_OPT_CLOSE_ON_FREE|BEV_OPT_THREADSAFE);
		assert(bevs[i]);
		bufferevent_setcb(bevs[i], discard_readcb, loud_writecb,
		    write_on_connectedcb, &states[i]);
		bufferevent_enable(bevs[i], EV_READ|EV_WRITE);
		bufferevent_socket_connect(bevs[i], (struct sockaddr *)&ss,
		    slen);
	}

	tv.tv_sec = cfg_duration - 1;
	tv.tv_usec = 995000;

	event_base_loopexit(base, &tv);

	tv.tv_sec = 0;
	tv.tv_usec = 100*1000;
	ms100_common = event_base_init_common_timeout(base, &tv);

	periodic_level_check = event_new(base, -1, EV_PERSIST, check_group_bucket_levels_cb, NULL);
	event_add(periodic_level_check, ms100_common);

	if (cfg_group_drain && ratelim_group) {
		group_drain_event = event_new(base, -1, EV_PERSIST, group_drain_cb, NULL);
		event_add(group_drain_event, &cfg_tick);
	}

	event_base_dispatch(base);

	ratelim_group = NULL; /* So no more responders get added */
	event_free(periodic_level_check);
	if (group_drain_event)
		event_del(group_drain_event);

	for (i = 0; i < cfg_n_connections; ++i) {
		bufferevent_free(bevs[i]);
	}
	evconnlistener_free(listener);

	/* Make sure no new echo_conns get added to the group. */
	ratelim_group = NULL;

	/* This should get _everybody_ freed */
	while (n_echo_conns_open) {
		printf("waiting for %d conns\n", n_echo_conns_open);
		tv.tv_sec = 0;
		tv.tv_usec = 300000;
		event_base_loopexit(base, &tv);
		event_base_dispatch(base);
	}

	if (group)
		bufferevent_rate_limit_group_free(group);

	if (total_n_bev_checks) {
		printf("Average read bucket level: %f\n",
		    (double)total_rbucket_level/total_n_bev_checks);
		printf("Average write bucket level: %f\n",
		    (double)total_wbucket_level/total_n_bev_checks);
		printf("Highest read bucket level: %f\n",
		    (double)max_bucket_level);
		printf("Highest write bucket level: %f\n",
		    (double)min_bucket_level);
		printf("Average max-to-read: %f\n",
		    ((double)total_max_to_read)/total_n_bev_checks);
		printf("Average max-to-write: %f\n",
		    ((double)total_max_to_write)/total_n_bev_checks);
	}
	if (total_n_group_bev_checks) {
		printf("Average group read bucket level: %f\n",
		    ((double)total_group_rbucket_level)/total_n_group_bev_checks);
		printf("Average group write bucket level: %f\n",
		    ((double)total_group_wbucket_level)/total_n_group_bev_checks);
	}

	total_received = 0;
	total_persec = 0.0;
	total_sq_persec = 0.0;
	for (i=0; i < cfg_n_connections; ++i) {
		double persec = states[i].received;
		persec /= cfg_duration;
		total_received += states[i].received;
		total_persec += persec;
		total_sq_persec += persec*persec;
		printf("%d: %f per second\n", i+1, persec);
	}
	printf("   total: %f per second\n",
	    ((double)total_received)/cfg_duration);
	if (expected_total_persec > 0) {
		double diff = expected_total_persec -
		    ((double)total_received/cfg_duration);
		printf("  [Off by %lf]\n", diff);
		if (cfg_grouplimit_tolerance > 0 &&
		    fabs(diff) > cfg_grouplimit_tolerance) {
			fprintf(stderr, "Group bandwidth out of bounds\n");
			ok = 0;
		}
	}

	printf(" average: %f per second\n",
	    (((double)total_received)/cfg_duration)/cfg_n_connections);
	if (expected_avg_persec > 0) {
		double diff = expected_avg_persec - (((double)total_received)/cfg_duration)/cfg_n_connections;
		printf("  [Off by %lf]\n", diff);
		if (cfg_connlimit_tolerance > 0 &&
		    fabs(diff) > cfg_connlimit_tolerance) {
			fprintf(stderr, "Connection bandwidth out of bounds\n");
			ok = 0;
		}
	}

	variance = total_sq_persec/cfg_n_connections - total_persec*total_persec/(cfg_n_connections*cfg_n_connections);

	printf("  stddev: %f per second\n", sqrt(variance));
	if (cfg_stddev_tolerance > 0 &&
	    sqrt(variance) > cfg_stddev_tolerance) {
		fprintf(stderr, "Connection variance out of bounds\n");
		ok = 0;
	}

	event_base_free(base);
	free(bevs);
	free(states);

	return ok ? 0 : 1;
}
Ejemplo n.º 20
0
void sig_cb(int fd, short event, void *argc){
	struct event_base* base = (event_base*)argc;
	struct timeval delay = {2, 0};
	printf("SIGINT, exiting in two seconds\n");
	event_base_loopexit(base, &delay);
}
Ejemplo n.º 21
0
static void accept_error_cb(struct evconnlistener* listener, void* arg) {
    struct event_base* base = evconnlistener_get_base(listener);
    int error = EVUTIL_SOCKET_ERROR();
    printf("Error %d (%s). Shutting down...", error, evutil_socket_error_to_string(error));
    event_base_loopexit(base, NULL);
}
Ejemplo n.º 22
0
static void do_exit(evutil_socket_t fd,short what,void *eb) {
  event_base_loopexit((struct event_base *)eb,0);
}
Ejemplo n.º 23
0
void YYLibEvent::Exit()
{
	event_base_loopexit(base, NULL);
}
Ejemplo n.º 24
0
//Signal handlers
void term_handler(int signo)
{
    event_base_loopexit(base, NULL);
}
Ejemplo n.º 25
0
Archivo: main.c Proyecto: buaazp/zimg
/**
 * @brief sighandler the signal handler of zimg
 *
 * @param signal the signal zimg get
 * @param siginfo signal info
 * @param arg the arg for handler
 */
static void sighandler(int signal, siginfo_t *siginfo, void *arg) {
    char msg[128];
    msg[0] = '\0';
    str_lcat(msg, "----/--/-- --:--:--:------ [INFO] signal Terminal received zimg shutting down", sizeof(msg));
    //str_lcat(msg, strsignal(signal));
    log_handler(msg);
    write(STDOUT_FILENO, "\nbye bye!\n", 10);

    //evbase_t *evbase = (evbase_t *)arg;
    struct timeval tv = { .tv_usec = 100000, .tv_sec = 0 }; /* 100 ms */
    event_base_loopexit(evbase, &tv);
}

/**
 * @brief init_thread the init function of threads
 *
 * @param htp evhtp object
 * @param thread the current thread
 * @param arg the arg for init
 */
void init_thread(evhtp_t *htp, evthr_t *thread, void *arg) {
    thr_arg_t *thr_args;
    thr_args = calloc(1, sizeof(thr_arg_t));
    LOG_PRINT(LOG_DEBUG, "thr_args alloc");
    thr_args->thread = thread;

    char mserver[32];

    if (settings.cache_on == true) {
        memcached_st *memc = memcached_create(NULL);
        snprintf(mserver, 32, "%s:%d", settings.cache_ip, settings.cache_port);
        memcached_server_st *servers = memcached_servers_parse(mserver);
        memcached_server_push(memc, servers);
        memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_BINARY_PROTOCOL, 1);
        memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_NO_BLOCK, 1);
        memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_NOREPLY, 1);
        memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_TCP_KEEPALIVE, 1);
        thr_args->cache_conn = memc;
        LOG_PRINT(LOG_DEBUG, "Memcached Connection Init Finished.");
        memcached_server_list_free(servers);
    } else
        thr_args->cache_conn = NULL;

    if (settings.mode == 2) {
        thr_args->ssdb_conn = NULL;
        memcached_st *beans = memcached_create(NULL);
        snprintf(mserver, 32, "%s:%d", settings.beansdb_ip, settings.beansdb_port);
        memcached_server_st *servers = memcached_servers_parse(mserver);
        servers = memcached_servers_parse(mserver);
        memcached_server_push(beans, servers);
        memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_BINARY_PROTOCOL, 0);
        memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_NO_BLOCK, 1);
        memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_TCP_KEEPALIVE, 1);
        thr_args->beansdb_conn = beans;
        LOG_PRINT(LOG_DEBUG, "beansdb Connection Init Finished.");
        memcached_server_list_free(servers);
    } else if (settings.mode == 3) {
        thr_args->beansdb_conn = NULL;
        redisContext* c = redisConnect(settings.ssdb_ip, settings.ssdb_port);
        if (c->err) {
            redisFree(c);
            LOG_PRINT(LOG_DEBUG, "Connect to ssdb server faile");
        } else {
            thr_args->ssdb_conn = c;
            LOG_PRINT(LOG_DEBUG, "Connect to ssdb server Success");
        }
    }

    thr_args->L = luaL_newstate();
    LOG_PRINT(LOG_DEBUG, "luaL_newstate alloc");
    if (thr_args->L != NULL) {
        luaL_openlibs(thr_args->L);
        luaL_openlib(thr_args->L, "zimg", zimg_lib, 0);
        luaL_openlib(thr_args->L, "log", loglib, 0);
    }
    luaL_loadfile(thr_args->L, settings.script_name);
    lua_pcall(thr_args->L, 0, 0, 0);

    evthr_set_aux(thread, thr_args);

    lua_State *L = luaL_newstate();
    if (L != NULL) {
        luaL_openlibs(L);
        if (luaL_loadfile(L, conf_file) || lua_pcall(L, 0, 0, 0)) {
            lua_close(L);
        } else {
            pthread_setspecific(gLuaStateKey, (void *)L);
        }
    }
}
Ejemplo n.º 26
0
void EventManager::Stop()
{
	event_base_loopexit(_eventBase, 0);
}
Ejemplo n.º 27
0
void EventLoop::stop()
{
    event_base_loopexit(base, NULL);
}
Ejemplo n.º 28
0
int
main(int argc, char **argv)
{
	struct event_config *cfg = event_config_new();
	struct event_base *base;
	struct evhttp *http;
	int i;
	int c;
	int use_iocp = 0;
	unsigned short port = 8080;
	char *endptr = NULL;

#ifdef WIN32
	WSADATA WSAData;
	WSAStartup(0x101, &WSAData);
#else
	if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
		return (1);
#endif

	for (i = 1; i < argc; ++i) {
		if (*argv[i] != '-')
			continue;

		c = argv[i][1];

		if ((c == 'p' || c == 'l') && i + 1 >= argc) {
			fprintf(stderr, "-%c requires argument.\n", c);
			exit(1);
		}

		switch (c) {
		case 'p':
			if (i+1 >= argc || !argv[i+1]) {
				fprintf(stderr, "Missing port\n");
				exit(1);
			}
			port = (int)strtol(argv[i+1], &endptr, 10);
			if (*endptr != '\0') {
				fprintf(stderr, "Bad port\n");
				exit(1);
			}
			break;
		case 'l':
			if (i+1 >= argc || !argv[i+1]) {
				fprintf(stderr, "Missing content length\n");
				exit(1);
			}
			content_len = (size_t)strtol(argv[i+1], &endptr, 10);
			if (*endptr != '\0' || content_len == 0) {
				fprintf(stderr, "Bad content length\n");
				exit(1);
			}
			break;
#ifdef WIN32
		case 'i':
			use_iocp = 1;
			evthread_use_windows_threads();
			event_config_set_flag(cfg,EVENT_BASE_FLAG_STARTUP_IOCP);
			break;
#endif
		default:
			fprintf(stderr, "Illegal argument \"%c\"\n", c);
			exit(1);
		}
	}

	base = event_base_new_with_config(cfg);
	if (!base) {
		fprintf(stderr, "creating event_base failed. Exiting.\n");
		return 1;
	}

	http = evhttp_new(base);

	content = malloc(content_len);
	if (content == NULL) {
		fprintf(stderr, "Cannot allocate content\n");
		exit(1);
	} else {
		int i = 0;
		for (i = 0; i < (int)content_len; ++i)
			content[i] = (i & 255);
	}

	evhttp_set_cb(http, "/ind", http_basic_cb, NULL);
	fprintf(stderr, "/ind - basic content (memory copy)\n");

#ifdef _EVENT2_EVENT_H_
	evhttp_set_cb(http, "/ref", http_ref_cb, NULL);
	fprintf(stderr, "/ref - basic content (reference)\n");
#endif

	fprintf(stderr, "Serving %d bytes on port %d using %s\n",
	    (int)content_len, port,
	    use_iocp? "IOCP" : event_base_get_method(base));

	evhttp_bind_socket(http, "0.0.0.0", port);

	if (use_iocp) {
		struct timeval tv={99999999,0};
		event_base_loopexit(base, &tv);
	}
	event_base_dispatch(base);

	/* NOTREACHED */
	return (0);
}
Ejemplo n.º 29
0
 void cancelLoop() {
     if (event_base_loopexit(m_ebase, NULL)) {
         ERROR_OUT("Error shutting down the server\n");
     }
 }
Ejemplo n.º 30
0
void storage_recv_notify_read(int sock, short event, void *arg)
{
	struct fast_task_info *pTask;
	StorageClientInfo *pClientInfo;
	long task_addr;
	int64_t remain_bytes;
	int bytes;
	int result;

	while (1)
	{
		if ((bytes=read(sock, &task_addr, sizeof(task_addr))) < 0)
		{
			if (!(errno == EAGAIN || errno == EWOULDBLOCK))
			{
				logError("file: "__FILE__", line: %d, " \
					"call read failed, " \
					"errno: %d, error info: %s", \
					__LINE__, errno, STRERROR(errno));
			}

			break;
		}
		else if (bytes == 0)
		{
			logError("file: "__FILE__", line: %d, " \
				"call read failed, end of file", __LINE__);
			break;
		}

		pTask = (struct fast_task_info *)task_addr;
		pClientInfo = (StorageClientInfo *)pTask->arg;

		if (pClientInfo->sock < 0)  //quit flag
		{
			struct storage_nio_thread_data *pThreadData;
			struct timeval tv;

			pThreadData = g_nio_thread_data + \
					pClientInfo->nio_thread_index;
                        tv.tv_sec = 1;
                        tv.tv_usec = 0;
			event_base_loopexit(pThreadData->ev_base, &tv);
			return;
		}

		/* //logInfo("=====thread index: %d, pClientInfo->sock=%d", \
			pClientInfo->nio_thread_index, pClientInfo->sock);
		*/

		switch (pClientInfo->stage)
		{
			case FDFS_STORAGE_STAGE_NIO_INIT:
				result = storage_nio_init(pTask);
				break;
			case FDFS_STORAGE_STAGE_NIO_RECV:
				pTask->offset = 0;
				remain_bytes = pClientInfo->total_length - \
					       pClientInfo->total_offset;
				if (remain_bytes > pTask->size)
				{
					pTask->length = pTask->size;
				}
				else
				{
					pTask->length = remain_bytes;
				}

				client_sock_read(pClientInfo->sock, EV_READ, pTask);
				result = 0;
				/*
				if ((result=event_add(&pTask->ev_read, \
						&g_network_tv)) != 0)
				{
					logError("file: "__FILE__", line: %d, " \
						"event_add fail.", __LINE__);
				}
				*/
				break;
			case FDFS_STORAGE_STAGE_NIO_SEND:
				result = storage_send_add_event(pTask);
				break;
			default:
				logError("file: "__FILE__", line: %d, " \
					"invalid stage: %d", __LINE__, \
					pClientInfo->stage);
				result = EINVAL;
				break;
		}

		if (result != 0)
		{
			task_finish_clean_up(pTask);
		}
	}
}