示例#1
0
int main(int argc, char* argv[])
{
    int id = 0;
    if (argc >= 2)
    {
        id = atoi(argv[1]);
    }

    int i=0;
    for (;i<argc; i++)
    {
        if (strcmp(argv[i], "-d") == 0)
        {
            init_daemon();
            break;
        }
    }

    server_start(id);

    while (1)
    {
        sleep(60);
    }

    server_shutdown();

    return 0;
}
示例#2
0
文件: app.c 项目: rzel/dim3
void app_end(void)
{
	if (server.map_open) map_end();
	if (server.game_open) game_end();
	
		// shut down app
		
	console_add_system("Closing App");
	
		// shutdown view
		
	if (!app.dedicated_host) view_shutdown();
	
		// physics ray tracing
		
	ray_trace_shutdown();

		// shutdown server
		
	server_shutdown();
	
		// OS network shutdown
		
	net_shutdown();
}
/**
 * Frees the ring structure and its added nodes.
 */
void
ch_free(ch_ring *ring)
{
	ch_ring_entry *deletes = NULL;
	ch_ring_entry *w = NULL;

	for (; ring->entries != NULL; ring->entries = ring->entries->next) {
		server_shutdown(ring->entries->server);

		if (ring->entries->malloced) {
			if (deletes == NULL) {
				w = deletes = ring->entries;
			} else {
				w = w->next = ring->entries;
			}
		}
	}

	assert(w != NULL);
	w->next = NULL;
	while (deletes != NULL) {
		w = deletes->next;
		free(deletes);
		deletes = w;
	}

	free(ring);
}
示例#4
0
文件: distr.c 项目: siavashg/distr
int main(int argc, char **argv) {
	int opt;
	int daemon = 0;
	int port = SERVER_PORT;
	int server_fd;
	pid_t pid, sid;

	/* Launch options */
	while ((opt = getopt(argc, argv, "dvp:")) != -1) {
		switch (opt) {
		case 'd':
			daemon = 1;
			break;
		case 'v':
			debug = 1;
			break;
		case 'p':
			port = atoi(optarg);
			break;
		default:
			printf("Usage: %s [-d] [-v] [-p port]\n", argv[0]);
			exit(EXIT_FAILURE);
			break;
		}
	}

	/* Signal handling */
	register_signals();

	deprintf ("Starting at port %d\n", port);

	/* Daemonify */
	if (daemon) {
		deprintf ("Starting as daemon\n");
		pid = fork();
		if (pid < 0) {
			exit(EXIT_FAILURE);
		} else if (pid > 0) {
			exit(EXIT_SUCCESS);
		}

		umask(0);
		sid = setsid();
		if (sid < 0) {
			exit(EXIT_FAILURE);
		}
	}

	/* INIT client nodes */
	TAILQ_INIT(&client_nodes);

	server_fd = server_init(port);
	server_shutdown(server_fd);

	printf("Shutting down server.\n");

	return 0;
}
示例#5
0
文件: main.c 项目: oxnz/RTFSC
int main(int argc, char *argv[]) {
	struct server server;
	sigset_t sigset;
	siginfo_t siginfo;
	struct timespec tmo;

	{ // setup server
		server.server_socket.addr = INADDR_ANY;
		server.server_socket.port = 8000;
		server.nrequest_max = 1024;
		server.nworker_min = 16;
		server.nworker_max = 32;
		server.nevent = 10;
		server.event_tmo = 10;
		if (server_init(&server)) {
			perror("server_init");
			return -1;
		}
	}
	{ // blocking all signals
		sigfillset(&sigset);
		if (pthread_sigmask(SIG_BLOCK, &sigset, NULL) != 0) {
			perror("pthread_sigmask");
			return -1;
		}
	}
	server_startup(&server);
	{ // signal handling
		tmo.tv_sec = 0;
		tmo.tv_nsec = 100000000; // 100 ms
		sigemptyset(&sigset);
		sigaddset(&sigset, SIGINT);
		sigfillset(&sigset);
		do {
			int signo = sigtimedwait(&sigset, &siginfo, &tmo);
			//int signo = sigwaitinfo(&sigset, &siginfo);
			if (signo == -1) {
				if (errno == EAGAIN || errno == EINTR) {
					continue;
				}
				perror("sigwaitinfo");
				break;
			}
			//dispatch_signal(siginfo);
			printf("got signal %d\n", siginfo.si_signo);
			if (siginfo.si_signo == SIGINT) {
				printf("interrupted, quittingx\n");
				break;
			}
		} while (1);
	}

	printf("shuting down\n");
	server_shutdown(&server);

	return 0;
}
示例#6
0
void world_destroy(void *p)
{
  server_startup_st *construct= (server_startup_st *)p;
  memcached_server_st *servers= (memcached_server_st *)construct->servers;
  memcached_server_list_free(servers);

  server_shutdown(construct);
  free(construct);
}
示例#7
0
static void sig_handler(int signal)
{
	if(server_shutdown_flag)	/* Already shutting down */
		return;

	switch(signal)
	{
		case SIGINT:
		case SIGTERM:
			log_wr(ILOG, "Terminating by signal %d.", signal);
			server_shutdown();
			break;
		case SIGUSR1:
			log_reopen();
			break;
		default:
			log_wr(ELOG, "Process terminated with unexpected signal %d.", signal);
			server_shutdown();
			break;
	}
}
示例#8
0
文件: main.c 项目: h4xxel/birdie26
void restart_to_menu(const char *name) {
	// This is ugly :D
	char buf[4096];
	
	server_shutdown();
	network_close_tcp(server_sock);
	
	sprintf(buf, "%s", d_fs_exec_path());
	sprintf(buf, "%s", basename(buf));
	if(name)
		execl(d_fs_exec_path(), buf, name, NULL);
	else
		execl(d_fs_exec_path(), buf, NULL);
}
示例#9
0
文件: server.c 项目: ryo/netbsd-src
/*
 * Initialize server
 */
