コード例 #1
0
bool IOEventLoop::EnsureInit() {
  if (ebase_ == nullptr) {
    event_config* cfg = event_config_new();
    if (cfg != nullptr) {
      if (use_precise_timer_) {
        event_config_set_flag(cfg, EVENT_BASE_FLAG_PRECISE_TIMER);
      }
      if (event_config_avoid_method(cfg, "epoll") != 0) {
        LOG(ERROR) << "event_config_avoid_method";
        return false;
      }
      ebase_ = event_base_new_with_config(cfg);
      // perf event files support reporting available data via poll methods. However, it doesn't
      // work well with epoll. Because perf_poll() in kernel/events/core.c uses a report and reset
      // way to report poll events. If perf_poll() is called twice, it may return POLLIN for the
      // first time, and no events for the second time. And epoll may call perf_poll() more than
      // once to confirm events. A failed situation is below:
      // When profiling SimpleperfExampleOfKotlin on Pixel device with `-g --duration 10`, the
      // kernel fills up the buffer before we call epoll_ctl(EPOLL_CTL_ADD). Then the POLLIN event
      // is returned when calling epoll_ctl(), while no events are returned when calling
      // epoll_wait(). As a result, simpleperf doesn't receive any poll wakeup events.
      if (strcmp(event_base_get_method(ebase_), "poll") != 0) {
        LOG(ERROR) << "event_base_get_method isn't poll: " << event_base_get_method(ebase_);
        return false;
      }
      event_config_free(cfg);
    }
    if (ebase_ == nullptr) {
      LOG(ERROR) << "failed to create event_base";
      return false;
    }
  }
  return true;
}
コード例 #2
0
ファイル: InitEventBase.cpp プロジェクト: 867344633/QService
void CInitBase::Init(void)
{
    m_pCfg = event_config_new();
    if (NULL == m_pCfg)
    {
        Q_EXCEPTION(Q_RTN_FAILE, "%s", "event_config_new error.");
    }

#ifdef Q_IOCP
    evthread_use_windows_threads();
    event_config_set_flag(m_pCfg, EVENT_BASE_FLAG_STARTUP_IOCP);
#endif

    m_pBase = event_base_new_with_config(m_pCfg);
    if (NULL == m_pBase)
    {
        Q_EXCEPTION(Q_RTN_FAILE, "%s", "event_base_new error.");
    }

#ifdef Q_IOCP
    Q_Printf("event version %s, using %s", event_get_version(), "IOCP");
#else
    Q_Printf("event version %s, using %s", event_get_version(), event_base_get_method(m_pBase));
#endif
}
コード例 #3
0
ファイル: HawkGateThread.cpp プロジェクト: YunYi/hawkutil
	Bool HawkGateThread::Init(UInt32 iBaseId)
	{
		HawkAssert(!m_pThread && !m_pBase && !m_pZmq);

		m_iBaseSid = iBaseId;

		//创建通用缓冲
		if (!m_pOctets)
			m_pOctets = new OctetsStream(m_pGateway->GetBufSize());

		//创建线程
		if (!m_pThread)
			m_pThread = new HawkThread(hawk_GateThreadRoutine);

		//创建事件基础对象
		if (!m_pBase)
		{
			event_config* pCfg = event_config_new();
			if (!pCfg) 
			{
				HawkPrint("Create EventConfig Failed.");
				return false;
			}
			
#ifdef PLATFORM_LINUX
			event_config_require_features(pCfg, EV_FEATURE_ET);
#endif
			event_config_set_flag(pCfg, EVENT_BASE_FLAG_NOLOCK);

			m_pBase = (void*)event_base_new_with_config(pCfg);
			event_config_free(pCfg);
			if (!m_pBase)
			{
				HawkPrint("Create EventBase Failed.");
				return false;
			}

			if (m_iBaseSid == 1)
			{
				const Char* pszMethod = event_base_get_method((event_base*)m_pBase);
				if (pszMethod && strlen(pszMethod))
				{
					HawkFmtPrint("Kernel Event Notification Mechanism: %s", pszMethod);
				}
			}			
		}

		//创建ZMQ对象
		if (!m_pZmq)
		{
			m_pZmq = P_ZmqManager->CreateZmq(HawkZmq::HZMQ_DEALER);
			m_pZmq->SetIdentity(&m_iBaseSid, sizeof(m_iBaseSid));
			m_pZmq->Connect(m_pGateway->GetThreadZmqAddr());
		}

		return true;
	}
