Ejemplo n.º 1
0
void *reactorThreadRun(void *arg)
{
    reactorThreadParam* param = (reactorThreadParam*)arg;
    aeServer* serv = param->serv;
    int thid = param->thid;
    aeEventLoop* el = aeCreateEventLoop( 1024 );
    serv->reactorThreads[thid].reactor.eventLoop = el;
 
    int ret,i;
	//每个线程都有workerNum个worker pipe
    for(  i = 0; i < serv->workerNum; i++ )
    {
        if ( aeCreateFileEvent( el,serv->workers[i].pipefd[0],
                     AE_READABLE,onMasterPipeReadable, thid  ) == -1 )
        {
            printf( "CreateFileEvent error fd "  );
            close(serv->workers[i].pipefd[0]);
        }
    }
    
    aeSetBeforeSleepProc( el ,initThreadOnLoopStart );
    aeMain( el );
	
    aeDeleteEventLoop( el );
    el = NULL;
}
Ejemplo n.º 2
0
int main(int argc, char **argv) {
    time_t start;

    initServerConfig();
    if (argc == 2) {
        resetServerSaveParams();
        loadServerConfig(argv[1]);
    } 

    if (server.daemonize) daemonize();
    initServer();
   
    linuxOvercommitMemoryWarning();
    start = time(NULL);
    if (server.appendonly) {
        loadAppendOnlyFile(server.appendfilename);
    } else {
        rdbLoad(server.dbfilename);
    }

    aeSetBeforeSleepProc(server.el,beforeSleep);
    aeMain(server.el);
    aeDeleteEventLoop(server.el);
   
    return 0;
}
Ejemplo n.º 3
0
int main(int argc, char** argv) {
    signal(SIGABRT, &sighandler);
    signal(SIGTERM, &sighandler);
    signal(SIGINT, &sighandler);

    initServer();

    aeEventLoop* eventLoop = aeCreateEventLoop(server.max_process_client + SHTTPSVR_EVENTLOOP_FDSET_INCR);
    server.el = eventLoop;

    int listen_socket = anetTcpServer(NULL, 80, NULL, server.tcp_backlog);
    anetNonBlock(NULL, listen_socket);

    if (listen_socket > 0
        && AE_ERR == aeCreateFileEvent(eventLoop, listen_socket, AE_READABLE, tAcceptProc, NULL)) {
        ERRLOG("aeCreateFileEvent error!");
        exit(1);
    }

    aeSetBeforeSleepProc(eventLoop, tBeforeSleepProc);
    initTimeEvent(eventLoop);
    aeMain(eventLoop);
    aeDeleteEventLoop(eventLoop);
    return 0;
}
Ejemplo n.º 4
0
int main()
{

	printf("Start\n");

	signal(SIGINT, StopServer);

	//初始化网络事件循环
	g_event_loop = aeCreateEventLoop(1024*10);

	//设置监听事件
	int fd = anetTcpServer(g_err_string, PORT, NULL);
	if( ANET_ERR == fd )
		fprintf(stderr, "Open port %d error: %s\n", PORT, g_err_string);
	if( aeCreateFileEvent(g_event_loop, fd, AE_READABLE, AcceptTcpHandler, NULL) == AE_ERR )
		fprintf(stderr, "Unrecoverable error creating server.ipfd file event.");

	//设置定时事件
	aeCreateTimeEvent(g_event_loop, 1, PrintTimer, NULL, NULL);

	//开启事件循环
	aeMain(g_event_loop);

	//删除事件循环
	aeDeleteEventLoop(g_event_loop);

	printf("End\n");
	return 0;
}
Ejemplo n.º 5
0
 void GatewayDataMgr::loopThread() {
     LOG(INFO)<<"start loopThread";
     aeMain(mPtEventLoop);
     aeDeleteEventLoop(mPtEventLoop);
     LOG(INFO)<<"end loopThread";
     return;
 }