bool
server_init(server_t *srv, char const *control, char const *sgroup)
{

	assert(srv != NULL);
	assert(control != NULL);

	memset(srv, 0, sizeof(*srv));
	FD_ZERO(&srv->fdset);
	srv->sgroup = sgroup;

	srv->fdmax = -1;
	srv->fdidx = calloc(FD_SETSIZE, sizeof(fd_idx_t));
	if (srv->fdidx == NULL) {
		log_crit("Failed to allocate fd index");
		goto fail;
	}

	srv->ctllen = CMSG_SPACE(SOCKCREDSIZE(MAX_GROUPS));
	srv->ctlbuf = malloc(srv->ctllen);
	if (srv->ctlbuf == NULL) {
		log_crit("Malloc cmsg buffer (len=%zu) failed.", srv->ctllen);
		goto fail;
	}

	srv->imtu = SDP_LOCAL_MTU - sizeof(sdp_pdu_t);
	srv->ibuf = malloc(srv->imtu);
	if (srv->ibuf == NULL) {
		log_crit("Malloc input buffer (imtu=%d) failed.", srv->imtu);
		goto fail;
	}

	srv->omtu = L2CAP_MTU_DEFAULT - sizeof(sdp_pdu_t);
	srv->obuf = malloc(srv->omtu);
	if (srv->obuf == NULL) {
		log_crit("Malloc output buffer (omtu=%d) failed.", srv->omtu);
		goto fail;
	}

	if (db_init(srv)
	    && server_open_control(srv, control)
	    && server_open_l2cap(srv))
		return true;

fail:
	server_shutdown(srv);
	return false;
}
void receiveLoop(void * arg) {
  int sock = (int)(unsigned long) arg;
  char recvbuf[4096];
  ssize_t m;
  int numSent = RESPONSE_LEN;
  int remaining = EXPECTED_RECV_LEN;
  int nc;

  while(1) {
    m = recv(sock, recvbuf, remaining, MSG_WAITALL);
    if (m > 0) {
      remaining = remaining - m;
      if (remaining == 0) {
#ifdef PERTURB_VARIANT
        fib(FIB_NUM);
#endif
        __sync_fetch_and_add(&num_requests, 1);
        remaining = EXPECTED_RECV_LEN;
        numSent = send(sock, RESPONSE, RESPONSE_LEN, 0);
        /*printf(".");*/
        if (numSent == -1) {
          perror("send failed");
          exit(-1);
        }
        if (numSent != RESPONSE_LEN) {
          perror("partial send");
          exit(-1);
        }
      } else if (remaining < 0) {
          perror("remaining < 0");
      } else {
        continue;
      }
    } else if (m == 0) {
      nc = __sync_sub_and_fetch(&num_clients, 1);
      //__sync_fetch_and_add(&num_requests, nreq);
      if (nc == 0)
        server_shutdown();
      break;
    } else {
      perror("recv");
    }
  }
}
示例#11
0
文件: app.c 项目: rzel/dim3
bool app_start(char *err_str)
{
		// initialize timing

	game_time_initialize();
	
		// physics ray tracing
		
	if (!ray_trace_initialize(err_str)) return(FALSE);
	
		// OS network initialization
		
	net_initialize();
	
		// read setup preferences
		
	setup_xml_read();
	
		// client network defaults
		
	net_setup.mode=net_mode_none;
	
		// initialize server
		
	if (!server_initialize(err_str)) return(FALSE);

		// initialize view
		// if not running in dedicated host mode
	
	if (!app.dedicated_host) {

		if (!view_initialize(err_str)) {
			server_shutdown();
			return(FALSE);
		}

		console_initialize();
	}

	return(TRUE);
}
/* -------------------------------------------------------------------------- */
int
server_process(server_t* server, const unsigned char* data, size_t size, 
               unsigned char** response, size_t* response_size)
{
  if(server == NULL || server->db == NULL || data == NULL || strlen((char*)data) == 0
     || size == 0 || response == NULL || response_size == NULL)
    return ERROR_INVALID_ARGUMENTS;

  /* unpack package */
  unsigned char packettype = '\0';
  unsigned char *domain = NULL;
  unsigned char* key = NULL;
  data_store_t ds;
  if(simple_memory_buffer_new(&ds, data, size) != ERROR_OK )
    return ERROR_UNKNOWN;
  
  int64_t ret = ERROR_OK;
  if((ret = data_store_read_byte(&ds, &packettype)) != ERROR_OK || 
     (ret = bunpack(&ds, "ss", &domain, &key)) != ERROR_OK){
    if(domain != NULL)
      freeMemory(domain);
    if(key != NULL)
      freeMemory(key);
  }

  /* handle incomming data */
  int64_t integer = 0;
  double dob = 0.0;
  char* string = NULL;
  unsigned char* blob = NULL;
  size_t bsize = 0;
  database_value_type_t type;
  size_t count = 0;
  int64_t count_enum = 0;
  size_t esize = 0;
  char* keys = NULL; 

  data_store_t response_ds;
  if(simple_memory_buffer_new(&response_ds, NULL, 0) != ERROR_OK){
    if(domain != NULL)
      freeMemory(domain);
    if(key != NULL)
      freeMemory(key);
    simple_memory_buffer_free(&ds);
    return ERROR_UNKNOWN;
  }

  if(ret == ERROR_OK){
    switch(packettype){

      /* Int handling */
      case PACKET_GET_INT:
         ret = database_get_int64(server->db, (char*)domain, (char*)key, &integer);
         if(ret != ERROR_OK) break;

         if(data_store_write_byte(&response_ds, PACKET_INT) != ERROR_OK ||
            bpack(&response_ds, "l", integer) != ERROR_OK)
           ret = ERROR_UNKNOWN; 
         break;

      case PACKET_SET_INT:
         if(bunpack(&ds, "l", &integer) != ERROR_OK){
           ret = ERROR_UNKNOWN; break;
          }

         ret = database_set_int64(server->db, (char*)domain, (char*)key, integer);
         if(ret != ERROR_OK) break;

         if(data_store_write_byte(&response_ds, PACKET_OK) != ERROR_OK)
           ret = ERROR_UNKNOWN; 
         break;

      /* Double handling */
      case PACKET_GET_DOUBLE:
         ret = database_get_double(server->db, (char*)domain, (char*)key, &dob);
         if(ret != ERROR_OK) break;

         if(data_store_write_byte(&response_ds, PACKET_DOUBLE) != ERROR_OK ||
            bpack(&response_ds, "d", dob) != ERROR_OK)
           ret = ERROR_UNKNOWN; 
         break;

      case PACKET_SET_DOUBLE:
         if(bunpack(&ds, "d", &dob) != ERROR_OK){
           ret = ERROR_UNKNOWN; break;
         }

         ret = database_set_double(server->db, (char*)domain, (char*)key, dob);
         if(ret != ERROR_OK) break;

         if(data_store_write_byte(&response_ds, PACKET_OK) != ERROR_OK)
           ret = ERROR_UNKNOWN; 
         break;

      /* String handling */
      case PACKET_GET_STRING:
         ret = database_get_string(server->db, (char*)domain, (char*)key, &string);
         if(ret != ERROR_OK){
           if(string)
             freeMemory(string);
           break;
         }

         if(data_store_write_byte(&response_ds, PACKET_STRING) != ERROR_OK ||
            bpack(&response_ds, "s", string) != ERROR_OK)
           ret = ERROR_UNKNOWN;
         freeMemory(string);
         break;

      case PACKET_SET_STRING:
         if(bunpack(&ds, "s", &string) != ERROR_OK){
           ret = ERROR_UNKNOWN; break;
         }

         ret = database_set_string(server->db, (char*)domain, (char*)key, string);
         if(ret != ERROR_OK) break;
         freeMemory(string);

         if(data_store_write_byte(&response_ds, PACKET_OK) != ERROR_OK)
           ret = ERROR_UNKNOWN; 
         break;

      /* Blob handling */
      case PACKET_GET_BLOB:
         ret = database_get_blob(server->db, (char*)domain, (char*)key, &blob, &bsize);
         if(ret != ERROR_OK){
           if(blob != NULL)
             freeMemory(blob);
           break;
         }

         if(data_store_write_byte(&response_ds, PACKET_BLOB) != ERROR_OK ||
            bpack(&response_ds, "b", bsize, blob) != ERROR_OK)
           ret = ERROR_UNKNOWN; 
         freeMemory(blob);
         break;

      case PACKET_SET_BLOB:
         if(bunpack(&ds, "b", &bsize, &blob) != ERROR_OK){
           ret = ERROR_UNKNOWN; break;
         }

         ret = database_set_blob(server->db, (char*)domain, (char*)key, blob, bsize);
         if(ret != ERROR_OK) break;
         freeMemory(blob);

         if(data_store_write_byte(&response_ds, PACKET_OK) != ERROR_OK)
           ret = ERROR_UNKNOWN; 
         break;

      /* Others handling */
      case PACKET_GET_ENUM:
         ret = database_enum_keys(server->db, (char*)domain, (char*)key, &count, &esize, &keys);
         if(ret != ERROR_OK){
           if(keys != NULL)
             freeMemory(keys);
           break;
         }
         
         count_enum = count;
         if(data_store_write_byte(&response_ds, PACKET_ENUM) != ERROR_OK)
           ret = ERROR_UNKNOWN; 
         if(keys == NULL){
           if(bpack(&response_ds, "l", count_enum) != ERROR_OK)
             ret = ERROR_UNKNOWN; 
         }else{
           if(bpack(&response_ds, "lb", count_enum, esize, keys) != ERROR_OK)
             ret = ERROR_UNKNOWN; 
           freeMemory(keys);
         }
         break;

      case PACKET_GET_VALUE_TYPE:
         ret = database_get_type(server->db, (char*)domain, (char*)key, &type);
         if(ret != ERROR_OK) break;

         if(data_store_write_byte(&response_ds, PACKET_TYPE) != ERROR_OK ||
            bpack(&response_ds, "l", (int64_t)type) != ERROR_OK)
           ret = ERROR_UNKNOWN; 
         break;

      case PACKET_SHUTDOWN:
        if(server_shutdown(server) != ERROR_OK){
          ret = ERROR_UNKNOWN; break;
        } 
        ret =  ERROR_SERVER_SHUTDOWN; 
        break;

      default: ret = ERROR_UNKNOWN; break;
    }
  freeMemory(domain);
  freeMemory(key);
  }

  /* free input datastore */
  if(simple_memory_buffer_free(&ds) != ERROR_OK)
    ret = ERROR_UNKNOWN;

  /* send packet */
  if(ret == ERROR_OK){
    if(sendPacket(&response_ds, response_size, response) != ERROR_OK)
      ret = ERROR_UNKNOWN;
  }

  if(simple_memory_buffer_free(&response_ds) != ERROR_OK)
    ret = ERROR_UNKNOWN;

  /* error packet */
  if(ret != ERROR_OK && ret != ERROR_SERVER_SHUTDOWN){
    data_store_t error_ds;
    if(simple_memory_buffer_new(&error_ds, NULL, 0) != ERROR_OK ||
       data_store_write_byte(&error_ds, PACKET_ERROR) != ERROR_OK ||
       bpack(&error_ds, "l", ret) != ERROR_OK){
      simple_memory_buffer_free(&error_ds);
      ret = ERROR_UNKNOWN; 
    }else{
      if((ret = sendPacket(&error_ds, response_size, response)) != ERROR_OK)
        ret = ERROR_UNKNOWN;
      simple_memory_buffer_free(&error_ds);
    }
  }

  return ret;
}
示例#13
0
int
main(int argc, char * const argv[])
{
	int stream_sock[] = {0, 0, 0};  /* tcp4, tcp6, UNIX */
	int stream_socklen = sizeof(stream_sock) / sizeof(stream_sock[0]);
	int dgram_sock[] = {0, 0};  /* udp4, udp6 */
	int dgram_socklen = sizeof(dgram_sock) / sizeof(dgram_sock[0]);
	char id;
	unsigned short listenport = 2003;
	int ch;
	size_t numaggregators;
	size_t numcomputes;
	server *internal_submission;
	char *listeninterface = NULL;
	server **servers;
	char *allowed_chars = NULL;
	int i;
	enum { SUB, CUM } smode = CUM;

	if (gethostname(relay_hostname, sizeof(relay_hostname)) < 0)
		snprintf(relay_hostname, sizeof(relay_hostname), "127.0.0.1");

	while ((ch = getopt(argc, argv, ":hvdmstf:i:l:p:w:b:q:S:c:H:")) != -1) {
		switch (ch) {
			case 'v':
				do_version();
				break;
			case 'd':
				if (mode == TEST) {
					mode = DEBUGTEST;
				} else {
					mode = DEBUG;
				}
				break;
			case 'm':
				smode = SUB;
				break;
			case 's':
				mode = SUBMISSION;
				break;
			case 't':
				if (mode == DEBUG) {
					mode = DEBUGTEST;
				} else {
					mode = TEST;
				}
				break;
			case 'f':
				config = optarg;
				break;
			case 'i':
				listeninterface = optarg;
				break;
			case 'l':
				relay_logfile = optarg;
				break;
			case 'p':
				listenport = (unsigned short)atoi(optarg);
				if (listenport == 0) {
					fprintf(stderr, "error: port needs to be a number >0\n");
					do_usage(1);
				}
				break;
			case 'w':
				workercnt = (char)atoi(optarg);
				if (workercnt <= 0) {
					fprintf(stderr, "error: workers needs to be a number >0\n");
					do_usage(1);
				}
				break;
			case 'b':
				batchsize = atoi(optarg);
				if (batchsize <= 0) {
					fprintf(stderr, "error: batch size needs to be a number >0\n");
					do_usage(1);
				}
				break;
			case 'q':
				queuesize = atoi(optarg);
				if (queuesize <= 0) {
					fprintf(stderr, "error: queue size needs to be a number >0\n");
					do_usage(1);
				}
				break;
			case 'S':
				collector_interval = atoi(optarg);
				if (collector_interval <= 0) {
					fprintf(stderr, "error: sending interval needs to be "
							"a number >0\n");
					do_usage(1);
				}
				break;
			case 'c':
				allowed_chars = optarg;
				break;
			case 'H':
				snprintf(relay_hostname, sizeof(relay_hostname), "%s", optarg);
				break;
			case '?':
			case ':':
				do_usage(1);
				break;
			case 'h':
			default:
				do_usage(0);
				break;
		}
	}
	if (optind == 1 || config == NULL)
		do_usage(1);


	/* seed randomiser for dispatcher and aggregator "splay" */
	srand(time(NULL));

	if (workercnt == 0)
		workercnt = mode == SUBMISSION ? 2 : get_cores();

	/* any_of failover maths need batchsize to be smaller than queuesize */
	if (batchsize > queuesize) {
		fprintf(stderr, "error: batchsize must be smaller than queuesize\n");
		exit(-1);
	}

	if (relay_logfile != NULL && mode != TEST && mode != DEBUGTEST) {
		FILE *f = fopen(relay_logfile, "a");
		if (f == NULL) {
			fprintf(stderr, "error: failed to open logfile '%s': %s\n",
					relay_logfile, strerror(errno));
			exit(-1);
		}
		relay_stdout = f;
		relay_stderr = f;
	} else {
		relay_stdout = stdout;
		relay_stderr = stderr;
	}
	relay_can_log = 1;

	logout("starting carbon-c-relay v%s (%s), pid=%d\n",
			VERSION, GIT_VERSION, getpid());
	fprintf(relay_stdout, "configuration:\n");
	fprintf(relay_stdout, "    relay hostname = %s\n", relay_hostname);
	fprintf(relay_stdout, "    listen port = %u\n", listenport);
	if (listeninterface != NULL)
		fprintf(relay_stdout, "    listen interface = %s\n", listeninterface);
	fprintf(relay_stdout, "    workers = %d\n", workercnt);
	fprintf(relay_stdout, "    send batch size = %d\n", batchsize);
	fprintf(relay_stdout, "    server queue size = %d\n", queuesize);
	fprintf(relay_stdout, "    statistics submission interval = %ds\n",
			collector_interval);
	if (allowed_chars != NULL)
		fprintf(relay_stdout, "    extra allowed characters = %s\n",
				allowed_chars);
	if (mode == DEBUG || mode == DEBUGTEST)
		fprintf(relay_stdout, "    debug = true\n");
	else if (mode == SUBMISSION)
		fprintf(relay_stdout, "    submission = true\n");
	fprintf(relay_stdout, "    routes configuration = %s\n", config);
	fprintf(relay_stdout, "\n");

	if (router_readconfig(&clusters, &routes,
				config, queuesize, batchsize) == 0)
	{
		logerr("failed to read configuration '%s'\n", config);
		return 1;
	}
	router_optimise(&routes);

	numaggregators = aggregator_numaggregators();
	numcomputes = aggregator_numcomputes();
#define dbg (mode == DEBUG || mode == DEBUGTEST ? 2 : 0)
	if (numaggregators > 10 && !dbg) {
		fprintf(relay_stdout, "parsed configuration follows:\n"
				"(%zd aggregations with %zd computations omitted "
				"for brevity)\n", numaggregators, numcomputes);
		router_printconfig(relay_stdout, 0, clusters, routes);
	} else {
		fprintf(relay_stdout, "parsed configuration follows:\n");
		router_printconfig(relay_stdout, 1 + dbg, clusters, routes);
	}
	fprintf(relay_stdout, "\n");

	/* shortcut for rule testing mode */
	if (mode == TEST || mode == DEBUGTEST) {
		char metricbuf[METRIC_BUFSIZ];
		char *p;

		fflush(relay_stdout);
		while (fgets(metricbuf, sizeof(metricbuf), stdin) != NULL) {
			if ((p = strchr(metricbuf, '\n')) != NULL)
				*p = '\0';
			router_test(metricbuf, routes);
		}

		exit(0);
	}

	if (signal(SIGINT, exit_handler) == SIG_ERR) {
		logerr("failed to create SIGINT handler: %s\n", strerror(errno));
		return 1;
	}
	if (signal(SIGTERM, exit_handler) == SIG_ERR) {
		logerr("failed to create SIGTERM handler: %s\n", strerror(errno));
		return 1;
	}
	if (signal(SIGQUIT, exit_handler) == SIG_ERR) {
		logerr("failed to create SIGQUIT handler: %s\n", strerror(errno));
		return 1;
	}
	if (signal(SIGHUP, hup_handler) == SIG_ERR) {
		logerr("failed to create SIGHUP handler: %s\n", strerror(errno));
		return 1;
	}
	if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
		logerr("failed to ignore SIGPIPE: %s\n", strerror(errno));
		return 1;
	}

	workers = malloc(sizeof(dispatcher *) * (1 + workercnt + 1));
	if (workers == NULL) {
		logerr("failed to allocate memory for workers\n");
		return 1;
	}

	if (bindlisten(stream_sock, &stream_socklen,
				dgram_sock, &dgram_socklen,
				listeninterface, listenport) < 0) {
		logerr("failed to bind on port %s:%d: %s\n",
				listeninterface == NULL ? "" : listeninterface,
				listenport, strerror(errno));
		return -1;
	}
	for (ch = 0; ch < stream_socklen; ch++) {
		if (dispatch_addlistener(stream_sock[ch]) != 0) {
			logerr("failed to add listener\n");
			return -1;
		}
	}
	for (ch = 0; ch < dgram_socklen; ch++) {
		if (dispatch_addlistener_udp(dgram_sock[ch]) != 0) {
			logerr("failed to listen to datagram socket\n");
			return -1;
		}
	}
	if ((workers[0] = dispatch_new_listener()) == NULL)
		logerr("failed to add listener\n");

	if (allowed_chars == NULL)
		allowed_chars = "-_:#";
	logout("starting %d workers\n", workercnt);
	for (id = 1; id < 1 + workercnt; id++) {
		workers[id + 0] = dispatch_new_connection(routes, allowed_chars);
		if (workers[id + 0] == NULL) {
			logerr("failed to add worker %d\n", id);
			break;
		}
	}
	workers[id + 0] = NULL;
	if (id < 1 + workercnt) {
		logerr("shutting down due to errors\n");
		keep_running = 0;
	}

	/* server used for delivering metrics produced inside the relay,
	 * that is collector (statistics) and aggregator (aggregations) */
	if ((internal_submission = server_new("internal", listenport, CON_PIPE,
					NULL, 3000 + (numcomputes * 3), batchsize)) == NULL)
	{
		logerr("failed to create internal submission queue, shutting down\n");
		keep_running = 0;
	}

	if (numaggregators > 0) {
		logout("starting aggregator\n");
		if (!aggregator_start(internal_submission)) {
			logerr("shutting down due to failure to start aggregator\n");
			keep_running = 0;
		}
	}

	logout("starting statistics collector\n");
	collector_start(&workers[1], clusters, internal_submission, smode == CUM);

	logout("startup sequence complete\n");

	/* workers do the work, just wait */
	while (keep_running)
		sleep(1);

	logout("shutting down...\n");
	/* make sure we don't accept anything new anymore */
	for (ch = 0; ch < stream_socklen; ch++)
		dispatch_removelistener(stream_sock[ch]);
	destroy_usock(listenport);
	logout("listeners for port %u closed\n", listenport);
	/* since workers will be freed, stop querying the structures */
	collector_stop();
	logout("collector stopped\n");
	if (numaggregators > 0) {
		aggregator_stop();
		logout("aggregator stopped\n");
	}
	server_shutdown(internal_submission);
	/* give a little time for whatever the collector/aggregator wrote,
	 * to be delivered by the dispatchers */
	usleep(500 * 1000);  /* 500ms */
	/* make sure we don't write to our servers any more */
	logout("stopped worker");
	for (id = 0; id < 1 + workercnt; id++)
		dispatch_stop(workers[id + 0]);
	for (id = 0; id < 1 + workercnt; id++) {
		dispatch_shutdown(workers[id + 0]);
		fprintf(relay_stdout, " %d", id + 1);
		fflush(relay_stdout);
	}
	fprintf(relay_stdout, "\n");
	router_shutdown();
	servers = router_getservers(clusters);
	logout("stopped server");
	for (i = 0; servers[i] != NULL; i++)
		server_stop(servers[i]);
	for (i = 0; servers[i] != NULL; i++) {
		server_shutdown(servers[i]);
		fprintf(relay_stdout, " %d", i + 1);
		fflush(relay_stdout);
	}
	fprintf(relay_stdout, "\n");
	logout("routing stopped\n");

	router_free(clusters, routes);
	free(workers);
	return 0;
}
示例#14
0
int main(int argc, char **argv) {
  /* Sensor values */

#if defined(CONFIG_WEDGE)
  int intake_temp;
  int exhaust_temp;
  int switch_temp;
  int userver_temp;
#else
  float intake_temp;
  float exhaust_temp;
  float userver_temp;
#endif

  int fan_speed = fan_high;
  int bad_reads = 0;
  int fan_failure = 0;
  int fan_speed_changes = 0;
  int old_speed;

  int fan_bad[FANS];
  int fan;

  unsigned log_count = 0; // How many times have we logged our temps?
  int opt;
  int prev_fans_bad = 0;

  struct sigaction sa;

  sa.sa_handler = fand_interrupt;
  sa.sa_flags = 0;
  sigemptyset(&sa.sa_mask);

  sigaction(SIGTERM, &sa, NULL);
  sigaction(SIGINT, &sa, NULL);
  sigaction(SIGUSR1, &sa, NULL);

  // Start writing to syslog as early as possible for diag purposes.

  openlog("fand", LOG_CONS, LOG_DAEMON);

#if defined(CONFIG_WEDGE) && !defined(CONFIG_WEDGE100)
  if (is_two_fan_board(false)) {
    /* Alternate, two fan configuration */
    total_fans = 2;
    fan_offset = 2; /* fan 3 is the first */

    fan_low = SIXPACK_FAN_LOW;
    fan_medium = SIXPACK_FAN_MEDIUM;
    fan_high = SIXPACK_FAN_HIGH;
    fan_max = SIXPACK_FAN_MAX;
    fan_speed = fan_high;
  }
#endif

  while ((opt = getopt(argc, argv, "l:m:h:b:t:r:v")) != -1) {
    switch (opt) {
    case 'l':
      fan_low = atoi(optarg);
      break;
    case 'm':
      fan_medium = atoi(optarg);
      break;
    case 'h':
      fan_high = atoi(optarg);
      break;
    case 'b':
      temp_bottom = INTERNAL_TEMPS(atoi(optarg));
      break;
    case 't':
      temp_top = INTERNAL_TEMPS(atoi(optarg));
      break;
    case 'r':
      report_temp = atoi(optarg);
      break;
    case 'v':
      verbose = true;
      break;
    default:
      usage();
      break;
    }
  }

  if (optind > argc) {
    usage();
  }

  if (temp_bottom > temp_top) {
    fprintf(stderr,
            "Should temp-bottom (%d) be higher than "
            "temp-top (%d)?  Starting anyway.\n",
            EXTERNAL_TEMPS(temp_bottom),
            EXTERNAL_TEMPS(temp_top));
  }

  if (fan_low > fan_medium || fan_low > fan_high || fan_medium > fan_high) {
    fprintf(stderr,
            "fan RPMs not strictly increasing "
            "-- %d, %d, %d, starting anyway\n",
            fan_low,
            fan_medium,
            fan_high);
  }

  daemon(1, 0);

  if (verbose) {
    syslog(LOG_DEBUG, "Starting up;  system should have %d fans.",
           total_fans);
  }

  for (fan = 0; fan < total_fans; fan++) {
    fan_bad[fan] = 0;
    write_fan_speed(fan + fan_offset, fan_speed);
    write_fan_led(fan + fan_offset, FAN_LED_BLUE);
  }

#if defined(CONFIG_YOSEMITE)
  /* Ensure that we can read from sensors before proceeding. */

  int found = 0;
  userver_temp = 100;
  while (!found) {
    for (int node = 1; node <= TOTAL_1S_SERVERS && !found; node++) {
      if (!yosemite_sensor_read(node, BIC_SENSOR_SOC_THERM_MARGIN,
                               &userver_temp) &&
          userver_temp < 0) {
        syslog(LOG_DEBUG, "SOC_THERM_MARGIN first valid read of %f.",
               userver_temp);
        found = 1;
      }
      sleep(5);
    }
    // XXX:  Will it ever be a problem that we don't exit this until
    //       we see a valid value?
  }
#endif

  /* Start watchdog in manual mode */
  start_watchdog(0);

  /* Set watchdog to persistent mode so timer expiry will happen independent
   * of this process's liveliness. */
  set_persistent_watchdog(WATCHDOG_SET_PERSISTENT);

  sleep(5);  /* Give the fans time to come up to speed */

  while (1) {
    int max_temp;
    old_speed = fan_speed;

    /* Read sensors */

#if defined(CONFIG_WEDGE) || defined(CONFIG_WEDGE100)
    read_temp(INTAKE_TEMP_DEVICE, &intake_temp);
    read_temp(EXHAUST_TEMP_DEVICE, &exhaust_temp);
    read_temp(CHIP_TEMP_DEVICE, &switch_temp);
    read_temp(USERVER_TEMP_DEVICE, &userver_temp);

    /*
     * uServer can be powered down, but all of the rest of the sensors
     * should be readable at any time.
     */

    if ((intake_temp == BAD_TEMP || exhaust_temp == BAD_TEMP ||
         switch_temp == BAD_TEMP)) {
      bad_reads++;
    }
#else
    intake_temp = exhaust_temp = userver_temp = BAD_TEMP;
    if (yosemite_sensor_read(FRU_SPB, SP_SENSOR_INLET_TEMP, &intake_temp) ||
        yosemite_sensor_read(FRU_SPB, SP_SENSOR_OUTLET_TEMP, &exhaust_temp))
      bad_reads++;

    /*
     * There are a number of 1S servers;  any or all of them
     * could be powered off and returning no values.  Ignore these
     * invalid values.
     */
    for (int node = 1; node <= TOTAL_1S_SERVERS; node++) {
      float new_temp;
      if (!yosemite_sensor_read(node, BIC_SENSOR_SOC_THERM_MARGIN,
			        &new_temp)) {
        if (userver_temp < new_temp) {
          userver_temp = new_temp;
        }
      }

      // Since the yosemite_sensor_read() times out after 8secs, keep WDT from expiring
      kick_watchdog();
    }
#endif

    if (bad_reads > BAD_READ_THRESHOLD) {
      server_shutdown("Some sensors couldn't be read");
    }

    if (log_count++ % report_temp == 0) {
      syslog(LOG_DEBUG,
#if defined(CONFIG_WEDGE) || defined(CONFIG_WEDGE100)
             "Temp intake %d, t2 %d, "
             " userver %d, exhaust %d, "
             "fan speed %d, speed changes %d",
#else
             "Temp intake %f, max server %f, exhaust %f, "
             "fan speed %d, speed changes %d",
#endif
             intake_temp,
#if defined(CONFIG_WEDGE) || defined(CONFIG_WEDGE100)
             switch_temp,
#endif
             userver_temp,
             exhaust_temp,
             fan_speed,
             fan_speed_changes);
    }

    /* Protection heuristics */

    if (intake_temp > INTAKE_LIMIT) {
      server_shutdown("Intake temp limit reached");
    }

#if defined(CONFIG_WEDGE) || defined(CONFIG_WEDGE100)
    if (switch_temp > SWITCH_LIMIT) {
      server_shutdown("T2 temp limit reached");
    }
#endif

    if (userver_temp + USERVER_TEMP_FUDGE > USERVER_LIMIT) {
      server_shutdown("uServer temp limit reached");
    }

    /*
     * Calculate change needed -- we should eventually
     * do something more sophisticated, like PID.
     *
     * We should use the intake temperature to adjust this
     * as well.
     */

#if defined(CONFIG_YOSEMITE)
    /* Use tables to lookup the new fan speed for Yosemite. */

    int intake_speed = temp_to_fan_speed(intake_temp, intake_map,
                                         INTAKE_MAP_SIZE);
    int cpu_speed = temp_to_fan_speed(userver_temp, cpu_map, CPU_MAP_SIZE);

    if (fan_speed == fan_max && fan_failure != 0) {
      /* Don't change a thing */
    } else if (intake_speed > cpu_speed) {
      fan_speed = intake_speed;
    } else {
      fan_speed = cpu_speed;
    }
#else
    /* Other systems use a simpler built-in table to determine fan speed. */

    if (switch_temp > userver_temp + USERVER_TEMP_FUDGE) {
      max_temp = switch_temp;
    } else {
      max_temp = userver_temp + USERVER_TEMP_FUDGE;
    }

    /*
     * If recovering from a fan problem, spin down fans gradually in case
     * temperatures are still high. Gradual spin down also reduces wear on
     * the fans.
     */
    if (fan_speed == fan_max) {
      if (fan_failure == 0) {
        fan_speed = fan_high;
      }
    } else if (fan_speed == fan_high) {
      if (max_temp + COOLDOWN_SLOP < temp_top) {
        fan_speed = fan_medium;
      }
    } else if (fan_speed == fan_medium) {
      if (max_temp > temp_top) {
        fan_speed = fan_high;
      } else if (max_temp + COOLDOWN_SLOP < temp_bottom) {
        fan_speed = fan_low;
      }
    } else {/* low */
      if (max_temp > temp_bottom) {
        fan_speed = fan_medium;
      }
    }
#endif

    /*
     * Update fans only if there are no failed ones. If any fans failed
     * earlier, all remaining fans should continue to run at max speed.
     */

    if (fan_failure == 0 && fan_speed != old_speed) {
      syslog(LOG_NOTICE,
             "Fan speed changing from %d to %d",
             old_speed,
             fan_speed);
      fan_speed_changes++;
      for (fan = 0; fan < total_fans; fan++) {
        write_fan_speed(fan + fan_offset, fan_speed);
      }
    }

    /*
     * Wait for some change.  Typical I2C temperature sensors
     * only provide a new value every second and a half, so
     * checking again more quickly than that is a waste.
     *
     * We also have to wait for the fan changes to take effect
     * before measuring them.
     */

    sleep(5);

    /* Check fan RPMs */

    for (fan = 0; fan < total_fans; fan++) {
      /*
       * Make sure that we're within some percentage
       * of the requested speed.
       */
      if (fan_speed_okay(fan + fan_offset, fan_speed, FAN_FAILURE_OFFSET)) {
        if (fan_bad[fan] > FAN_FAILURE_THRESHOLD) {
          write_fan_led(fan + fan_offset, FAN_LED_BLUE);
          syslog(LOG_CRIT,
                 "Fan %d has recovered",
                 fan);
        }
        fan_bad[fan] = 0;
      } else {
        fan_bad[fan]++;
      }
    }

    fan_failure = 0;
    for (fan = 0; fan < total_fans; fan++) {
      if (fan_bad[fan] > FAN_FAILURE_THRESHOLD) {
        fan_failure++;
        write_fan_led(fan + fan_offset, FAN_LED_RED);
      }
    }

    if (fan_failure > 0) {
      if (prev_fans_bad != fan_failure) {
        syslog(LOG_CRIT, "%d fans failed", fan_failure);
      }

      /*
       * If fans are bad, we need to blast all of the
       * fans at 100%;  we don't bother to turn off
       * the bad fans, in case they are all that is left.
       *
       * Note that we have a temporary bug with setting fans to
       * 100% so we only do fan_max = 99%.
       */

      fan_speed = fan_max;
      for (fan = 0; fan < total_fans; fan++) {
        write_fan_speed(fan + fan_offset, fan_speed);
      }

#if defined(CONFIG_WEDGE) || defined(CONFIG_WEDGE100)
      /*
       * On Wedge, we want to shut down everything if none of the fans
       * are visible, since there isn't automatic protection to shut
       * off the server or switch chip.  On other platforms, the CPUs
       * generating the heat will automatically turn off, so this is
       * unnecessary.
       */

      if (fan_failure == total_fans) {
        int count = 0;
        for (fan = 0; fan < total_fans; fan++) {
          if (fan_bad[fan] > FAN_SHUTDOWN_THRESHOLD)
            count++;
        }
        if (count == total_fans) {
          server_shutdown("all fans are bad for more than 12 cycles");
        }
      }
#endif

      /*
       * Fans can be hot swapped and replaced; in which case the fan daemon
       * will automatically detect the new fan and (assuming the new fan isn't
       * itself faulty), automatically readjust the speeds for all fans down
       * to a more suitable rpm. The fan daemon does not need to be restarted.
       */
    }

    /* Suppress multiple warnings for similar number of fan failures. */
    prev_fans_bad = fan_failure;

    /* if everything is fine, restart the watchdog countdown. If this process
     * is terminated, the persistent watchdog setting will cause the system
     * to reboot after the watchdog timeout. */
    kick_watchdog();
  }
}
示例#15
0
static void int_sig_handler( int sig_num) 
{
    server_shutdown();
    exit(sig_num);
}
示例#16
0
文件: core.c 项目: logbird/webServer
void sig_handle(int sigtype)
{
    server_shutdown();
}
示例#17
0
void server::handle_read_from_fifo(const boost::system::error_code& error, std::size_t)
{
	if(error) {
		if(error == boost::asio::error::operation_aborted)
			// This means fifo was closed by load_config() to open another fifo
			return;
		ERR_CS << "Error reading from fifo: " << error.message() << '\n';
		return;
	}

	std::istream is(&admin_cmd_);
	std::string cmd;
	std::getline(is, cmd);

	const control_line ctl = cmd;

	if(ctl == "shut_down") {
		LOG_CS << "Shut down requested by admin, shutting down...\n";
		throw server_shutdown("Shut down via fifo command");
	} else if(ctl == "readonly") {
		if(ctl.args_count()) {
			cfg_["read_only"] = read_only_ = utils::string_bool(ctl[1], true);
		}

		LOG_CS << "Read only mode: " << (read_only_ ? "enabled" : "disabled") << '\n';
	} else if(ctl == "flush") {
		LOG_CS << "Flushing config to disk...\n";
		write_config();
	} else if(ctl == "reload") {
		if(ctl.args_count()) {
			if(ctl[1] == "blacklist") {
				LOG_CS << "Reloading blacklist...\n";
				load_blacklist();
			} else {
				ERR_CS << "Unrecognized admin reload argument: " << ctl[1] << '\n';
			}
		} else {
			LOG_CS << "Reloading all configuration...\n";
			load_config();
			LOG_CS << "Reloaded configuration\n";
		}
	} else if(ctl == "setpass") {
		if(ctl.args_count() != 2) {
			ERR_CS << "Incorrect number of arguments for 'setpass'\n";
		} else {
			const std::string& addon_id = ctl[1];
			const std::string& newpass = ctl[2];
			config& campaign = get_campaign(addon_id);

			if(!campaign) {
				ERR_CS << "Add-on '" << addon_id << "' not found, cannot set passphrase\n";
			} else if(newpass.empty()) {
				// Shouldn't happen!
				ERR_CS << "Add-on passphrases may not be empty!\n";
			} else {
				set_passphrase(campaign, newpass);
				write_config();
				LOG_CS << "New passphrase set for '" << addon_id << "'\n";
			}
		}
	} else {
		ERR_CS << "Unrecognized admin command: " << ctl.full() << '\n';
	}

	read_from_fifo();
}
示例#18
0
int main(int argc, char *argv[])
{
    char buff[BUFLEN], sysbuff[2*BUFLEN];  
    short *ptr;                            
    int rval, option;                      
    int verbose = 0;                       // Disable printing message
    int iteration;                         // Iteration of receiving/sending
    int test_mode;                         // Test mode (RTT/Throughput)
    int stream_mode;                       // Stream or ping-pong mode
    int CPUoption;                         // Monitor system information?
    long_int size;                         // Message size
    long_int elapsedTime;                  // Elapsed time
    struct SYSInfo sysinfo;                // Structure for system information
    struct PROInfo proinfo;                // Structure for process information
    struct hostent *hp;                    // Hostent structure
    struct in_addr sin_addr;               // Hold client's address

    /**************** Variable initialization ******************************/
    /******* 0 means using default value in the socket option setting ******/

    controlSock.port = DEFAULTPORT;        // TCP connection port number
    controlSock.recvBuf = 0;               // TCP socket (recv) buffer size 
    controlSock.sendBuf = 0;               // TCP socket (send) buffer size
    controlSock.blocking = 1;              // Blocking communication mode
    controlSock.delay = 0;                 // Enable Nagel algorithm 
    controlSock.mss = 0;                   // TCP MSS (Maximum Segment Size)
    controlSock.cork = 0;                  // TCP_CORK option 
    controlSock.tos =0;                    // TOS (Type of Service)
    controlSock.dataSize = 8192;           // Data size of each sending/receiving
    testSock.port = 0;                     // Test port is selected by system
  
    /*********************** Print help message ****************************/

    if ( argc > 1 && strcmp(argv[1], "--help") == 0 ) {
	fprintf(stderr, help_description);
	fprintf(stderr, help_usage, DEFAULTPORT, DEFAULTSIZE, DEFAULTPORT,  
		DEFAULTREPEAT, DEFAULTTIME);
	fprintf(stderr, help_example);
	return 0;
    } 

    /**************** Parse the command line *******************************/
      
    if ( argc > 1 ) {
	while ( (option = getopt (argc, argv, ":vp:")) != -1) {
	    switch ( option ) {
	    case 'v':  
		verbose = 1;
		break;
	    case 'p':
		if ( atoi(optarg) >= 0 )
		    controlSock.port = atoi(optarg);
		break;
	    case ':':
		fprintf(stderr,"Error: -%c without filename.\n", optopt);
		print_usage();
		return 1;
	    case '?':
		fprintf(stderr,"Error: Unknown argument %c\n", optopt);
		print_usage();
		return 1;
	    default: 
		print_usage();
		return 1;
	    }
	}
    }

    /******************** Handle the interruption **************************/
 
    signal(SIGINT, int_sig_handler);
    signal(SIGTSTP, int_sig_handler);
    signal(SIGPIPE, pipe_sig_handler);
    signal(SIGCHLD, child_sig_handler);
 
    /************ Initialize communications for the server *****************/

    if ( server_init(&controlSock) == NOTOK) {
	perror("Unable to initialize communications.");
	exit(1);
    }
    fprintf(stderr, "TCP socket listening on port [%d]\n", controlSock.port);

    /**************** TCP data channel waiting a connection ****************/

    while ( server_get_connection(&controlSock, &sin_addr) == OK ) {
 
	/********** Create a new process to handle the UDP test ************/

	if ( (rval=fork()) > 0 ) { // Parent
	    close (controlSock.socket);
	    continue;
	} else                   // Child
	    close (controlSock.welcomeSocket);

	/*** Receive the TCP communication options from client *************/

	bzero(buff, BUFLEN);
	if ( get_request(&controlSock, buff) == NOTOK || 
	     sscanf(buff, client_request_str, &test_mode, &testSock.blocking, 
		    &testSock.delay, &testSock.cork, &stream_mode, 
		    &testSock.recvBuf, &testSock.sendBuf, &testSock.mss, 
		    &testSock.tos, &testSock.dataSize, &CPUoption) != 11 ) {
	    if ( verbose ) {
		fprintf(stderr, "Receive TCP options error [%s]\n", buff);
		fprintf(stderr, "Quit this session.\n");
	    }
	    close (controlSock.socket);
	    exit (1);
	}

	if ( CPUoption ) {
	    if ( start_trace_system( &sysinfo ) == OK ) {
		sleep (1);
		if ( stop_trace_system ( &sysinfo ) == OK )
		    CPUoption = 1;
	    } else 
		CPUoption = 0;
	}

	/************************ Check the test mode **********************/

	if ( test_mode != LATENCY && test_mode != SENDFILE && 
	     test_mode != THROUGHPUT ) { 
	    if ( verbose )
		fprintf(stderr, "Wrong test mode request: %d\n", test_mode);
	    close (controlSock.socket);
	    exit (1);
	}

	/********** Create another TCP connection (test channel)  **********/

	if ( server_init(&testSock) == NOTOK ) {
	    if ( verbose )
		fprintf(stderr, "Server test channel initialization error. \n");
	    close (controlSock.socket);
	    exit(1);
	}

	/********* Allocate the memory for sending/receiving data **********/
	    
	if ( (rbuffer = (char *)malloc(testSock.dataSize)) == NULL ||
	     (sbuffer = (char *)malloc(testSock.dataSize)) == NULL ) {
	    if ( verbose )
		fprintf(stderr, "Could not malloc memory! buffer size: %lld\n", size);
	    close (controlSock.socket);
	    exit(1);
	}    
	    
	/**** Randomize the buffer to prevent possible data compression ****/
	    
	srand(time(NULL));
	for ( ptr = (short *)sbuffer; ptr < (short *)(sbuffer+testSock.dataSize); 
	      ptr +=2 )
	    *ptr = (short)rand();   

	
	/******** Inform client the test channel's port number *************/
	
	sprintf(buff, server_port_str, testSock.port);
	if ( send_request(controlSock.socket, buff, strlen(buff)) == NOTOK ) {
	    if ( verbose )
		fprintf(stderr, "Send TCP test port number error.\n");
	    close_session();
	}

	/************ Accept (establish) the test connection ***************/
	
	if ( server_get_connection(&testSock, &sin_addr) == NOTOK ) {
	    fprintf(stderr, "Server test channel getting connection error.\n");
	    close_session();
	}
	close(testSock.welcomeSocket); // Close test channel's welcome socket


	/*********** Inform client the server's network settings ***********/

	sprintf(buff, server_parameter_str, testSock.blocking, testSock.delay,
		testSock.cork, testSock.recvBuf, testSock.sendBuf, testSock.mss, 
		testSock.tos, CPUoption);
	if ( send_request(controlSock.socket, buff, strlen(buff)) == NOTOK ) {
	    if ( verbose )
		fprintf(stderr, "Failed to send server's configuration.\n");
	    close_session();
	}

	/********** Send syslog to client if the option is defined *********/

	if ( CPUoption ) {
	    bzero(sysbuff, 2*BUFLEN);
	    if ( sysinfo_to_string(&sysinfo, sysbuff, 2*BUFLEN) == NOTOK ||
		 send_request(controlSock.socket, sysbuff, strlen(sysbuff)) == NOTOK ) {
		if ( verbose )
		    fprintf(stderr, "Failed to send system initial information.\n");
		close_session();
	    }
	}		
	
	/*********** Print out the connection message **********************/

	if ( verbose ) {
	    get_local_time(buff, BUFLEN);
	    fprintf(stderr, "Session[%d] started at [%s]:\n", (int)getpid(), buff);
	    if ( (hp=gethostbyaddr((char *)&sin_addr, sizeof(sin_addr), AF_INET)) )
		fprintf(stderr, "Connection from %s [%s] ", 
			hp->h_name, inet_ntoa(sin_addr));
	    else        // Host not in the host tables or DNS
		fprintf(stderr, "Connection from [%s] ", inet_ntoa(sin_addr));

	    if ( test_mode == SENDFILE )
		strcpy(buff, "Throughput test with sendfile");
	    else 
		strcpy(buff, test_mode == LATENCY ? "Latency(RTT) test":"Throughput test");
	    fprintf(stderr, "[%s] [%s]\n", buff, stream_mode ? "Unidirectional":"Bidirectional");

	    fprintf(stderr, "%s %s %s ", testSock.blocking ? "Blocking[ON]":"Blocking[OFF]", 
		    testSock.delay ? "TCP_NODELAY[OFF]":"TCP_NODELAY[ON]",
		    testSock.cork ? "TCP_CORK[ON]":"TCP_CORK[OFF]");
	    fprintf(stderr, "Recv-buff[%d] Send-buff[%d] MSS[%d]\n", 
		    testSock.recvBuf, testSock.sendBuf, testSock.mss);
	}
	
	/** Set a timer in case of communication abnormally disconnected ***/
	
	if ( signal(SIGALRM, time_out_handler) == SIG_ERR ) {
	    if ( verbose )
		perror("Signal alarm.");
	    close_session();
	}
	
	if ( setjmp(alarm_env) != 0 ) {
	    if ( verbose )
		fprintf(stderr, "Connection lost.\n");
	    close_session();
	}
	
	alarm (5);
	
	/********** TCP test channel waiting for  a request ****************/
	
	while ( get_request(&controlSock, buff) == OK ) {
	    
	    alarm(0);  // Cancel timer
	    
	    /********************** parse client's request *****************/

	    if ( sscanf(buff, test_start_str, &size, &iteration) != 2) {
		
		/************************* Session ends ********************/
		
		if ( strncmp(buff, test_done_str, strlen(test_done_str)) == 0 ) {
		    if ( test_mode != LATENCY && CPUoption ) {
			if ( start_trace_system(&sysinfo) == OK ) {
			    sleep(1);
			    bzero(buff, BUFLEN);
			    if ( stop_trace_system(&sysinfo) == OK &&
				 sysinfo_to_string( &sysinfo, sysbuff, 2*BUFLEN ) == OK &&
				 send_request(controlSock.socket, sysbuff, strlen(sysbuff)) == OK ) {
				if ( verbose ) {
				    get_local_time(buff, BUFLEN);
				    fprintf(stderr, "Session[%d] ended at [%s].\n", (int)getpid(), buff);
				}
				close_session();
			    }
			}
			if ( verbose )
			    fprintf(stderr, "Failed to send the last syslog.\n");
		    }
		    if ( verbose ) {
			get_local_time(buff, BUFLEN);
			fprintf(stderr, "Session[%d] ended at [%s].\n", (int)getpid(), buff);
		    }
		    close_session();
		} else if ( verbose ) 
		    fprintf(stderr, "Wrong format. Unable to parse request: %s", buff);
		close_session();
	    }
	    
	    /************** Are request number acceptable? *****************/
	    
	    if ( size < 1 || iteration < 1 ) {
		if ( verbose )
		    fprintf(stderr, "Client's request is not acceptable...\n");
		close_session();
	    }
  
	    if ( CPUoption ) {
		if( start_trace_system( &sysinfo ) == NOTOK ) {
		    if ( verbose )
			fprintf(stderr, "Trace system information error.\n");
		    close_session();
		}
	    }

	    if ( test_mode != LATENCY )
		start_trace_process( &proinfo );

	    if ( (server_tcp_test(size, iteration, stream_mode, &elapsedTime, 
				  &testSock)) == NOTOK ) {
		if ( verbose )
		    fprintf(stderr, "TCP test error. Quit the session.\n");
		close_session();
	    } else {  
		if ( test_mode != LATENCY )
		    stop_trace_process( &proinfo ); // Stop tracing process info

		if ( CPUoption ) { // Stop tracing system info
		    usleep(1000);  // Wait for a while for the data to be updated
		    if ( stop_trace_system ( &sysinfo ) == NOTOK ) {
			if ( verbose )
			    fprintf(stderr, "Failed to get system information.\n");
		    }
		}
		    
		strcpy(buff, test_done_str); // Send a confirmation to client
		if ( send_request(controlSock.socket, buff, strlen(buff)) == NOTOK ) {
		    if ( verbose )
			fprintf(stderr, "Failed to send confirmation error\n");
		    close_session();
		}
		
		if ( test_mode != LATENCY ) { // Send the process inforamtion
		    sprintf(buff, server_proinfo_str, elapsedTime, 
			    proinfo.utime_sec*1000000LL + proinfo.utime_usec,
			    proinfo.stime_sec*1000000LL + proinfo.stime_usec);

		    if ( send_request(controlSock.socket, buff, strlen(buff)) == NOTOK ) {
			if ( verbose )
			    fprintf(stderr, "Failed to send process info error\n");
			close_session();
		    }		       
		}

		if ( CPUoption ) { // Send client the system information if defined
		    if ( sysinfo_to_string( &sysinfo, sysbuff, 2*BUFLEN) == NOTOK ||
			 send_request(controlSock.socket, sysbuff, strlen(sysbuff)) == NOTOK ) {
			if ( verbose )
			    fprintf(stderr, "Failed to send system information.\n");
			close_session();
		    }
		}
	    }
	    
#ifdef DEBUG
	    fprintf(stderr, " DEBUG: Test done in %s mode. Message size: %lld  Repeats: %d \n", 
		    stream_mode ? "stream":"ping-pong", size, iteration);
	    if ( elapsedTime > 0 ) 
		fprintf(stderr, " DEBUG: Total transimitted %lld bytes in %f seconds. Network throughput : %f Mbps\n\n",
			stream_mode? size*iteration : size*2*iteration, elapsedTime/1000000.0, stream_mode ? 
			size*iteration*8.0/elapsedTime : size*iteration*2*8.0/elapsedTime ); 
#endif

	} // while loop of get_request
	close_session();
	     
    } // while loop of get_connection

    /*********************** clean up the connections. *********************/

    server_shutdown();
    return 0;

}
示例#19
0
int32_t
main(int32_t argc, char *argv[])
{
	struct bthid_server	 srv;
	struct sigaction	 sa;
	char const		*pid_file = BTHIDD_PIDFILE;
	char			*ep;
	int32_t			 opt, detach, tval;

	memset(&srv, 0, sizeof(srv));
	memset(&srv.bdaddr, 0, sizeof(srv.bdaddr));
	detach = 1;
	tval = 10; /* sec */

	while ((opt = getopt(argc, argv, "a:c:dH:hp:t:")) != -1) {
		switch (opt) {
		case 'a': /* BDADDR */
			if (!bt_aton(optarg, &srv.bdaddr)) {
				struct hostent  *he;

				if ((he = bt_gethostbyname(optarg)) == NULL)
					errx(1, "%s: %s", optarg, hstrerror(h_errno));

				memcpy(&srv.bdaddr, he->h_addr, sizeof(srv.bdaddr));
			}
			break;
			
		case 'c': /* config file */
			config_file = optarg;
			break;

		case 'd': /* do not detach */
			detach = 0;
			break;

		case 'H': /* hids file */
			hids_file = optarg;
			break;

		case 'p': /* pid file */
			pid_file = optarg;
			break;

		case 't': /* rescan interval */
			tval = strtol(optarg, (char **) &ep, 10);
			if (*ep != '\0' || tval <= 0)
				usage();
			break;

		case 'h':
		default:
			usage();
			/* NOT REACHED */
		}
	}

	openlog(BTHIDD_IDENT, LOG_PID|LOG_PERROR|LOG_NDELAY, LOG_USER);

	/* Become daemon if required */
	if (detach && daemon(0, 0) < 0) {
		syslog(LOG_CRIT, "Could not become daemon. %s (%d)",
			strerror(errno), errno);
		exit(1);
	}

	/* Install signal handler */
	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = sighandler;

	if (sigaction(SIGTERM, &sa, NULL) < 0 ||
	    sigaction(SIGHUP, &sa, NULL) < 0 ||
	    sigaction(SIGINT, &sa, NULL) < 0) {
		syslog(LOG_CRIT, "Could not install signal handlers. %s (%d)",
			strerror(errno), errno);
		exit(1);
	}

	sa.sa_handler = SIG_IGN;
	if (sigaction(SIGPIPE, &sa, NULL) < 0) {
		syslog(LOG_CRIT, "Could not install signal handlers. %s (%d)",
			strerror(errno), errno);
		exit(1);
	}

	sa.sa_handler = SIG_IGN;
	sa.sa_flags = SA_NOCLDSTOP|SA_NOCLDWAIT;
	if (sigaction(SIGCHLD, &sa, NULL) < 0) {
		syslog(LOG_CRIT, "Could not install signal handlers. %s (%d)",
			strerror(errno), errno);
		exit(1);
	}

	if (read_config_file() < 0 || read_hids_file() < 0 ||
	    server_init(&srv) < 0 || write_pid_file(pid_file) < 0)
		exit(1);

	for (done = 0; !done; ) {
		if (elapsed(tval))
			client_rescan(&srv);

		if (server_do(&srv) < 0)
			break;
	}

	server_shutdown(&srv);
	remove_pid_file(pid_file);
	clean_config();
	closelog();

	return (0);
}
示例#20
0
文件: server.c 项目: jonsafari/mocp
/* Handle incoming connections */
void server_loop ()
{
	struct sockaddr_un client_name;
	socklen_t name_len = sizeof (client_name);

	logit ("MOC server started, pid: %d", getpid());

	assert (server_sock != -1);

	log_circular_start ();

	do {
		int res;
		fd_set fds_write, fds_read;

		FD_ZERO (&fds_read);
		FD_ZERO (&fds_write);
		FD_SET (server_sock, &fds_read);
		FD_SET (wake_up_pipe[0], &fds_read);
		add_clients_fds (&fds_read, &fds_write);

		res = 0;
		if (!server_quit)
			res = select (max_fd(server_sock)+1, &fds_read,
					&fds_write, NULL, NULL);

		if (res == -1 && errno != EINTR && !server_quit)
			fatal ("select() failed: %s", xstrerror (errno));

		if (!server_quit && res >= 0) {
			if (FD_ISSET(server_sock, &fds_read)) {
				int client_sock;

				debug ("accept()ing connection...");
				client_sock = accept (server_sock,
					(struct sockaddr *)&client_name,
					&name_len);

				if (client_sock == -1)
					fatal ("accept() failed: %s", xstrerror (errno));
				logit ("Incoming connection");
				if (!add_client(client_sock))
					busy (client_sock);
			}

			if (FD_ISSET(wake_up_pipe[0], &fds_read)) {
				int w;

				logit ("Got 'wake up'");

				if (read(wake_up_pipe[0], &w, sizeof(w)) < 0)
					fatal ("Can't read wake up signal: %s", xstrerror (errno));
			}

			send_events (&fds_write);
			handle_clients (&fds_read);
		}

		if (server_quit)
			logit ("Exiting...");

	} while (!server_quit);

	log_circular_log ();
	log_circular_stop ();

	close_clients ();
	clients_cleanup ();
	close (server_sock);
	server_sock = -1;
	server_shutdown ();
}
示例#21
0
/**
 * TERM
 * negative return code (rc) will terminate current session! */