コード例 #4
0
ファイル: compat_libevent.c プロジェクト: ageis/tor
/** Initialize the Libevent library and set up the event base. */
void
tor_libevent_initialize(tor_libevent_cfg *torcfg)
{
  tor_assert(the_event_base == NULL);
  /* some paths below don't use torcfg, so avoid unused variable warnings */
  (void)torcfg;

  {
    int attempts = 0;
    struct event_config *cfg;

    ++attempts;
    cfg = event_config_new();
    tor_assert(cfg);

    /* Telling Libevent not to try to turn locking on can avoid a needless
     * socketpair() attempt. */
    event_config_set_flag(cfg, EVENT_BASE_FLAG_NOLOCK);

    if (torcfg->num_cpus > 0)
      event_config_set_num_cpus_hint(cfg, torcfg->num_cpus);

    /* We can enable changelist support with epoll, since we don't give
     * Libevent any dup'd fds.  This lets us avoid some syscalls. */
    event_config_set_flag(cfg, EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST);

    the_event_base = event_base_new_with_config(cfg);

    event_config_free(cfg);
  }

  if (!the_event_base) {
    /* LCOV_EXCL_START */
    log_err(LD_GENERAL, "Unable to initialize Libevent: cannot continue.");
    exit(1); // exit ok: libevent is broken.
    /* LCOV_EXCL_STOP */
  }

  log_info(LD_GENERAL,
      "Initialized libevent version %s using method %s. Good.",
      event_get_version(), tor_libevent_get_method());
}
コード例 #5
0
ファイル: thread.c プロジェクト: sidgwick/memcached
/*
 * Set up a thread's information.
 */