Ejemplo n.º 6
0
void *reactorThreadRun( void *arg )
{
	reactorThreadParam *param = (reactorThreadParam *) arg;
	appnetServer *serv = param->serv;
	int thid = param->thid;
	aeEventLoop *el = aeCreateEventLoop( MAX_EVENT );
	serv->reactor_threads[thid].reactor.event_loop = el;
	serv->reactor_threads[thid].hh = (httpHeader *) malloc( sizeof(httpHeader) );
	serv->reactor_threads[thid].hs = (handshake *) malloc( sizeof(handshake) );
	
	int ret,i,index;
	for (i = 0; i < serv->worker_num + serv->task_worker_num; i++)
	{
		index = i * serv->reactor_num + thid;
		
		if (aeCreateFileEvent( el , serv->worker_pipes[index].pipefd[0] , AE_READABLE ,
				onMasterPipeReadable , thid ) == -1)
		{
			
			printf( "CreateFileEvent error fd " );
			close( serv->worker_pipes[index].pipefd[0] );
		}
	}
	
	aeSetBeforeSleepProc( el , initThreadOnLoopStart );
	aeMain( el );
	aeDeleteEventLoop( el );
	
	free( serv->reactor_threads[thid].hh );
	free( serv->reactor_threads[thid].hs );
	el = NULL;
}
Ejemplo n.º 7
0
int main(int argc, char **argv)
{
	init_server_config();

	aeMain(g_server.el);
	
	return 0;
}
Ejemplo n.º 8
0
static void *
master_thread_run(void *args)
{    
    /* vire master run */
    aeMain(master.vel.el);

    return NULL;
}
Ejemplo n.º 9
0
static void *vrt_dispatch_data_thread_run(void *args)
{
    dispatch_data_thread *ddt = args;
    srand(vrt_usec_now()^(int)pthread_self());

    aeMain(ddt->el);
    
    return NULL;
}
Ejemplo n.º 10
0
int run_storage_service()
{
	aeSetBeforeSleepProc(g_storage_service.eventLoop,NULL);
	aeMain(g_storage_service.eventLoop);
	aeDeleteEventLoop(g_storage_service.eventLoop);
	
	close(g_storage_service.sockfd);
	return 0;
}
Ejemplo n.º 11
0
int main(int argc, char **argv)
{
	int ret;
#if _LINUX_
	aeEventLoop *loop;
#endif

	SSRC = getpid();
	IPCAM_DEV = create_empty_ipcam_link();

#if !_LINUX_
	pthread_t deal_msg_pid;
	pthread_t deal_console_input_pid;
	pthread_t maintain_ipcam_link_pid;

	ret = pthread_create(&deal_console_input_pid, 0, 
				deal_console_input, NULL);
	if (ret) {
		debug_print("pthread_create failed");
		exit(errno);
	}

	ret = pthread_create(&deal_msg_pid, 0, 
				recv_msg_from_ipcam, NULL);
	if (ret) {
		debug_print("pthread_create failed");
		exit(errno);
	}

	ret = pthread_create(&maintain_ipcam_link_pid, 0, 
				maintain_ipcam_link, NULL);
	if (ret) {
		debug_print("pthread_create failed");
		exit(errno);
	}

	pthread_join(maintain_ipcam_link_pid, NULL);
	pthread_join(deal_msg_pid, NULL);
	pthread_join(deal_console_input_pid, NULL);
#else
	int pc_server_fd;

	pc_server_fd = init_server_UDP_fd(PC_SERVER_PORT, "0.0.0.0");
	assert(pc_server_fd > 0);
	loop = aeCreateEventLoop();
	fprintf(stdout, "\033[01;32mipc_shell> \033[0m");
	fflush(stdout);
	ret = aeCreateFileEvent(loop, STDIN_FILENO, AE_READABLE, dealcmd, NULL);
	assert(ret != AE_ERR);
	ret = aeCreateFileEvent(loop, pc_server_fd, AE_READABLE, dealnet, NULL);
	assert(ret != AE_ERR);
	aeCreateTimeEvent(loop, CHECK_IPCAM_CYCLE * 1000, watch_ipcam_link_clear, NULL, NULL);
	aeMain(loop);
#endif
	return 0;
}
Ejemplo n.º 12
0
int main(int argc, char** argv)
{
	aeEventLoop *el = aeCreateEventLoop(100);
	if(aeCreateTimeEvent(el, 1000, timerEvent, NULL, NULL) == AE_ERR) {
		printf("Can't create the serverCron time event.");
		return 1;
	}
	aeMain(el);
	aeDeleteEventLoop(el);
}
Ejemplo n.º 13
0
void runMainReactor( appnetServer *serv )
{
	int res;
	res = aeCreateFileEvent( serv->main_reactor->event_loop , serv->listenfd ,
			AE_READABLE , onAcceptEvent , NULL );
	
	printf( "Master Run pid=%d and listen socketfd=%d is ok? [%d]\n" , getpid() ,
			serv->listenfd , res == 0 );
	printf( "Server start ok ,You can exit program by Ctrl+C !!! \n" );
	
	aeMain( serv->main_reactor->event_loop );
	aeDeleteEventLoop( serv->main_reactor->event_loop );
}
Ejemplo n.º 14
0
void forkWorker(aeEventLoop *el, int server_sk){
    void *clientData;
    clientData = NULL;
    int pid = fork();
    if(pid < 0){
        perror("fork");
    }
    else if(pid == 0){
        info("fork");
        aeCreateFileEvent(el, server_sk, AE_READABLE, doAccept, clientData);
        aeMain(el);
    }
}
Ejemplo n.º 15
0
int main(int argv, char *argc){
	initServerConfig();
	initServer();

    if (server.ipfd > 0)
        redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
    if (server.sofd > 0)
        redisLog(REDIS_NOTICE,"The server is now ready to accept connections at %s", server.unixsocket);
//    aeSetBeforeSleepProc(server.el,beforeSleep);
    aeMain(server.el);
    aeDeleteEventLoop(server.el);

	return EXIT_SUCCESS;
}
Ejemplo n.º 16
0
static void benchmark(char *title, char *cmd, int len) {
    client c;

    config.title = title;
    config.requests_issued = 0;
    config.requests_finished = 0;

    c = createClient(cmd,len,NULL);
    createMissingClients(c);

    config.start = mstime();
    aeMain(config.el);
    config.totlatency = mstime()-config.start;

    showLatencyReport();
    freeAllClients();
}
Ejemplo n.º 17
0
/* 启动网络
*/
static void* _NTInit(void* _v) {
    pthread_mutex_lock(&g_rootThreadMutex);

    int listenPort;
    struct configOption *confOpt;
    char tmpstr[TMPSTR_SIZE] = {""};

    confOpt = configGet(g_conf, "net_server", "port");

    if (NULL != confOpt) {

        if (confOpt->valueLen > TMPSTR_SIZE) {
            trvExit(0, "监听端口太大");
        }

        memcpy(tmpstr, confOpt->value, confOpt->valueLen);
        tmpstr[confOpt->valueLen] = 0;
        listenPort = atoi(tmpstr);
    }
    else listenPort = -1; /* 输入一个不正常的监听端口,意味着不监听 */


    if (ERRNO_ERR == NTInit(listenPort)) {
        trvExit(0, "初始化网络失败");
    }

    /*
    if(aeCreateTimeEvent(g_server.el, 1, serverCron, NULL, NULL) == AE_ERR) {
        trvLogE("Can't create the serverCron time event.");
        exit(1);
    }
    */


    aeSetBeforeSleepProc(g_server.el, beforeSleep);

    pthread_mutex_unlock(&g_rootThreadMutex);

    pthread_cond_signal(&g_rootThreadCond);

    aeMain(g_server.el);
    aeDeleteEventLoop(g_server.el);

    return NULL;
}
Ejemplo n.º 18
0
int main(int argc, char **argv) {
	server.maxclients = TEST_MAX_CLIENT;
	server.el = aeCreateEventLoop(server.maxclients + 32+96);
	strcpy(server.bindaddr, "127.0.0.1");
	server.port = 8888;
	server.tcpkeepalive = 0;
	server.clients = listCreate();
	server.sfd = anetTcpServer(server.neterr, server.port, server.bindaddr, 16);
	if (server.sfd == ANET_ERR) {
		fprintf(stderr, "Creating Server TCP listening socket %s:%d\t%s", server.bindaddr ? server.bindaddr : "*", server.port, server.neterr);
		exit(EXIT_FAILURE);
	}
	if (aeCreateFileEvent(server.el, server.sfd, AE_READABLE, acceptTcpHandler, NULL)) {
		fprintf(stderr, "Unrecoverable error creating %d file event", server.sfd);
		exit(EXIT_FAILURE);
	}
	aeMain(server.el);
}
Ejemplo n.º 19
0
static void *
worker_thread (void *arg)
{
  workerArg *wa = (workerArg *) arg;
  int ret;
  int flags;
  workerState ws;

  // set read flag to be nonblock 
  flags = fcntl (wa->rfd, F_GETFL, 0);
  assert (flags != -1);
  ret = fcntl (wa->rfd, F_SETFL, flags | O_NONBLOCK);
  assert (ret != -1);

  init_worker_state (&ws);
  ws.arg = wa;
  ws.size = wa->size;
  ws.tps = wa->tps;
  ws.el = aeCreateEventLoop (2048);
  assert (ws.el != NULL);

  ret =
    aeCreateFileEvent (ws.el, ws.arg->rfd, AE_READABLE, command_handler, &ws);
  assert (ret != AE_ERR);

  ws.teid = aeCreateTimeEvent (ws.el, 1, worker_cron, &ws, NULL);
  assert (ws.teid != -1LL);

  aeMain (ws.el);

  sb_clear (&ws.cin);
  sb_clear (&ws.in);
  sb_clear (&ws.out);
  if (ws.teid != -1LL)
    {
      aeDeleteTimeEvent (ws.el, ws.teid);
    }
  if (ws.el != NULL)
    {
      aeDeleteEventLoop (ws.el);
    }
  return NULL;
}
Ejemplo n.º 20
0
int main (int argc, char **argv) {
    signal(SIGPIPE, SIG_IGN);

    redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);
    if (c->err) {
        /* Let *c leak for now... */
        printf("Error: %s\n", c->errstr);
        return 1;
    }

    loop = aeCreateEventLoop();
    redisAeAttach(loop, c);
    redisAsyncSetConnectCallback(c,connectCallback);
    redisAsyncSetDisconnectCallback(c,disconnectCallback);
    redisAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc-1], strlen(argv[argc-1]));
    redisAsyncCommand(c, getCallback, (char*)"end-1", "GET key");
    aeMain(loop);
    return 0;
}
Ejemplo n.º 21
0
int main(int argc, char **argv){
	setbuf(stdout,NULL);
	printf("Start\n");

	signal(SIGINT, StopServer);

	//初始化网络事件循环
	g_event_loop = aeCreateEventLoop(1024*10);
	
	long int start_time = getCurrentTime();
	/*//设置监听事件
	int i;
	for(i=0; i<10; i++){
		int fd = anetTcpConnect(NULL, argv[1], atoi(argv[2]));
		if( ANET_ERR == fd ){
			fprintf(stderr, "connect error: %s\n", PORT, NULL);
		}
		if(anetNonBlock(NULL, fd) == ANET_ERR){
			fprintf(stderr, "set nonblock error: %d\n", fd);
		}
		
		
		WriteHandler(g_event_loop, fd, NULL, 0);
	}*/

	
	//设置定时事件
	aeCreateTimeEvent(g_event_loop, 5000, PrintTimer, NULL, NULL);

	//开启事件循环
	aeMain(g_event_loop);

	//删除事件循环
	aeDeleteEventLoop(g_event_loop);

	/*printf("End\n");
	long int end_time = getCurrentTime();
	double elapsed = (double)(end_time-start_time);
	printf("test_time : %0.2f s\n", elapsed/1000);
	printf("total_req : %d\n", total_req);
	printf("total_res : %d\n", total_res);*/
	return 0;
}
Ejemplo n.º 22
0
int main(int argc,char**argv)
{
    int i,listen_fd;
    struct sigaction sig_action;

    ParseArgs(argc,argv);

    //daemonize();

    sig_action.sa_handler=SignalHandler;
    sig_action.sa_flags=SA_RESTART;
    sigemptyset(&sig_action.sa_mask);
    sigaction(SIGINT,&sig_action,NULL);
    sigaction(SIGTERM,&sig_action,NULL);
    sigaction(SIGPIPE,&sig_action,NULL);


    if((policy->listen.addr==NULL)||!strcmp(policy->listen.addr,"any")){
	free(policy->listen.addr);
	policy->listen.addr=strdup("0.0.0.0");
    }else if (!strcmp(policy->listen.addr,"localhost")){
	free(policy->listen.addr);
	policy->listen.addr=strdup("127.0.0.1");
    }

    listen_fd=anetTcpServer(anet_error,policy->listen.port,policy->listen.addr);
    el=aeCreateEventLoop(1024);

    if(listen_fd<0||aeCreateFileEvent(el,listen_fd,AE_READABLE,Proxy_AcceptTcpHandler,NULL)==AE_ERR){
	LogFatal("listen failed:%s",strerror(errno));
    }

    LogInfo("listening on:%s:%d",(policy->listen.addr?policy->listen.addr:"any"),policy->listen.port);
    for(i=0;i<policy->nhost;i++){
	LogInfo("proxy to %s:%d",policy->hosts[i].addr,policy->hosts[i].port);
    }

    aeMain(el);
    aeDeleteEventLoop(el);
    FreePolicy(policy);
    return 0;
}
Ejemplo n.º 23
0
int main(int argc, char **argv)
{
	(void) argc;
	(void) argv;

	_svr.bindaddr = HOST;
	_svr.port = PORT;

	_svr.db = silokatana_open();
	_svr.el = aeCreateEventLoop(11024);
	_svr.fd = anetTcpServer(_svr.neterr, _svr.port, _svr.bindaddr);
	if (_svr.fd == ANET_ERR) {
		__PANIC("openning port error #%d:%s", _svr.port, _svr.neterr);
		exit(1);
	}

	if (anetNonBlock(_svr.neterr, _svr.fd) == ANET_ERR) {
		__ERROR("set nonblock #%s",_svr.neterr);
		exit(1);
	}

	aeCreateTimeEvent(_svr.el, 3000, server_cron, NULL, NULL);

	if (aeCreateFileEvent(_svr.el, _svr.fd, AE_READABLE, accept_handler, NULL) == AE_ERR) 
		__ERROR("creating file event");

	__INFO("siloserver starting, port:%d, pid:%d", PORT, (long)getpid());
	printf("%s", _ascii_logo);

	aeMain(_svr.el);

	__ERROR("oops,exit");
	aeDeleteEventLoop(_svr.el);
	silokatana_close(_svr.db);

	return 1;
}
Ejemplo n.º 24
0
int main(int argc, const char **argv) {
    int i;
    char *data, *cmd;
    int len;

    client c;

    signal(SIGHUP, SIG_IGN);
    signal(SIGPIPE, SIG_IGN);

    config.numclients = 50;
    config.requests = 10000;
    config.liveclients = 0;
    config.el = aeCreateEventLoop(1024*10);
    aeCreateTimeEvent(config.el,1,showThroughput,NULL,NULL);
    config.keepalive = 1;
    config.datasize = 3;
    config.pipeline = 1;
    config.randomkeys = 0;
    config.randomkeys_keyspacelen = 0;
    config.quiet = 0;
    config.csv = 0;
    config.loop = 0;
    config.idlemode = 0;
    config.latency = NULL;
    config.clients = listCreate();
    config.hostip = "127.0.0.1";
    config.hostport = 6379;
    config.hostsocket = NULL;
    config.tests = NULL;
    config.dbnum = 0;

    i = parseOptions(argc,argv);
    argc -= i;
    argv += i;

//    printf ("SET PAGE POOL SIZE\n");
//    set_page_pool_size(config.requests);
    config.latency = zmalloc(sizeof(long long)*config.requests);

    if (config.keepalive == 0) {
        printf("WARNING: keepalive disabled, you probably need 'echo 1 > /proc/sys/net/ipv4/tcp_tw_reuse' for Linux and 'sudo sysctl -w net.inet.tcp.msl=1000' for Mac OS X in order to use a lot of clients/requests\n");
    }

    if (config.idlemode) {
        printf("Creating %d idle connections and waiting forever (Ctrl+C when done)\n", config.numclients);
        c = createClient("",0,NULL); /* will never receive a reply */
        createMissingClients(c);
        aeMain(config.el);
        /* and will wait for every */
    }

    /* Run benchmark with command in the remainder of the arguments. */
    if (argc) {
        sds title = sdsnew(argv[0]);
        for (i = 1; i < argc; i++) {
            title = sdscatlen(title, " ", 1);
            title = sdscatlen(title, (char*)argv[i], strlen(argv[i]));
        }

        do {
            len = redisFormatCommandArgv(&cmd,argc,argv,NULL);
            benchmark(title,cmd,len);
            free(cmd);
        } while(config.loop);

        return 0;
    }

    /* Run default benchmark suite. */
    do {
        data = zmalloc(config.datasize+1);
        memset(data,'x',config.datasize);
        data[config.datasize] = '\0';

        if (test_is_selected("ping_inline") || test_is_selected("ping"))
            benchmark("PING_INLINE","PING\r\n",6);

        if (test_is_selected("ping_mbulk") || test_is_selected("ping")) {
            len = redisFormatCommand(&cmd,"PING");
            benchmark("PING_BULK",cmd,len);
            free(cmd);
        }

        if (test_is_selected("set")) {
            len = redisFormatCommand(&cmd,"SET key:__rand_int__ %s",data);
            benchmark("SET",cmd,len);
            free(cmd);
        }

        if (test_is_selected("get")) {
            len = redisFormatCommand(&cmd,"GET key:__rand_int__");
            benchmark("GET",cmd,len);
            free(cmd);
        }

        if (test_is_selected("incr")) {
            len = redisFormatCommand(&cmd,"INCR counter:__rand_int__");
            benchmark("INCR",cmd,len);
            free(cmd);
        }

        if (test_is_selected("lpush")) {
            len = redisFormatCommand(&cmd,"LPUSH mylist %s",data);
            benchmark("LPUSH",cmd,len);
            free(cmd);
        }

        if (test_is_selected("lpop")) {
            len = redisFormatCommand(&cmd,"LPOP mylist");
            benchmark("LPOP",cmd,len);
            free(cmd);
        }

        if (test_is_selected("sadd")) {
            len = redisFormatCommand(&cmd,
                "SADD myset element:__rand_int__");
            benchmark("SADD",cmd,len);
            free(cmd);
        }

        if (test_is_selected("spop")) {
            len = redisFormatCommand(&cmd,"SPOP myset");
            benchmark("SPOP",cmd,len);
            free(cmd);
        }

        if (test_is_selected("lrange") ||
            test_is_selected("lrange_100") ||
            test_is_selected("lrange_300") ||
            test_is_selected("lrange_500") ||
            test_is_selected("lrange_600"))
        {
            len = redisFormatCommand(&cmd,"LPUSH mylist %s",data);
            benchmark("LPUSH (needed to benchmark LRANGE)",cmd,len);
            free(cmd);
        }

        if (test_is_selected("lrange") || test_is_selected("lrange_100")) {
            len = redisFormatCommand(&cmd,"LRANGE mylist 0 99");
            benchmark("LRANGE_100 (first 100 elements)",cmd,len);
            free(cmd);
        }

        if (test_is_selected("lrange") || test_is_selected("lrange_300")) {
            len = redisFormatCommand(&cmd,"LRANGE mylist 0 299");
            benchmark("LRANGE_300 (first 300 elements)",cmd,len);
            free(cmd);
        }

        if (test_is_selected("lrange") || test_is_selected("lrange_500")) {
            len = redisFormatCommand(&cmd,"LRANGE mylist 0 449");
            benchmark("LRANGE_500 (first 450 elements)",cmd,len);
            free(cmd);
        }

        if (test_is_selected("lrange") || test_is_selected("lrange_600")) {
            len = redisFormatCommand(&cmd,"LRANGE mylist 0 599");
            benchmark("LRANGE_600 (first 600 elements)",cmd,len);
            free(cmd);
        }

        if (test_is_selected("mset")) {
            const char *argv[21];
            argv[0] = "MSET";
            for (i = 1; i < 21; i += 2) {
                argv[i] = "key:__rand_int__";
                argv[i+1] = data;
            }
            len = redisFormatCommandArgv(&cmd,21,argv,NULL);
            benchmark("MSET (10 keys)",cmd,len);
            free(cmd);
        }

        if (!config.csv) printf("\n");
    } while(config.loop);

    return 0;
}
Ejemplo n.º 25
0
void * server_worker(void* arg)
{ 
    aeMain(loop);
    return NULL;
}
Ejemplo n.º 26
0
int main(int argc, char **argv) {
    struct addrinfo *addrs, *addr;
    char *host = "127.0.0.1";
    char *port = "1337";
    int rc;
    // for checking that the server's up
    char poke[SHA_LENGTH * 2];
    tinymt64_t rando;

    if (parse_args(&cfg, &host, &port, argc, argv)) {
        usage();
        exit(1);
    }

    struct addrinfo hints = {
        .ai_family   = AF_UNSPEC,
        .ai_socktype = SOCK_STREAM
    };

    if ((rc = getaddrinfo(host, port, &hints, &addrs)) != 0) {
        const char *msg = gai_strerror(rc);
        fprintf(stderr, "unable to resolve %s:%s: %s\n", host, port, msg);
        exit(1);
    }

    for (addr = addrs; addr != NULL; addr = addr->ai_next) {
        int fd = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
        if (fd == -1) continue;
        rc = connect(fd, addr->ai_addr, addr->ai_addrlen);
        tinymt64_init(&rando, time_us());
        random_hash(&rando, poke);
        if (rc == 0 && write(fd, poke, SHA_LENGTH * 2) == SHA_LENGTH * 2) {
            read(fd, poke, SHA_LENGTH * 2);
            close(fd);
            break;
        }
        close(fd);
    }

    if (addr == NULL) {
        char *msg = strerror(errno);
        fprintf(stderr, "unable to connect to %s:%s: %s\n", host, port, msg);
        exit(1);
    }

    signal(SIGPIPE, SIG_IGN);
    signal(SIGINT,  SIG_IGN);
    cfg.addr = *addr;

    pthread_mutex_init(&statistics.mutex, NULL);
    statistics.latency  = stats_alloc(SAMPLES);
    statistics.requests = stats_alloc(SAMPLES);

    thread *threads = zcalloc(cfg.threads * sizeof(thread));
    uint64_t connections = cfg.connections / cfg.threads;
    uint64_t stop_at     = time_us() + (cfg.duration * 1000000);

    for (uint64_t i = 0; i < cfg.threads; i++) {
        thread *t = &threads[i];
        t->connections = connections;
        t->stop_at     = stop_at;

        if (pthread_create(&t->thread, NULL, &thread_main, t)) {
            char *msg = strerror(errno);
            fprintf(stderr, "unable to create thread %"PRIu64" %s\n", i, msg);
            exit(2);
        }
    }

    struct sigaction sa = {
        .sa_handler = handler,
        .sa_flags   = 0,
    };
    sigfillset(&sa.sa_mask);
    sigaction(SIGINT, &sa, NULL);

    char *time = format_time_s(cfg.duration);
    printf("Running %s test @ %s:%s\n", time, host, port);
    printf("  %"PRIu64" threads and %"PRIu64" connections\n", cfg.threads, cfg.connections);

    uint64_t start    = time_us();
    uint64_t complete = 0;
    uint64_t bytes    = 0;
    errors errors     = { 0 };

    for (uint64_t i = 0; i < cfg.threads; i++) {
        thread *t = &threads[i];
        pthread_join(t->thread, NULL);

        complete += t->complete;
        bytes    += t->bytes;

        errors.connect   += t->errors.connect;
        errors.handshake += t->errors.handshake;
        errors.read      += t->errors.read;
        errors.validate  += t->errors.validate;
        errors.write     += t->errors.write;
        errors.timeout   += t->errors.timeout;
    }

    uint64_t runtime_us = time_us() - start;
    long double runtime_s   = runtime_us / 1000000.0;
    long double req_per_s   = complete   / runtime_s;
    long double bytes_per_s = bytes      / runtime_s;

    print_stats_header();
    print_stats("Latency", statistics.latency, format_time_us);
    print_stats("Req/Sec", statistics.requests, format_metric);
    if (cfg.latency) print_stats_latency(statistics.latency);

    char *runtime_msg = format_time_us(runtime_us);

    printf("  %"PRIu64" requests in %s, %sB read\n", complete, runtime_msg, format_binary(bytes));
    if (errors.connect || errors.read || errors.write || errors.timeout) {
        printf("  Socket errors: connect %d, read %d, write %d, timeout %d\n",
               errors.connect, errors.read, errors.write, errors.timeout);
    }

    if (errors.handshake) {
        printf("  Bad handshakes from server: %d\n", errors.handshake);
    }

    if (errors.validate) {
        printf("  %d proofs failed verification.\n", errors.validate);
    }

    printf("Requests/sec: %9.2Lf\n", req_per_s);
    printf("Transfer/sec: %10sB\n", format_binary(bytes_per_s));

    return 0;
}