int handleTERM(sessionid_t sessionid, bus_t bus, char *device,
               char *parameter, char *reply)
{
    struct timeval akt_time;
    int rc = SRCP_UNSUPPORTEDDEVICEGROUP;
    *reply = 0x00;

    if (bus_has_devicegroup(bus, DG_GL)
        && strncasecmp(device, "GL", 2) == 0) {
        long int addr = 0;
        int nelem = 0;
        if (strlen(parameter) > 0)
            nelem = sscanf(parameter, "%ld", &addr);
        if (nelem == 1) {
            sessionid_t lockid;
            cacheGetLockGL(bus, addr, &lockid);
            if (lockid == 0) {
                rc = cacheTermGL(bus, addr);
            }
            else if (lockid == sessionid) {
                if (SRCP_OK == cacheUnlockGL(bus, addr, sessionid))
                    rc = cacheTermGL(bus, addr);
            }
            else {
                rc = SRCP_DEVICELOCKED;
            }
        }
    }
    else if (bus_has_devicegroup(bus, DG_GA)
             && strncasecmp(device, "GA", 2) == 0) {
        long int addr = 0;
        int nelem = 0;
        if (strlen(parameter) > 0)
            nelem = sscanf(parameter, "%ld", &addr);
        if (nelem == 1) {
            sessionid_t lockid;
            getlockGA(bus, addr, &lockid);
            if (lockid == 0) {
                rc = termGA(bus, addr);
            }
            else if (lockid == sessionid) {
                if (SRCP_OK == unlockGA(bus, addr, sessionid))
                    rc = termGA(bus, addr);
            }
            else {
                rc = SRCP_DEVICELOCKED;
            }
        }
    }
    else if (bus_has_devicegroup(bus, DG_LOCK)
             && strncasecmp(device, "LOCK", 4) == 0) {
        long int addr;
        char devgrp[10];
        int nelem = -1;
        if (strlen(parameter) > 0)
            nelem = sscanf(parameter, "%s %ld", devgrp, &addr);

        if (nelem <= 1) {
            rc = SRCP_LISTTOOSHORT;
        }
        else {
            rc = SRCP_UNSUPPORTEDDEVICE;
            if (strncmp(devgrp, "GL", 2) == 0) {
                rc = cacheUnlockGL(bus, addr, sessionid);
            }
            else if (strncmp(devgrp, "GA", 2) == 0) {
                rc = unlockGA(bus, addr, sessionid);
            }
        }
    }

    else if (bus_has_devicegroup(bus, DG_POWER)
             && strncasecmp(device, "POWER", 5) == 0) {
        rc = termPower(bus);
    }

    else if (bus_has_devicegroup(bus, DG_SERVER)
             && strncasecmp(device, "SERVER", 6) == 0) {
        rc = SRCP_OK;
        server_shutdown();
    }

    else if (bus_has_devicegroup(bus, DG_SESSION)
             && strncasecmp(device, "SESSION", 7) == 0) {
        sessionid_t termsession = 0;
        int nelem = 0;
        if (strlen(parameter) > 0)
            nelem = sscanf(parameter, "%ld", &termsession);
        if (nelem <= 0)
            termsession = sessionid;
        rc = termSESSION(bus, sessionid, termsession, reply);
    }

    else if (bus_has_devicegroup(bus, DG_SM)
             && strncasecmp(device, "SM", 2) == 0) {
        rc = infoSM(bus, TERM, 0, -1, 0, 0, 0, reply);
    }

    else if (bus_has_devicegroup(bus, DG_TIME)
             && strncasecmp(device, "TIME", 4) == 0) {
        rc = termTIME();
    }

    gettimeofday(&akt_time, NULL);
    srcp_fmt_msg(abs(rc), reply, akt_time);
    return rc;
}
示例#22
0
/*
 * Serve DNS requests.
 */