static void setup_thread(LIBEVENT_THREAD *me) {
#if defined(LIBEVENT_VERSION_NUMBER) && LIBEVENT_VERSION_NUMBER >= 0x02000101
    struct event_config *ev_config;
    ev_config = event_config_new();
    event_config_set_flag(ev_config, EVENT_BASE_FLAG_NOLOCK);
    me->base = event_base_new_with_config(ev_config);
    event_config_free(ev_config);
#else
    me->base = event_init();
#endif

    if (! me->base) {
        fprintf(stderr, "Can't allocate event base\n");
        exit(1);
    }

    /* Listen for notifications from other threads */
    event_set(&me->notify_event, me->notify_receive_fd,
              EV_READ | EV_PERSIST, thread_libevent_process, me);
    event_base_set(me->base, &me->notify_event);

    if (event_add(&me->notify_event, 0) == -1) {
        fprintf(stderr, "Can't monitor libevent notify pipe\n");
        exit(1);
    }

    me->new_conn_queue = malloc(sizeof(struct conn_queue));
    if (me->new_conn_queue == NULL) {
        perror("Failed to allocate memory for connection queue");
        exit(EXIT_FAILURE);
    }
    cq_init(me->new_conn_queue);

    if (pthread_mutex_init(&me->stats.mutex, NULL) != 0) {
        perror("Failed to initialize mutex");
        exit(EXIT_FAILURE);
    }

    me->suffix_cache = cache_create("suffix", SUFFIX_SIZE, sizeof(char*),
                                    NULL, NULL);
    if (me->suffix_cache == NULL) {
        fprintf(stderr, "Failed to create suffix cache\n");
        exit(EXIT_FAILURE);
    }
#ifdef EXTSTORE
    me->io_cache = cache_create("io", sizeof(io_wrap), sizeof(char*), NULL, NULL);
    if (me->io_cache == NULL) {
        fprintf(stderr, "Failed to create IO object cache\n");
        exit(EXIT_FAILURE);
    }
#endif
}
コード例 #6
0
ファイル: compat_libevent.c プロジェクト: alexwykoff/tor
/** Initialize the Libevent library and set up the event base. */
void
tor_libevent_initialize(void)
{
  tor_assert(the_event_base == NULL);

#ifdef __APPLE__
  if (MACOSX_KQUEUE_IS_BROKEN ||
      tor_get_libevent_version(NULL) < V_OLD(1,1,'b')) {
    setenv("EVENT_NOKQUEUE","1",1);
  }
#endif

#ifdef HAVE_EVENT2_EVENT_H
  {
    struct event_config *cfg = event_config_new();
    tor_assert(cfg);

    /* In 0.2.2, we don't use locking at all.  Telling Libevent not to try to
     * turn it on can avoid a needless socketpair() attempt.
     */
    event_config_set_flag(cfg, EVENT_BASE_FLAG_NOLOCK);

    the_event_base = event_base_new_with_config(cfg);

    event_config_free(cfg);
  }
#else
  the_event_base = event_init();
#endif

  if (!the_event_base) {
    log_err(LD_GENERAL, "Unable to initialize Libevent: cannot continue.");
    exit(1);
  }

#if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
  /* Making this a NOTICE for now so we can link bugs to a libevent versions
   * or methods better. */
  log(LOG_NOTICE, LD_GENERAL,
      "Initialized libevent version %s using method %s. Good.",
      event_get_version(), tor_libevent_get_method());
#else
  log(LOG_NOTICE, LD_GENERAL,
      "Initialized old libevent (version 1.0b or earlier).");
  log(LOG_WARN, LD_GENERAL,
      "You have a *VERY* old version of libevent.  It is likely to be buggy; "
      "please build Tor with a more recent version.");
#endif
}
コード例 #7
0
ClientImpl::ClientImpl(ClientConfig config) throw(voltdb::Exception, voltdb::LibEventException) :
        m_nextRequestId(INT64_MIN), m_nextConnectionIndex(0), m_listener(config.m_listener),
        m_invocationBlockedOnBackpressure(false), m_loopBreakRequested(false), m_isDraining(false),
        m_instanceIdIsSet(false), m_outstandingRequests(0), m_username(config.m_username),
        m_maxOutstandingRequests(config.m_maxOutstandingRequests), m_ignoreBackpressure(false),
        m_useClientAffinity(false),m_updateHashinator(false), m_pendingConnectionSize(0) ,
        m_pLogger(0)
{

    pthread_once(&once_initLibevent, initLibevent);
#ifdef DEBUG
    if (!voltdb_clientimpl_debug_init_libevent) {
        event_enable_debug_mode();
        voltdb_clientimpl_debug_init_libevent = true;
    }
#endif
    struct event_config *cfg = event_config_new();
    event_config_set_flag(cfg, EVENT_BASE_FLAG_NO_CACHE_TIME);//, EVENT_BASE_FLAG_NOLOCK);
    m_base = event_base_new_with_config(cfg);
    assert(m_base);
    if (!m_base) {
        throw voltdb::LibEventException();
    }
    m_hashScheme = config.m_hashScheme;
    if (m_hashScheme == HASH_SHA1) {
        SHA1_CTX context;
        SHA1_Init(&context);
        SHA1_Update( &context, reinterpret_cast<const unsigned char*>(config.m_password.data()), config.m_password.size());
        m_passwordHash = (unsigned char *)malloc(20*sizeof(char));
        SHA1_Final ( &context, m_passwordHash);
    } else if (config.m_hashScheme == HASH_SHA256) {
        m_passwordHash = (unsigned char *)malloc(32*sizeof(char));
        computeSHA256(config.m_password.c_str(), config.m_password.size(), m_passwordHash);
    } else {
        throw voltdb::LibEventException();
    }

    if (0 == pipe(m_wakeupPipe)) {
        struct event *ev = event_new(m_base, m_wakeupPipe[0], EV_READ|EV_PERSIST, wakeupPipeCallback, this);
        event_add(ev, NULL);
    } else {
        m_wakeupPipe[1] = -1;
    }
    SHA1_CTX context;
    SHA1_Init(&context);
    SHA1_Update( &context, reinterpret_cast<const unsigned char*>(config.m_password.data()), config.m_password.size());
    SHA1_Final(&context, m_passwordHash);
}
コード例 #8
0
ファイル: XtReactor.cpp プロジェクト: tempbottle/xtrovert
int CXtReactor::IocpInit(void)
{
	if ( m_pEvtBaseCfg == NULL )
	{
		new_event_base_cfg;
		if ( m_pEvtBaseCfg == NULL )
		{
			return XT_REACT_ERR_MEM_FAIL;
		}
	}

	evthread_use_windows_threads();
	event_config_set_flag( m_pEvtBaseCfg, EVENT_BASE_FLAG_STARTUP_IOCP );
	m_pEvtBase = event_base_new_with_config(m_pEvtBaseCfg);

	event_config_free(m_pEvtBaseCfg);

	return FUN_RET_OK;
}
コード例 #9
0
int
main(int argc, char **argv)
{
    struct event_config *evcfg;
    struct event_base *base;
    struct evconnlistener *listener;

    struct sockaddr_in sin;
    WSADATA wsa_data;
    WSAStartup(0x0201, &wsa_data);

    evcfg = event_config_new();
    event_config_set_flag(evcfg, EVENT_BASE_FLAG_STARTUP_IOCP);
    base = event_base_new_with_config(evcfg);
    //base = event_base_new();
    if (!base) {
        fprintf(stderr, "Could not initialize libevent!\n");
        return 1;
    }

    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_port = htons(PORT);

    listener = evconnlistener_new_bind(base, listener_cb, (void *)base,
                                       LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE, -1,
                                       (struct sockaddr*)&sin,
                                       sizeof(sin));

    if (!listener) {
        fprintf(stderr, "Could not create a listener!\n");
        return 1;
    }


    event_base_dispatch(base);
    return 0;
}
コード例 #10
0
ファイル: bench_http.c プロジェクト: amking/libevent
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");

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

	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);

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

	/* NOTREACHED */
	return (0);
}
コード例 #11
0
ファイル: compat_libevent.c プロジェクト: twstrike/tor
/** Initialize the Libevent library and set up the event base. */
void
tor_libevent_initialize(tor_libevent_cfg *torcfg)
{
  tor_assert(the_event_base == NULL);
  /* some paths below don't use torcfg, so avoid unused variable warnings */
  (void)torcfg;

#ifdef HAVE_EVENT2_EVENT_H
  {
    int attempts = 0;
    int using_threads;
    struct event_config *cfg;

  retry:
    ++attempts;
    using_threads = 0;
    cfg = event_config_new();
    tor_assert(cfg);

#if defined(_WIN32) && defined(USE_BUFFEREVENTS)
    if (! torcfg->disable_iocp) {
      evthread_use_windows_threads();
      event_config_set_flag(cfg, EVENT_BASE_FLAG_STARTUP_IOCP);
      using_iocp_bufferevents = 1;
      using_threads = 1;
    } else {
      using_iocp_bufferevents = 0;
    }
#elif defined(__COVERITY__)
    /* Avoid a 'dead code' warning below. */
    using_threads = ! torcfg->disable_iocp;
#endif

    if (!using_threads) {
      /* Telling Libevent not to try to turn locking on can avoid a needless
       * socketpair() attempt. */
      event_config_set_flag(cfg, EVENT_BASE_FLAG_NOLOCK);
    }

#if defined(LIBEVENT_VERSION_NUMBER) && LIBEVENT_VERSION_NUMBER >= V(2,0,7)
    if (torcfg->num_cpus > 0)
      event_config_set_num_cpus_hint(cfg, torcfg->num_cpus);
#endif

#if LIBEVENT_VERSION_NUMBER >= V(2,0,9)
    /* We can enable changelist support with epoll, since we don't give
     * Libevent any dup'd fds.  This lets us avoid some syscalls. */
    event_config_set_flag(cfg, EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST);
#endif

    the_event_base = event_base_new_with_config(cfg);

    event_config_free(cfg);

    if (using_threads && the_event_base == NULL && attempts < 2) {
      /* This could be a socketpair() failure, which can happen sometimes on
       * windows boxes with obnoxious firewall rules.  Downgrade and try
       * again. */
#if defined(_WIN32) && defined(USE_BUFFEREVENTS)
      if (torcfg->disable_iocp == 0) {
        log_warn(LD_GENERAL, "Unable to initialize Libevent. Trying again "
                 "with IOCP disabled.");
      } else
#endif
      {
          log_warn(LD_GENERAL, "Unable to initialize Libevent. Trying again.");
      }

      torcfg->disable_iocp = 1;
      goto retry;
    }
  }
#else
  the_event_base = event_init();
#endif

  if (!the_event_base) {
    log_err(LD_GENERAL, "Unable to initialize Libevent: cannot continue.");
    exit(1);
  }

  /* Making this a NOTICE for now so we can link bugs to a libevent versions
   * or methods better. */
  log_info(LD_GENERAL,
      "Initialized libevent version %s using method %s. Good.",
      event_get_version(), tor_libevent_get_method());

#ifdef USE_BUFFEREVENTS
  tor_libevent_set_tick_timeout(torcfg->msec_per_tick);
#endif
}
コード例 #12
0
ファイル: test.cpp プロジェクト: aubonbeurre/abbsandbox
int main(int argc, char*argv[]) {
	printf("Hello, world!\n");

	event_config *conf = event_config_new();

#ifdef WIN32
	WORD wVersionRequested;
	WSADATA wsaData;
	int err;

	/* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
	wVersionRequested = MAKEWORD(2, 2);

	err = WSAStartup(wVersionRequested, &wsaData);
	if (err != 0) {
		/* Tell the user that we could not find a usable */
		/* Winsock DLL.                                  */
		printf("WSAStartup failed with error: %d\n", err);
		return 1;
	}

	evthread_use_windows_threads();

	event_config_set_flag(conf, EVENT_BASE_FLAG_STARTUP_IOCP);