void *thread_main(void *arg) {
    thread *thread = arg;

    aeEventLoop *loop = aeCreateEventLoop(10 + cfg.connections * 3);
    thread->cs   = zmalloc(thread->connections * sizeof(connection));
    thread->loop = loop;
    tinymt64_init(&thread->rand, time_us());
    thread->latency = stats_alloc(100000);

    connection *c = thread->cs;

    for (uint64_t i = 0; i < thread->connections; i++, c++) {
        c->thread = thread;
        random_hash(&thread->rand, c->hash);
        connect_socket(thread, c);
    }

    aeCreateTimeEvent(loop, CALIBRATE_DELAY_MS, calibrate, thread, NULL);
    aeCreateTimeEvent(loop, TIMEOUT_INTERVAL_MS, check_timeouts, thread, NULL);

    thread->start = time_us();
    aeMain(loop);

    aeDeleteEventLoop(loop);
    zfree(thread->cs);

    uint64_t max = thread->latency->max;
    stats_free(thread->latency);

    pthread_mutex_lock(&statistics.mutex);
    for (uint64_t i = 0; i < thread->missed; i++) {
        stats_record(statistics.latency, max);
    }
    pthread_mutex_unlock(&statistics.mutex);

    return NULL;
}
void easysocketbenchmark::startloop(){
	aeMain(this->g_event_loop);
}
Ejemplo n.º 28
0
int main(int argc, const char **argv) {
    int i;
    char *data, *cmd;
    int len;

    client c;

#ifdef _WIN32
    w32initWinSock();
#endif

    signal(SIGHUP, SIG_IGN);
    signal(SIGPIPE, SIG_IGN);

    config.numclients = 50;
    config.requests = 10000;
    config.liveclients = 0;
    config.el = aeCreateEventLoop();
    aeCreateTimeEvent(config.el,1,showThroughput,NULL,NULL);
    config.keepalive = 1;
    config.datasize = 3;
    config.randomkeys = 0;
    config.randomkeys_keyspacelen = 0;
    config.quiet = 0;
    config.loop = 0;
    config.idlemode = 0;
    config.latency = NULL;
    config.clients = listCreate();
    config.hostip = "127.0.0.1";
    config.hostport = 6379;
    config.hostsocket = NULL;

    i = parseOptions(argc,argv);
    argc -= i;
    argv += i;

    config.latency = zmalloc(sizeof(long long)*config.requests);

    if (config.keepalive == 0) {
        printf("WARNING: keepalive disabled, you probably need 'echo 1 > /proc/sys/net/ipv4/tcp_tw_reuse' for Linux and 'sudo sysctl -w net.inet.tcp.msl=1000' for Mac OS X in order to use a lot of clients/requests\n");
    }

    if (config.idlemode) {
        printf("Creating %d idle connections and waiting forever (Ctrl+C when done)\n", config.numclients);
        c = createClient("",0); /* will never receive a reply */
        createMissingClients(c);
        aeMain(config.el);
        /* and will wait for every */
    }

    /* Run benchmark with command in the remainder of the arguments. */
    if (argc) {
        sds title = sdsnew(argv[0]);
        for (i = 1; i < argc; i++) {
            title = sdscatlen(title, " ", 1);
            title = sdscatlen(title, (char*)argv[i], strlen(argv[i]));
        }

        do {
            len = redisFormatCommandArgv(&cmd,argc,argv,NULL);
            benchmark(title,cmd,len);
            free(cmd);
        } while(config.loop);

        return 0;
    }

    /* Run default benchmark suite. */
    do {
        data = zmalloc(config.datasize+1);
        memset(data,'x',config.datasize);
        data[config.datasize] = '\0';

        benchmark("PING (inline)","PING\r\n",6);

        len = redisFormatCommand(&cmd,"PING");
        benchmark("PING",cmd,len);
        free(cmd);

        const char *argv[21];
        argv[0] = "MSET";
        for (i = 1; i < 21; i += 2) {
            argv[i] = "foo:rand:000000000000";
            argv[i+1] = data;
        }
        len = redisFormatCommandArgv(&cmd,21,argv,NULL);
        benchmark("MSET (10 keys)",cmd,len);
        free(cmd);

        len = redisFormatCommand(&cmd,"SET foo:rand:000000000000 %s",data);
        benchmark("SET",cmd,len);
        free(cmd);

        len = redisFormatCommand(&cmd,"GET foo:rand:000000000000");
        benchmark("GET",cmd,len);
        free(cmd);

        len = redisFormatCommand(&cmd,"INCR counter:rand:000000000000");
        benchmark("INCR",cmd,len);
        free(cmd);

        len = redisFormatCommand(&cmd,"LPUSH mylist %s",data);
        benchmark("LPUSH",cmd,len);
        free(cmd);

        len = redisFormatCommand(&cmd,"LPOP mylist");
        benchmark("LPOP",cmd,len);
        free(cmd);

        len = redisFormatCommand(&cmd,"SADD myset counter:rand:000000000000");
        benchmark("SADD",cmd,len);
        free(cmd);

        len = redisFormatCommand(&cmd,"SPOP myset");
        benchmark("SPOP",cmd,len);
        free(cmd);

        len = redisFormatCommand(&cmd,"LPUSH mylist %s",data);
        benchmark("LPUSH (again, in order to bench LRANGE)",cmd,len);
        free(cmd);

        len = redisFormatCommand(&cmd,"LRANGE mylist 0 99");
        benchmark("LRANGE (first 100 elements)",cmd,len);
        free(cmd);

        len = redisFormatCommand(&cmd,"LRANGE mylist 0 299");
        benchmark("LRANGE (first 300 elements)",cmd,len);
        free(cmd);

        len = redisFormatCommand(&cmd,"LRANGE mylist 0 449");
        benchmark("LRANGE (first 450 elements)",cmd,len);
        free(cmd);

        len = redisFormatCommand(&cmd,"LRANGE mylist 0 599");
        benchmark("LRANGE (first 600 elements)",cmd,len);
        free(cmd);

        printf("\n");
    } while(config.loop);

#ifdef _WIN32
    WSACleanup();
#endif
    return 0;
}
Ejemplo n.º 29
0
static void* run(void *ud) {
	aeMain(M->eventloop);
	return NULL;
}
Ejemplo n.º 30
0
int main(int argc, char **argv)
{
    int c;
    struct rlimit rlim;
    struct rlimit rlim_new;
    struct sigaction sa;
    
    mx_init_main();
    
    while ((c = getopt(argc, argv, "p:L:dc:vh")) != -1) {
        switch (c) {
        case 'v':
            mx_version();
            exit(0);
        case 'h':
            mx_usage();
            exit(0);
        case 'd':
            mx_daemon->daemon_mode = 1;
            break;
        case 'p':
            mx_daemon->port = atoi(optarg);
            break;
        case 'L':
            mx_daemon->log_file = strdup(optarg);
            break;
        case 'c':
            mx_daemon->conf_file = strdup(optarg);
            break;
        default:
            exit(-1);
        }
    }
    
    if (getrlimit(RLIMIT_CORE, &rlim)==0) {
        rlim_new.rlim_cur = rlim_new.rlim_max = RLIM_INFINITY;
        if (setrlimit(RLIMIT_CORE, &rlim_new)!=0) {
            rlim_new.rlim_cur = rlim_new.rlim_max = rlim.rlim_max;
            (void) setrlimit(RLIMIT_CORE, &rlim_new);
        }
    }

    if ((getrlimit(RLIMIT_CORE, &rlim)!=0) || rlim.rlim_cur==0) {
        fprintf(stderr, "[failed] unable ensure corefile creation.\n");
        exit(-1);
    }
    
    if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
        fprintf(stderr, "[failed] unable getrlimit number of files.\n");
        exit(-1);
    } else {
        int maxfiles = 1024;
        if (rlim.rlim_cur < maxfiles)
            rlim.rlim_cur = maxfiles + 3;
        if (rlim.rlim_max < rlim.rlim_cur)
            rlim.rlim_max = rlim.rlim_cur;
        if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
            fprintf(stderr, "[failed] unable set rlimit for open files "
                "Try running as root or requesting smaller maxconns value.\n");
            exit(-1);
        }
    }
    
    sa.sa_handler = SIG_IGN;
    sa.sa_flags = 0;
    if (sigemptyset(&sa.sa_mask) == -1 || sigaction(SIGPIPE, &sa, 0) == -1) {
        fprintf(stderr, "[failed] unable ignore SIGPIPE.\n");
        exit(-1);
    }
    
    if (mx_daemon->conf_file)
        mx_config_read_file(mx_daemon->conf_file); /* read configure file */
    else
        fprintf(stderr, "[notice] not found configure file and use default setting.\n");
    if (mx_daemon->daemon_mode)
        mx_daemonize();
    mx_init_daemon();
    mx_load_queue();  /* load queues from disk */
    aeMain(mx_daemon->event);

    return 0;
}