void
server_child(struct nsd *nsd)
{
	size_t i;
	region_type *server_region = region_create(xalloc, free);
	netio_type *netio = netio_create(server_region);
	netio_handler_type *tcp_accept_handlers;
	query_type *udp_query;
	sig_atomic_t mode;

	assert(nsd->server_kind != NSD_SERVER_MAIN);
	DEBUG(DEBUG_IPC, 2, (LOG_INFO, "child process started"));

	if (!(nsd->server_kind & NSD_SERVER_TCP)) {
		close_all_sockets(nsd->tcp, nsd->ifs);
	}
	if (!(nsd->server_kind & NSD_SERVER_UDP)) {
		close_all_sockets(nsd->udp, nsd->ifs);
	}

	if (nsd->this_child && nsd->this_child->parent_fd != -1) {
		netio_handler_type *handler;

		handler = (netio_handler_type *) region_alloc(
			server_region, sizeof(netio_handler_type));
		handler->fd = nsd->this_child->parent_fd;
		handler->timeout = NULL;
		handler->user_data = (struct ipc_handler_conn_data*)region_alloc(
			server_region, sizeof(struct ipc_handler_conn_data));
		((struct ipc_handler_conn_data*)handler->user_data)->nsd = nsd;
		((struct ipc_handler_conn_data*)handler->user_data)->conn =
			xfrd_tcp_create(server_region);
		handler->event_types = NETIO_EVENT_READ;
		handler->event_handler = child_handle_parent_command;
		netio_add_handler(netio, handler);
	}

	if (nsd->server_kind & NSD_SERVER_UDP) {
		udp_query = query_create(server_region,
			compressed_dname_offsets, compression_table_size);

		for (i = 0; i < nsd->ifs; ++i) {
			struct udp_handler_data *data;
			netio_handler_type *handler;

			data = (struct udp_handler_data *) region_alloc(
				server_region,
				sizeof(struct udp_handler_data));
			data->query = udp_query;
			data->nsd = nsd;
			data->socket = &nsd->udp[i];

			handler = (netio_handler_type *) region_alloc(
				server_region, sizeof(netio_handler_type));
			handler->fd = nsd->udp[i].s;
			handler->timeout = NULL;
			handler->user_data = data;
			handler->event_types = NETIO_EVENT_READ;
			handler->event_handler = handle_udp;
			netio_add_handler(netio, handler);
		}
	}

	/*
	 * Keep track of all the TCP accept handlers so we can enable
	 * and disable them based on the current number of active TCP
	 * connections.
	 */
	tcp_accept_handlers = (netio_handler_type *) region_alloc(
		server_region, nsd->ifs * sizeof(netio_handler_type));
	if (nsd->server_kind & NSD_SERVER_TCP) {
		for (i = 0; i < nsd->ifs; ++i) {
			struct tcp_accept_handler_data *data;
			netio_handler_type *handler;

			data = (struct tcp_accept_handler_data *) region_alloc(
				server_region,
				sizeof(struct tcp_accept_handler_data));
			data->nsd = nsd;
			data->socket = &nsd->tcp[i];
			data->tcp_accept_handler_count = nsd->ifs;
			data->tcp_accept_handlers = tcp_accept_handlers;

			handler = &tcp_accept_handlers[i];
			handler->fd = nsd->tcp[i].s;
			handler->timeout = NULL;
			handler->user_data = data;
			handler->event_types = NETIO_EVENT_READ | NETIO_EVENT_ACCEPT;
			handler->event_handler = handle_tcp_accept;
			netio_add_handler(netio, handler);
		}
	}

	/* The main loop... */
	while ((mode = nsd->mode) != NSD_QUIT) {
		if(mode == NSD_RUN) nsd->mode = mode = server_signal_mode(nsd);

		/* Do we need to do the statistics... */
		if (mode == NSD_STATS) {
#ifdef BIND8_STATS
			/* Dump the statistics */
			bind8_stats(nsd);
#else /* !BIND8_STATS */
			log_msg(LOG_NOTICE, "Statistics support not enabled at compile time.");
#endif /* BIND8_STATS */

			nsd->mode = NSD_RUN;
		}
		else if (mode == NSD_REAP_CHILDREN) {
			/* got signal, notify parent. parent reaps terminated children. */
			if (nsd->this_child->parent_fd != -1) {
				sig_atomic_t parent_notify = NSD_REAP_CHILDREN;
				if (write(nsd->this_child->parent_fd,
				    &parent_notify,
				    sizeof(parent_notify)) == -1)
				{
					log_msg(LOG_ERR, "problems sending command from %d to parent: %s",
						(int) nsd->this_child->pid, strerror(errno));
				}
			} else /* no parent, so reap 'em */
				while (waitpid(0, NULL, WNOHANG) > 0) ;
			nsd->mode = NSD_RUN;
		}
		else if(mode == NSD_RUN) {
			/* Wait for a query... */
			if (netio_dispatch(netio, NULL, NULL) == -1) {
				if (errno != EINTR) {
					log_msg(LOG_ERR, "netio_dispatch failed: %s", strerror(errno));
					break;
				}
			}
		} else if(mode == NSD_QUIT) {
			/* ignore here, quit */
		} else {
			log_msg(LOG_ERR, "mode bad value %d, back to service.",
				mode);
			nsd->mode = NSD_RUN;
		}
	}

#ifdef	BIND8_STATS
	bind8_stats(nsd);
#endif /* BIND8_STATS */

	namedb_fd_close(nsd->db);
	region_destroy(server_region);
	server_shutdown(nsd);
}
/* main transaction thread recieve loop */
void* tx_worker_thread(void* params) 
{
    worker_state_t* wstate = (worker_state_t*)params;

    printf("Started TM thread: (%s:%d)\n", wstate->tm_host, wstate->tm_port);

    int bytes = 0;
    int running = true;
    struct sockaddr_in recv_addr;
    message_t msg;

    /* if uncertain, wait */
    if (wstate->uncertain) {
        tx_worker_uncertain(wstate);
        /* we're not actually gonna go into the transaction loop,
         * we just need an update on the current transaction */
        running = false;
    }

    while(running) 
    {
        bytes = server_recv(wstate->server, &msg, &recv_addr); 
        if (bytes <= 0)
            continue;

        /* delay function */
        if (wstate->delay != 0 && wstate->delay != -1000) {
            int sleep_time = abs(wstate->delay);
            sleep(sleep_time);
        }

        /* update vector clock */
        vclock_update(wstate->node_id, wstate->vclock, msg.vclock);
        vclock_increment(wstate->node_id, wstate->vclock);
        txlog_write_clock(wstate->txlog, wstate->vclock);
        
        switch(msg.type)
        {
            case PREPARE_TO_COMMIT: {
                message_t vote;
                message_init(&vote, wstate->vclock);
                vote.tid = wstate->transaction;

                /* vote commit? */
                if (wstate->do_commit) {
                    vote.type = PREPARED;
                    shitviz_append(wstate->node_id, "Voting COMMIT", wstate->vclock);

                    /* log prepared */
                    txlog_entry_t entry;
                    txentry_init(&entry, LOG_PREPARED, wstate->transaction, wstate->vclock);
                    txlog_append(wstate->txlog, &entry);

                    /* negative delay crash */
                    if (wstate->delay < 0) exit(1);

                    server_send_to(wstate->server, wstate->tm_host, wstate->tm_port, &vote);

                    /* we're uncertain! force wait for a reply */
                    wstate->uncertain = true;
                    tx_worker_uncertain(wstate);

                    /* this transaction is finished as soon as we get a reply */
                    running = false;
                    break;
                }

                /* vote abort? */
                if (wstate->do_abort) {
                    vote.type = ABORT;
                    shitviz_append(wstate->node_id, "Voting ABORT", wstate->vclock);

                    /* reset state */
                    wstate->do_abort = false;
                    wstate->do_commit = true;

                    /* negative delay crash */
                    if (wstate->delay < 0) exit(1);

                    server_send_to(wstate->server, wstate->tm_host, wstate->tm_port, &vote);

                    /* we're uncertain! force wait for a reply */
                    wstate->uncertain = true;
                    tx_worker_uncertain(wstate);

                    /* this transaction is finished as soon as we get a reply */
                    running = false;
                    break;
                }

                shitviz_append(wstate->node_id, "Dunno what to do for PREPARE :(", wstate->vclock);
                break;
            }

            case TX_ERROR: {
                char err_buff[512];
                sprintf(err_buff, "Manager Error: %s", msg.strdata);
                shitviz_append(wstate->node_id, err_buff, wstate->vclock);

                /* if value=1 then exit the transaction thread */
                if (msg.value) 
                    running = false;
                break;
            }

            case COMMIT: {
                /* log commit etc */
                shitviz_append(wstate->node_id, "Commit", wstate->vclock);

                txlog_entry_t entry;
                txentry_init(&entry, LOG_COMMIT, wstate->transaction, wstate->vclock);
                txlog_append(wstate->txlog, &entry);

                running = false;
                break;
            }

            case ABORT: {
                /* log abort */
                shitviz_append(wstate->node_id, "Abort", wstate->vclock);

                /* roll back */
                update_rollback(wstate);

                running = false;
                break;
            }

            default:
                shitviz_append(wstate->node_id, "Unknown command", wstate->vclock);
                break;
        }
    }
    
    /* clean up */
    printf("Exiting transaction thread\n");
    server_shutdown(&wstate->server);
    wstate->is_active = false;
    return NULL;
}
示例#24
0
int
main(int argc, char *argv[])
{
	server_t		 server;
	char const		*control = SDP_LOCAL_PATH;
	char const		*user = "******", *group = "_sdpd";
	char const		*sgroup = NULL;
	int32_t			 detach = 1, opt;
	struct sigaction	 sa;

	while ((opt = getopt(argc, argv, "c:dG:g:hu:")) != -1) {
		switch (opt) {
		case 'c': /* control */
			control = optarg;
			break;

		case 'd': /* do not detach */
			detach = 0;
			break;

		case 'G': /* super group */
			sgroup = optarg;
			break;

		case 'g': /* group */
			group = optarg;
			break;

		case 'u': /* user */
			user = optarg;
			break;

		case 'h':
		default:
			usage();
			/* NOT REACHED */
		}
	}

	log_open(SDPD, !detach);

	/* Become daemon if required */
	if (detach && daemon(0, 0) < 0) {
		log_crit("Could not become daemon. %s (%d)",
			strerror(errno), errno);
		exit(1);
	}

	/* Set signal handlers */
	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = sighandler;

	if (sigaction(SIGTERM, &sa, NULL) < 0 ||
	    sigaction(SIGHUP,  &sa, NULL) < 0 ||
	    sigaction(SIGINT,  &sa, NULL) < 0) {
		log_crit("Could not install signal handlers. %s (%d)",
			strerror(errno), errno);
		exit(1);
	}

	sa.sa_handler = SIG_IGN;
	if (sigaction(SIGPIPE, &sa, NULL) < 0) {
		log_crit("Could not install signal handlers. %s (%d)",
			strerror(errno), errno);
		exit(1);
	}

	/* Initialize server */
	if (server_init(&server, control, sgroup) < 0)
		exit(1);

	if ((user != NULL || group != NULL) && drop_root(user, group) < 0)
		exit(1);

	for (done = 0; !done; ) {
		if (server_do(&server) != 0)
			done ++;
	}

	server_shutdown(&server);
	log_close();

	return (0);
}
示例#25
0
	EventManger::~EventManger()
	{
		server_shutdown(_mgr);
	}