#endif

	base = event_base_new_with_config(conf);
	const char ** methods = event_get_supported_methods();
	int loop;

	std::cout << "Version: " << event_get_version() << std::endl;
	std::cout << "Method: " << event_base_get_method(base) << std::endl;
	std::cout << "Features: 0x" << std::hex << event_base_get_features(base)
			<< std::endl;
	std::cout << "Base: " << base << std::endl;
	while (*methods) {
		std::cout << "Method: " << *methods++ << std::endl;
	}

	event_set_log_callback(_log_cb);

	/* The caller has already set up fd1, fd2 somehow, and make them
	 nonblocking. */

	if (0) {
		evutil_socket_t fd1 = 1;
		evutil_socket_t fd2 = 1;
		struct timeval five_seconds = { 5, 0 };
		struct event *ev1 = event_new(base, fd1,
				EV_TIMEOUT | EV_READ/*|EV_PERSIST*/, cb_func,
				(char*) "Reading event");
		struct event *ev2 = event_new(base, fd2, EV_WRITE/*|EV_PERSIST*/, cb_func,
				(char*) "Writing event");

		event_add(ev1, &five_seconds);
		event_add(ev2, NULL);

		std::cout << "\nEntering loop" << std::endl;
		loop = event_base_loop(base, 0);
		std::cout << "Exiting loop: " << loop << std::endl;
	}

	// http server
	evhttp *ev_http = evhttp_new(base);
	int http_port = 9090;

	// evhttp_bind_socket expects its PORT param in host byte order. Sigh.
	int r = evhttp_bind_socket(ev_http, "0.0.0.0", http_port);
	// This return value is undocumented (!), but this seems to work.
	if (r == -1) {
		std::cerr << "could not open port " << http_port << std::endl;
		return 3;
	}

	evhttp_set_gencb(ev_http, http_handle_generic, 0);
	//evhttp_set_cb(ev_http, "/", http_handle_root);

	std::cout << "\nEntering loop" << std::endl;
	loop = event_base_loop(base, 0);
	std::cout << "Exiting loop: " << loop << std::endl;

	evhttp_free(ev_http);

	event_base_free(base);
	event_config_free(conf);

	return 0;
}
コード例 #13
0
void *http_server(apr_thread_t* t, void* d)
{
	http_server_data_t *server_data = d;
	struct event_config *cfg = event_config_new();
	struct event_base *base = NULL;
	struct evhttp *http = NULL;
	int i = 0;

	event_config_set_flag(cfg, EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST);

	base = event_base_new_with_config(cfg);
	if (!base)
	{
		LOG4C_ERROR(logger, "Couldn't create an event_base: exiting");
		goto done;
	}

	event_config_free(cfg);

	/* Create a new evhttp object to handle requests. */
	http = evhttp_new(base);
	if (!http)
	{
	    LOG4C_ERROR(logger, "couldn't create evhttp. Exiting.");
		goto done;
	}

	evhttp_add_server_alias(http, "TVersity-Virtual-STB");

	for (i = 0; i < server_data->num_handlers; i++)
	{
		evhttp_set_cb(http, server_data->handlers[i].uri, http_request_cb, &(server_data->handlers[i]));
	}

	//set up static file handler
	if (server_data->static_root)
	{
	    evhttp_set_gencb(http, static_files_cb, (void *) server_data->static_root);
	}

	struct evhttp_bound_socket *handle = evhttp_accept_socket_with_handle(http, server_data->sock);
	if (!handle)
	{
        LOG4C_ERROR(logger, "could not accept on socket");
		goto done;
	}

	server_base[server_data->server_index] = base;

	event_base_dispatch(base);

done:
    if(server_data)
        free(server_data);
    if(http)
    {
        evhttp_free(http);
    }
	if (base)
	{
        server_base[server_data->server_index] = NULL;
	    event_base_free(base);
	}

	apr_atomic_dec32(&num_servers);

	return NULL;
}
コード例 #14
0
ファイル: NFCNet.cpp プロジェクト: joyfish/NoahGameFrame
int NFCNet::InitServerNet()
{
    int nMaxClient = mnMaxConnect;
    int nCpuCount = mnCpuCount;
    int nPort = mnPort;

    struct sockaddr_in sin;

#if NF_PLATFORM == NF_PLATFORM_WIN
    WSADATA wsa_data;
    WSAStartup(0x0201, &wsa_data);

#endif
    //////////////////////////////////////////////////////////////////////////

    struct event_config *cfg = event_config_new();

#if NF_PLATFORM == NF_PLATFORM_WIN

    //event_config_avoid_method(cfg, "iocp");
    //event_config_require_features(cfg, event_method_feature.EV_FEATURE_ET);//触发方式
    evthread_use_windows_threads();
    if(event_config_set_flag(cfg, EVENT_BASE_FLAG_STARTUP_IOCP) < 0)
    {
        //使用IOCP
        return -1;
    }

    if(event_config_set_num_cpus_hint(cfg, nCpuCount) < 0)
    {
        return -1;
    }

    base = event_base_new_with_config(cfg);

#else

    //event_config_avoid_method(cfg, "epoll");
    if(event_config_set_flag(cfg, EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST) < 0)
    {
        //使用EPOLL
        return -1;
    }

    if(event_config_set_num_cpus_hint(cfg, nCpuCount) < 0)
    {
        return -1;
    }

    base = event_base_new_with_config(cfg);//event_base_new()

#endif
    event_config_free(cfg);

    //////////////////////////////////////////////////////////////////////////

    if (!base)
    {
        fprintf(stderr, "Could not initialize libevent!\n");
        Final();

        return -1;
    }

    //初始化时间
    //gettime(base, &base->event_tv);

    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_port = htons(nPort);

    printf("server started with %d\n", nPort);

    listener = evconnlistener_new_bind(base, listener_cb, (void *)this,
                                       LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE, -1,
                                       (struct sockaddr*)&sin,
                                       sizeof(sin));

    if (!listener)
    {
        fprintf(stderr, "Could not create a listener!\n");
        Final();

        return -1;
    }

    //     signal_event = evsignal_new(base, SIGINT, signal_cb, (void *)this);
    //
    //     if (!signal_event || event_add(signal_event, NULL)<0)
    //     {
    //         fprintf(stderr, "Could not create/add a signal event!\n");
    //         Final();
    //         return -1;
    //     }

    mbServer = true;

    event_set_log_callback(&NFCNet::log_cb);

    return mnMaxConnect;
}
コード例 #15
0
ファイル: net_service_internal.cpp プロジェクト: dxmgame/dxm
bool CNetService::Initialize( Foundation::LogService::ILog::Ptr log, unsigned int recv_size ) {

	DXM_COMPONENT_LOG.set_log(log);
	DXM_NDC("NetService::Initialize");

	boost::unique_lock<boost::shared_mutex> lock(running_mutex_);
	if(is_running_) 
	{
		DXM_COMPONENT_LOG( DXM_COMPONENT_LOG_LEVEL_ERROR, "net service is initialized");
		return false;
	}

	if(recv_size == 0) {
		DXM_COMPONENT_LOG(DXM_COMPONENT_LOG_LEVEL_ERROR, "recv_size cannot be 0" );
		return false;
	}

	tls_recv_buffer_.set_default_size(recv_size);

#ifdef WIN32
	//	wsa init
	WSAData wsaData;
	if(WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
		DXM_COMPONENT_LOG( DXM_COMPONENT_LOG_LEVEL_ERROR, "net service initialize WSAStartup failed.");
		return false;
	}

	DXM_COMPONENT_LOG( DXM_COMPONENT_LOG_LEVEL_TRACE, "wsastartup ok.");

	//	about thread and lock
	evthread_use_windows_threads();
	DXM_COMPONENT_LOG( DXM_COMPONENT_LOG_LEVEL_TRACE, "evthread_set ok.");

	//	get count of processors
	SYSTEM_INFO sysInfo;
	GetSystemInfo(&sysInfo);
	DXM_COMPONENT_LOG( DXM_COMPONENT_LOG_LEVEL_TRACE, "getsysteminfo ok. numberofprocessors: %u.", sysInfo.dwNumberOfProcessors);

	//	event config
	ev_config_ = event_config_new();
	event_config_set_flag(ev_config_, EVENT_BASE_FLAG_STARTUP_IOCP);
	event_config_set_num_cpus_hint(ev_config_, sysInfo.dwNumberOfProcessors);
	DXM_COMPONENT_LOG( DXM_COMPONENT_LOG_LEVEL_TRACE, "event_config_set ok.");
#else
	//	about thread and lock
	evthread_use_pthreads();

	//	event config
	ev_config_ = event_config_new();
	event_config_set_flag(ev_config_, EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST);
	DXM_COMPONENT_LOG(DXM_COMPONENT_LOG_LEVEL_TRACE, "event_config_set ok.");
#endif

	//	event base
	ev_base_ = event_base_new_with_config(ev_config_);
	DXM_COMPONENT_LOG( DXM_COMPONENT_LOG_LEVEL_TRACE, "event_base_new ok.");

	// tv
	timeval tv;

	// ev token bucket cfg
	tv.tv_sec = 0;
	tv.tv_usec = 0;
	ev_t_bucket_cfg_ = ev_token_bucket_cfg_new(EV_RATE_LIMIT_MAX, EV_RATE_LIMIT_MAX, 1024, 1024, &tv);
	DXM_COMPONENT_LOG( DXM_COMPONENT_LOG_LEVEL_TRACE, "ev_token_bucket_cfg_new ok.");

	//	set an event
	tv.tv_sec = 1;
	tv.tv_usec = 0;
	ev_ = evtimer_new(ev_base_, defaultEventFunc, this);
	event_add(ev_, &tv);
	DXM_COMPONENT_LOG( DXM_COMPONENT_LOG_LEVEL_TRACE, "event_add timer ok.");
	
	// run loop callback
	pthread_create(&loop_thread_, 0, loopThreadStartFunc, this);
	DXM_COMPONENT_LOG( DXM_COMPONENT_LOG_LEVEL_TRACE, "main thread create ok.");

	//	start
	is_running_ = true;
	DXM_COMPONENT_LOG( DXM_COMPONENT_LOG_LEVEL_INFO, "Initialize Finish.");
	return true;
}
コード例 #16
0
ファイル: game_event.c プロジェクト: a1406/txgg
int game_event_init()
{
	int ret = 0;
	struct event_config *config = NULL;
//	struct event *event_signal1 = NULL;
//	struct event *event_signal2 = NULL;	
	
	event_set_log_callback(libevent_log);

	config = event_config_new();
	if (!config)
	{
		log4c_category_log(mycat, LOG4C_PRIORITY_ERROR, "%s %d: event_config_new failed[%d]", __FUNCTION__, __LINE__, errno);
		ret = -10;
		goto fail;
	}
	event_config_require_features(config, EV_FEATURE_ET | EV_FEATURE_O1 /*| EV_FEATURE_FDS*/);
	event_config_set_flag(config, EVENT_BASE_FLAG_NOLOCK | EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST);
	base = event_base_new_with_config(config);
	if (!base)
	{
		log4c_category_log(mycat, LOG4C_PRIORITY_ERROR, "%s %d: event_base_new_with_config failed[%d]", __FUNCTION__, __LINE__, errno);
		ret = -20;
		goto fail;
	}
/*
	event_signal1 = evsignal_new(base, SIGUSR1, cb_signal, NULL);
	if (!event_signal1) {
		log4c_category_log(mycat, LOG4C_PRIORITY_ERROR, "%s %d: evsignal_new failed[%d]", __FUNCTION__, __LINE__, errno);
		ret = -30;
		goto fail;
	}
	event_signal2 = evsignal_new(base, SIGUSR2, cb_signal, NULL);
	if (!event_signal2) {
		log4c_category_log(mycat, LOG4C_PRIORITY_ERROR, "%s %d: evsignal_new failed[%d]", __FUNCTION__, __LINE__, errno);
		ret = -30;
		goto fail;
	}
	
//	struct event event_signal, event_timer;
//	evsignal_assign(&event_signal, base, SIGUSR1, cb_signal, NULL);
//	evtimer_assign(&event_timer, base, cb_timer, NULL);
	evsignal_add(event_signal1, NULL);
	evsignal_add(event_signal2, NULL);	
*/	
	return (0);
	
fail:
/*	
	if (event_signal1) {
		event_free(event_signal1);
		event_signal1 = NULL;
	}
	if (event_signal2) {
		event_free(event_signal2);
		event_signal2 = NULL;
	}
*/	
	if (config) {
		event_config_free(config);
		config = NULL;
	}
	if (base) {
		event_base_free(base);
		base = NULL;
	}
	return (ret);
}
コード例 #17
0
ファイル: test-ratelim.c プロジェクト: diwakergupta/libevent
static int
test_ratelimiting(void)
{
	struct event_base *base;
	struct sockaddr_in sin;
	struct evconnlistener *listener;

	struct sockaddr_storage ss;
	ev_socklen_t slen;

	struct bufferevent **bevs;
	struct client_state *states;
	struct bufferevent_rate_limit_group *group = NULL;

	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;

	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);

	listener = evconnlistener_new_bind(base, echo_listenercb, base,
	    LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE, -1,
	    (struct sockaddr *)&sin, sizeof(sin));

	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;
		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));

	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);

	event_base_dispatch(base);

	ratelim_group = NULL; /* So no more responders get added */

	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);

	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;
}
コード例 #18
0
bool EventLoopL::Prepare()
{
	_DBG("EventLoopL::Prepare");

	if(!EventConfig_)
	{
		EventConfig_ = event_config_new();
	}

	if(!EventConfig_)
	{
		throwSystemError("event_config_new allocate fail!");
	}

	//event_config_avoid_method(EventConfig_, "select");//avoid select
	//event_config_avoid_method(EventConfig_, "poll");//avoid poll
	if(0 != event_config_require_features(EventConfig_, EV_FEATURE_O1))//EV_FEATURE_ET ?
	{
		_ERR("set event config feature fail!");
		return false;
	}

	if(0 != event_config_set_flag(EventConfig_, EVENT_BASE_FLAG_NOLOCK))
	{
		_ERR("set event config flag fail!");
		return false;
	}

	if(!EventBase_)
	{
		EventBase_ = event_base_new_with_config(EventConfig_);
	}

	if(!EventBase_)
	{
		throwSystemError("event_base_new_with_config allocate fail!");
		return false;
	}

	_DBG("Current used method : %s", event_base_get_method(EventBase_));

	for(auto &data : Datas_)
	{
		if(data)
		{
			std::shared_ptr<IO> io(data->io.lock());
			if(!io)
			{
				_WRN("This io %d is not exist!", io->Index());
				continue;
			}

			if(io->Index() < 0)
			{
				_ERR("This IO has been removed!");
				continue;
			}
			
			if(data->ev)
			{
				event_del(data->ev);
				event_free(data->ev);
				data->ev = NULL;
			}

			event* ev = event_new(EventBase_, io->Fd(), io->Condition(), CEventCallBack, (void*)&(data->fn));	
			_DBG("Add io %p(index : %d  fd : %d  cond : %d)", ev, io->Index(), io->Fd(), io->Condition());

			if(ev == NULL)
			{
				_ERR("event_new fail, index %d", io->Index());
				continue;
			}
			data->ev = ev;

			if(event_add(ev, NULL))
			{
				_ERR("event_add fail, index %d!", io->Index());
				continue;
			}
		}
	}

	int evtfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
	if (evtfd < 0)
	{
		_ERR("Get eventfd fail!");
		return false;
	}
	Wakeup_.reset(new IO(evtfd, EV_READ | EV_PERSIST));
	Wakeup_->SetCallback(std::bind(&EventLoopL::quitAsync, this, std::placeholders::_1));
	AddIO(Wakeup_);

	return true;
}