示例#26
0
文件: main.c 项目: atrinik/atrinik
/**
 * The main function.
 * @param argc
 * Number of arguments.
 * @param argv
 * Arguments.
 * @return
 * 0.
 */
int main(int argc, char **argv)
{
#ifdef WIN32
    /* Open all files in binary mode by default. */
    _set_fmode(_O_BINARY);
#endif

    init(argc, argv);
    memset(&marker, 0, sizeof(struct obj));

    if (settings.plugin_unit_tests) {
        LOG(INFO, "Running plugin unit tests...");
        object *activator = player_get_dummy(PLAYER_TESTING_NAME1, NULL);
        object *me = player_get_dummy(PLAYER_TESTING_NAME2, NULL);
        trigger_unit_event(activator, me);

        if (!settings.unit_tests) {
            cleanup();
            exit(0);
        }
    }

    if (settings.unit_tests) {
#ifdef HAVE_CHECK
        LOG(INFO, "Running unit tests...");
        cleanup();
        check_main(argc, argv);
        exit(0);
#else
        LOG(ERROR, "Unit tests have not been compiled, aborting.");
        exit(1);
#endif
    }

    atexit(cleanup);

    if (settings.world_maker) {
#ifdef HAVE_WORLD_MAKER
        LOG(INFO, "Running the world maker...");
        world_maker();
        exit(0);
#else
        LOG(ERROR, "Cannot run world maker; server was not compiled with libgd, exiting...");
        exit(1);
#endif
    }

    if (!settings.no_console) {
        console_start_thread();
    }

    process_delay = 0;

    LOG(INFO, "Server ready. Waiting for connections...");

    for (; ; ) {
        if (unlikely(shutdown_timer_check())) {
            break;
        }

        console_command_handle();
        socket_server_process();

        if (++process_delay >= max_time_multiplier) {
            process_delay = 0;
            main_process();
        }

        socket_server_post_process();

        /* Sleep proper amount of time before next tick */
        sleep_delta();
    }

    server_shutdown();

    return 0;
}
示例#27
0
文件: signals.c 项目: hyper/rq
//-----------------------------------------------------------------------------
// When the SIGINT signal is received, we need to start shutting down the
// service.  This means that it needs to:
//   1.  Close the listening socket.
//   2.  Send a CLOSING message to every connected node.
//   3.  if there are any undelivered messages in the queues, we need to return them.
//   4.  Shutdown the nodes if we can.
//   5.  Shutdown the queues if we can.
//   6.  Tell the stats system to close its event as soon as there are no more nodes connected.
void sigint_handler(evutil_socket_t fd, short what, void *arg)
{
	system_data_t *sysdata = (system_data_t *) arg;
	server_t *server;
	stats_t *stats;
	queue_t *q;
	node_t *node;
	controller_t *ct;
	
	logger(sysdata->logging, 3, "SIGINT");

	assert(sysdata);
	assert(sysdata->servers);

	// delete the sigint event, we dont need it anymore.
	assert(sysdata->sigint_event);
	event_free(sysdata->sigint_event);
	sysdata->sigint_event = NULL;

	// delete the sighup event, we dont need that either.
	assert(sysdata->sighup_event);
	event_free(sysdata->sighup_event);
	sysdata->sighup_event = NULL;

	// delete the sigusr1 event, we dont need that either.
	assert(sysdata->sigusr1_event);
	event_free(sysdata->sigusr1_event);
	sysdata->sigusr1_event = NULL;

	// delete the sigusr2 event, we dont need that either.
	assert(sysdata->sigusr2_event);
	event_free(sysdata->sigusr2_event);
	sysdata->sigusr2_event = NULL;

	logger(sysdata->logging, 2, "Shutting down servers.");
	while ((server = ll_pop_head(sysdata->servers))) {
		server_shutdown(server);
		server_free(server);
		free(server);
	}

	// All active nodes should be informed that we are shutting down.
	logger(sysdata->logging, 2, "Shutting down nodes.");
	assert(sysdata->nodelist);
	ll_start(sysdata->nodelist);
	while ((node = ll_next(sysdata->nodelist))) {
		assert(node->handle > 0);
		logger(sysdata->logging, 2, "Initiating shutdown of node %d.", node->handle);
		node_shutdown(node);
	}
	ll_finish(sysdata->nodelist);

	// Now attempt to shutdown all the queues.  Basically, this just means that the queue will close down all the 'waiting' consumers.
	logger(sysdata->logging, 2, "Initiating shutdown of queues.");
	ll_start(sysdata->queues);
	while ((q = ll_next(sysdata->queues))) {
		assert(q->name != NULL);
		assert(q->qid > 0);
		logger(sysdata->logging, 2, "Initiating shutdown of queue %d ('%s').", q->qid, q->name);
		queue_shutdown(q);
	}
	ll_finish(sysdata->queues);

	// if we have controllers that are attempting to connect, we need to change their status so that they dont.
	logger(sysdata->logging, 2, "Stopping controllers that are connecting.");
	ll_start(sysdata->controllers);
	while ((ct = ll_next(sysdata->controllers))) {
		BIT_SET(ct->flags, FLAG_CONTROLLER_FAILED);
		if (ct->connect_event) {
			event_free(ct->connect_event);
			ct->connect_event = NULL;
		}
	}
	ll_finish(sysdata->controllers);

	// Put stats event on notice that we are shutting down, so that as soon as there are no more nodes, it needs to stop its event.
	assert(sysdata != NULL);
	assert(sysdata->stats != NULL);
	stats = sysdata->stats;
	assert(stats->shutdown == 0);
	stats->shutdown ++;

	// Tell the logging system not to use events anymore.
	log_direct(sysdata->logging);
}