void server_destroy(server_t* server) { if(server->running) server_stop(server); free(server->clients); free(server); }
void sig_handler(int signo) { if(signo == SIGINT) { server_stop(&ftp_server); } }
/* funzione utilizzate per la creazione di semafori, memorie e code di messaggi. * ritorna 1 se tutte le risorse sono allocate correttamente, 0 altrimenti. */ int server_start() { log_date(LOG_PATH, "(start) Avvio server"); get_date(start_date); // Creazione di semafori, memorie e code di messaggi if ((semid = semget(SEMKEY, SEM_TOT, 0600 | IPC_CREAT)) == -1) errorlog(LOG_PATH, "Semafori non allocati"); if ((shmid = shmget(SHMKEY, sizeof(repo), 0600 | IPC_CREAT)) == -1) errorlog( LOG_PATH, "Area di memoria Repository non allocata"); if ((shmlog = shmget(BUFFER_SHMKEY, sizeof(buffer), 0600 | IPC_CREAT)) == -1) errorlog( LOG_PATH, "Area di memoria LOG non allocata"); if ((shmls = shmget(LS_SHMKEY, sizeof(numlettori), 0600 | IPC_CREAT)) == -1) errorlog( LOG_PATH, "Area di memoria LETTORI/SCRITTORI non allocata"); if ((shmauth = shmget(AUTH_SHMKEY, sizeof(auth), 0600 | IPC_CREAT)) == -1) errorlog( LOG_PATH, "Area di memoria AUTORIZZAZIONI non allocata"); if ((shmpush = shmget(PUSH_SHMKEY, sizeof(push), 0600 | IPC_CREAT)) == -1) errorlog( LOG_PATH, "Area di memoria PUSH non allocata"); if ((msgid = msgget(MSGKEY, IPC_CREAT | 0600)) == -1) errorlog(LOG_PATH, "Coda messaggi non allocata"); // Controllo errori all'avvio */ if (semid == -1 || shmid == -1 || shmlog == -1 || shmls == -1 || shmauth == -1 || shmpush == -1 || msgid == -1) server_stop(); if (!setup()) { errorlog(LOG_PATH, "(start) File del repository iniziale non trovato"); return 0; } return 1; }
int main() { //init win32 socket #ifdef __WIN32__ static WSADATA wsa_data; int result = WSAStartup((WORD)(1<<8|1), &wsa_data); //初始化WinSocket动态连接库 if( result != 0 ) // 初始化失败 return -1; #endif #ifndef __WIN32__ signal( SIGPIPE, SIG_IGN ); //ignore send,recv SIGPIPE error #endif NEW( websrv, sizeof(webserver) ); memset( websrv, 0, sizeof(webserver) ); server_create( websrv, "config.xml" ); server_start( websrv ); do_console(); server_stop( websrv ); server_end( websrv ); DEL( websrv ); #ifdef __WIN32__ WSACleanup(); #endif memory_end(); return 0; }
int socket_server_multiple_test(void) { pthread_t server_thread, timeout_thread, request_threads[20]; testserver.master = 0; testserver.max_threads = 20; testserver.kvserver.handle = &socket_server_request_handler; pthread_create(&server_thread, NULL, socket_server_run_thread, NULL); pthread_mutex_lock(&socket_server_test_lock); while (!server_running) pthread_cond_wait(&socket_server_test_cond, &socket_server_test_lock); pthread_mutex_unlock(&socket_server_test_lock); for (int i = 0; i < 20; i++) pthread_create(&request_threads[i], NULL, socket_server_request_thread, NULL); pthread_create(&timeout_thread, NULL, socket_server_timeout_thread, NULL); pthread_mutex_lock(&socket_server_test_lock); while (!complete) pthread_cond_wait(&socket_server_completion_cond, &socket_server_test_lock); pthread_cond_broadcast(&socket_server_test_cond); pthread_mutex_unlock(&socket_server_test_lock); for (int i = 0; i < 20; i++) pthread_join(request_threads[i], NULL); server_stop(&testserver); ASSERT_EQUAL(synch, 0); return 1; }
static void __stop(int unused) { #pragma ref unused static bool stopped = false; if (stopped) { return; } stopped = true; puts("Stopping morrigan."); if (input) { bdestroy(input); } net_stop(); game_stop(); server_stop(); if (l) { landscape_destroy(l); l = NULL; } }
static void sigint_cb( evutil_socket_t fd, short what, void *ctx ) { (void)fd; (void)what; (void)ctx; ED2KD_LOGNFO("caught SIGINT, terminating..."); server_stop(); }
void server_fini (void) { if (server_init_done) { server_init_done = false; server_stop(); } }
static void main_server_on_signal(int sig) { if (sig == SIGINT) { server_stop(); printf("\n"); exit(0); } }
static void hid_server_remove(struct btd_profile *p, struct btd_adapter *adapter) { server_stop(adapter_get_address(adapter)); adapters = g_slist_remove(adapters, adapter); btd_adapter_unref(adapter); }
void ox_nrmgr_delete(struct nr_mgr* self) { int i = 0; for(; i < self->reactor_num; ++i) { ox_thread_delete(self->reactors[i].thread); } i = 0; for(; i < self->reactor_num; ++i) { struct net_reactor* reactor = self->reactors+i; ox_stack_delete(reactor->waitclose_list); ox_stack_delete(reactor->waitsend_list); ox_rwlist_force_flush(reactor->free_sendmsg_list); reactor_freesendmsg_handle(reactor); ox_rwlist_delete(reactor->free_sendmsg_list); ox_rwlist_delete(reactor->logic_msglist); ox_rwlist_delete(reactor->enter_list); { struct rwlist_s* rwlist = reactor->fromlogic_rwlist; struct rwlist_msg_data* rwlist_msg = NULL; ox_rwlist_force_flush(reactor->fromlogic_rwlist); while((rwlist_msg = (struct rwlist_msg_data*)ox_rwlist_pop(rwlist, 0)) != NULL) { if(rwlist_msg->msg_type == RMT_SENDMSG) { free(rwlist_msg->data.send.data); } else if(rwlist_msg->msg_type == RMT_CLOSE) { } else if(rwlist_msg->msg_type == RMT_REQUEST_CLOSE) { } else if(rwlist_msg->msg_type == RMT_REQUEST_FREENETMSG) { free(rwlist_msg->data.free.msg); } } ox_rwlist_delete(reactor->fromlogic_rwlist); } server_stop(reactor->server); } free(self->reactors); free(self); }
/** * @brief Signal handler for server. * * @param sig - Signal No. provided by system */ void server_sig_handler(int sig) { switch(sig) { case SIGTERM: server_stop(); break; default: break; } }
static void hid_server_remove(struct btd_adapter *adapter) { bdaddr_t src; adapter_get_address(adapter, &src); server_stop(&src); adapters = g_slist_remove(adapters, adapter); btd_adapter_unref(adapter); }
/* this function will be called by the SCM to request an action */ DWORD WINAPI HandlerEx(DWORD dwControl, DWORD dwEventType, LPVOID lpEventData, LPVOID lpContext) { enum { DENY_ACTION = 0xff }; switch(dwControl) { case SERVICE_CONTROL_INTERROGATE: u_dbg("SERVICE_CONTROL_INTERROGATE" ); SetServiceStatus(ctx->hServiceStatus, &ctx->status); return NO_ERROR; case SERVICE_CONTROL_STOP: u_dbg("SERVICE_CONTROL_STOP"); if(ctx->status.dwCurrentState == SERVICE_STOPPED) return NO_ERROR; /* service already stopped */ /* start the stop procedure, move to stop_pending state */ ctx->status.dwCheckPoint = 1; ctx->status.dwWaitHint = 2000; ctx->status.dwCurrentState = SERVICE_STOP_PENDING; SetServiceStatus(ctx->hServiceStatus, &ctx->status); server_stop(ctx->server); return NO_ERROR; case SERVICE_CONTROL_PAUSE: u_dbg("SERVICE_CONTROL_PAUSE"); break; case SERVICE_CONTROL_CONTINUE: u_dbg("SERVICE_CONTROL_CONTINUE"); break; case SERVICE_CONTROL_SHUTDOWN: u_dbg("SERVICE_CONTROL_SHUTDOWN"); break; case SERVICE_CONTROL_PARAMCHANGE: u_dbg("SERVICE_CONTROL_PARAMCHANGE"); break; default: u_dbg("SERVICE_CONTROL_UNKNOWN!!!!"); } if(dwControl > 127 && dwControl < 255) { /* user defined control code */ u_dbg("SERVICE_CONTROL_USER_DEFINED"); } return ERROR_CALL_NOT_IMPLEMENTED; }
int tpcmaster_run_test(void) { setup_slaves(); pthread_t runner; pthread_create(&runner, NULL, &tpcmaster_runner, tpcmaster_test_connect); pthread_mutex_lock(&tpcmaster_lock); while (done == 0) pthread_cond_wait(&tpcmaster_cond, &tpcmaster_lock); pthread_mutex_unlock(&tpcmaster_lock); server_stop(&socket_server); cleanup_slaves(); return 1; }
void game_free(Game * game) { if (game == NULL) return; server_stop(game); g_assert(game->player_list_use_count == 0); if (game->server_port != NULL) g_free(game->server_port); params_free(game->params); g_free(game); }
int server_destroy(SERVER *sp) { server_stop(sp); pthread_attr_destroy(&sp->ca_detached); pthread_mutex_destroy(&sp->clients_mtx); pthread_cond_destroy(&sp->clients_cv); if (sp->fd >= 0) s_close(sp->fd); a_free(sp); }
/*! \brief Event loop listening for signals and remote commands. */ static void event_loop(server_t *server) { uint8_t buf[KNOT_WIRE_MAX_PKTSIZE]; size_t buflen = sizeof(buf); /* Read control socket configuration. */ conf_val_t listen_val = conf_get(conf(), C_CTL, C_LISTEN); conf_val_t rundir_val = conf_get(conf(), C_SRV, C_RUNDIR); char *rundir = conf_abs_path(&rundir_val, NULL); struct sockaddr_storage addr = conf_addr(&listen_val, rundir); free(rundir); /* Bind to control interface (error logging is inside the function. */ int remote = remote_bind(&addr); sigset_t empty; (void)sigemptyset(&empty); /* Run event loop. */ for (;;) { int ret = remote_poll(remote, &empty); /* Events. */ if (ret > 0) { ret = remote_process(server, &addr, remote, buf, buflen); if (ret == KNOT_CTL_STOP) { break; } } /* Interrupts. */ if (sig_req_stop) { break; } if (sig_req_reload) { sig_req_reload = false; server_reload(server, conf()->filename); } } server_stop(server); /* Close remote control interface. */ remote_unbind(&addr, remote); /* Wait for server to finish. */ server_wait(server); }
int main(const int argc, const char* argv[]) { struct server s; s.port = DEFAULT_PORT; // Process user arguments. process_args(&s, argv, argc); #ifdef DEBUG fprintf(stderr, "Server: Creating barber process.\n"); #endif int pid = fork(); if (pid == -1) { perror("Error while creating barber process"); return EXIT_FAILURE; } if (!pid) { // Barber (child) process. barber(); } else { // Ignore SIGCHLD. signal(SIGCHLD, SIG_IGN); // Initialize server socket and bind it. if (server_init(&s, s.port) == -1) { perror("Error while init. of server"); return EXIT_FAILURE; } printf("Server is running on port: %d\n", s.port); server_start(&s); // Run Forest, run! // Stop server, free memory and wait. server_stop(&s); } // Try removing semaphores. int semaphores = semaphores_init(getuid()); semctl(semaphores, 0, IPC_RMID, NULL); return EXIT_SUCCESS; }
// ------------------------------------ main ------------------------------------------------------------ int main(int argc, char *argv[]) { if (strcmp(argv[argc-1],"start") != 0 && strcmp(argv[argc-1],"stop") != 0) { // print help printf("Creates or controls a server on this computer at port %d\n",PORT_NUMBER); printf("Usage: mystore4 {start | stop}\n or mystore4 {portno} {start | stop}\n"); printf("For the server to process any input, precede the sent message with a \"u\""); printf("If first char is \"q\", then we're telling the server to quit\n"); printf("For any other string, server returns \"Huh?\"\n"); return 0; } if (argc == 3) portno = atoi(argv[1]); if (strcmp(argv[argc-1],"start") == 0) server_start(); else server_stop(); return 0; }
void do_console() { char buf[1024]; while(1) { scanf( "%s", buf ); if( strcmp( buf, "quit" ) == 0 ){ break; }else if( strcmp( buf, "stop" ) == 0 ){ server_stop( websrv ); }else if( strcmp( buf, "start" ) == 0 ){ server_start( websrv ); }else if( strcmp( buf, "clear" ) == 0 ){ server_clear( websrv ); }else if( strcmp( buf, "reload" ) == 0 ){ server_reload( websrv ); }else if( strcmp( buf, "print" ) == 0 ){ server_print( websrv ); memory_print(); }else{ SLEEP(3); //Temperory fixed for linux nohup! } } }
static void hid_server_remove(struct btd_profile *p, struct btd_adapter *adapter) { server_stop(adapter_get_address(adapter)); }
void WINAPI TimeServiceMain(DWORD dwArgc, LPTSTR *lpszArgv) { #ifdef _WIN64 unsigned __int64 dwCompKey = CK_SERVICECONTROL; #else DWORD dwCompKey = CK_SERVICECONTROL; #endif DWORD fdwControl = SERVICE_CONTROL_RUN; DWORD dwBytesTransferred; OVERLAPPED *po; SERVICE_STATUS ss; SERVICE_STATUS_HANDLE hSS; BOOL bPasswordCompileEmbedded = 0; // We must get the private password for connecting to this machine. // The password can be compiled into the server any of the following ways...... // 1 way - the easiest way, just uncomment and put any value between the quotes // then remove the code between --Load External Password Begin & End-- below // ***** example of very simple integrated password ******** // GString strPassword("Password"); // GString strPort("80"); // GString strRoot; // bPasswordCompileEmbedded = 1; // Another way - a most secure way to embed the password. // ***** example of integrated password ******** // GString strPassword; // MakePassword(strPassword); // Go read the MakePassword() routine above. // GString strPort("80"); // GString strRoot; // bPasswordCompileEmbedded = 1; // OR // The password can be retrieved from an external disk location. // Passwords can be obtained from disk in two different ways. // Either in a registry key matching the (probably renamed) // executable file that is this server, OR by loading a // predefined file name at a predefined location. // This file must be present while starting the server, but can be // removed once this process has fully started. // --Load External Password Begin-- GString strPassword; GString strPort; GString strRoot; if (!bPasswordCompileEmbedded) { GString strThisEXEName(GetThisEXEName()); GString strStartupKey; // use our runtime image name as the registry key char buf[512]; long lSize = sizeof(buf); if (RegQueryValue(HKEY_CLASSES_ROOT,(const char *)strThisEXEName,buf,&lSize) == ERROR_SUCCESS) { // uudecode the startup key BUFFER b; BufferInit(&b); unsigned int nDecoded; uudecode(buf, &b, &nDecoded, false); strStartupKey.write((const char *)b.pBuf,nDecoded); BufferTerminate(&b); } GString strStartupData; if (strStartupKey.Length()) { // look for a file in the root of the file system (c:\) // with the same name as this .exe GString strFile("c:\\"); strFile += strThisEXEName; // load the crypted disk file into clear text memory char *pDest; int nDestLen; GString strErrorOut; if (FileDecryptToMemory(strStartupKey, strFile, &pDest, &nDestLen, strErrorOut)) { // parse into the profile data structures pDest[7 + nDestLen] = 0; // null terminate it strStartupData.write(&pDest[7], nDestLen + 1); // and cap the GString } else { // if the file was not in the root of the file system // see if there is an environment setting directing // this server to look for the file in another location // The variable name is dynamic, matching this .exe name // and the environment variable value must be a fully // qualified path and file name to the startup file. if (getenv(strThisEXEName)) { if (FileDecryptToMemory(strStartupKey, getenv(strThisEXEName), &pDest, &nDestLen, strErrorOut)) { // parse into the profile data structures strStartupData.write(&pDest[7], nDestLen-7); } } } // parse stored settings in startup file to startup variables if (strStartupData.Length()) { GStringList lstOptions("&&",strStartupData); GStringIterator it(&lstOptions); if (it()) strPassword = it++; if (it()) strRoot = it++; // currently not used if (it()) strPort = it++; } } } // --Load External Password End-- GString strFile; GString strConfigFileDefault; GString strErrorOut; int bSetStartupFile = 0; #ifdef _WIN32 SetPriorityClass(GetCurrentProcess(),HIGH_PRIORITY_CLASS); // = 1 point above normal #endif // Create the completion port and save its handle in a global // variable so that the Handler function can access it. g_hIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, CK_PIPE, 0); // Give SCM the address of this service's Handler // NOTE: hSS does not have to be closed. hSS = RegisterServiceCtrlHandler((const char *)strServerName, TimeServiceHandler); // Do what the service should do. // Initialize the members that never change ss.dwServiceType = SERVICE_WIN32_OWN_PROCESS; ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE | SERVICE_ACCEPT_SHUTDOWN; do { switch (dwCompKey) { case CK_SERVICECONTROL: // We got a new control code ss.dwWin32ExitCode = NO_ERROR; ss.dwServiceSpecificExitCode = 0; ss.dwCheckPoint = 0; ss.dwWaitHint = 0; if (fdwControl == SERVICE_CONTROL_INTERROGATE) { SetServiceStatus(hSS, &ss); break; } // Determine which PENDING state to return if (dwSrvCtrlToPend[fdwControl] != 0) { ss.dwCurrentState = dwSrvCtrlToPend[fdwControl]; ss.dwCheckPoint = 0; ss.dwWaitHint = 500; // half a second SetServiceStatus(hSS, &ss); } switch (fdwControl) { case SERVICE_CONTROL_RUN: case SERVICE_CONTROL_CONTINUE: try { if (strRoot.Length() && strPort.Length()) { GString strCfgData; strCfgData.Format(pzBoundStartupConfig,(const char *)strRoot,(const char *)strPort); SetProfile(new GProfile((const char *)strCfgData, (int)strCfgData.Length(), 0)); if (!server_start()) { ss.dwCurrentState = SERVICE_STOPPED; ss.dwCheckPoint = ss.dwWaitHint = 0; SetServiceStatus(hSS, &ss); break; } } else { // No password compiled in - and no valid startup file found for(int i=0; i<3;i++) { // three beeps MessageBeep(0); Sleep(1000); } ss.dwCurrentState = SERVICE_STOPPED; ss.dwCheckPoint = ss.dwWaitHint = 0; SetServiceStatus(hSS, &ss); break; } } catch ( GException &) { ss.dwCurrentState = SERVICE_STOPPED; ss.dwCheckPoint = ss.dwWaitHint = 0; SetServiceStatus(hSS, &ss); break; } if (dwSrvPendToState[ss.dwCurrentState] != 0) { ss.dwCurrentState = dwSrvPendToState[ss.dwCurrentState]; ss.dwCheckPoint = ss.dwWaitHint = 0; SetServiceStatus(hSS, &ss); } break; case SERVICE_CONTROL_PAUSE: case SERVICE_CONTROL_STOP: case SERVICE_CONTROL_SHUTDOWN: server_stop(); if (dwSrvPendToState[ss.dwCurrentState] != 0) { ss.dwCurrentState = dwSrvPendToState[ss.dwCurrentState]; ss.dwCheckPoint = ss.dwWaitHint = 0; SetServiceStatus(hSS, &ss); } break; } // Determine which complete state to return break; } if (ss.dwCurrentState != SERVICE_STOPPED) { // Sleep until a control code comes in or a client connects GetQueuedCompletionStatus(g_hIOCP, &dwBytesTransferred, &dwCompKey, &po, INFINITE); fdwControl = dwBytesTransferred; } } while (ss.dwCurrentState != SERVICE_STOPPED); // Cleanup and stop this service CloseHandle(g_hIOCP); }
int main( int argc, char *argv[] ) { size_t i; int ret, opt, longIndex = 0; struct event *evsig_int; #ifdef _WIN32 WSADATA WSAData; #endif pthread_t tcp_thread, *job_threads; if ( evutil_secure_rng_init() < 0 ) { ED2KD_LOGERR("failed to seed random number generator"); return EXIT_FAILURE; } /* parse command line arguments */ opt = getopt_long( argc, argv, optString, longOpts, &longIndex ); while( opt != -1 ) { switch( opt ) { case 'v': display_version(); return EXIT_SUCCESS; case 'g': { unsigned char hash[ED2K_HASH_SIZE]; char hex_hash[sizeof(hash)*2+1]; get_random_user_hash(hash); bin2hex(hash, hex_hash, sizeof(hex_hash)); puts(hex_hash); return EXIT_SUCCESS; } case 'h': display_usage(); return EXIT_SUCCESS; default: return EXIT_FAILURE; } opt = getopt_long( argc, argv, optString, longOpts, &longIndex ); } #ifdef _WIN32 if ( 0 != WSAStartup(0x0201, &WSAData) ) { ED2KD_LOGERR("WSAStartup failed!"); return EXIT_FAILURE; } #endif if ( !server_load_config(NULL) ) { ED2KD_LOGERR("failed to load configuration file"); return EXIT_FAILURE; } display_libevent_info(); #ifdef EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED ret = evthread_use_windows_threads(); #elif EVTHREAD_USE_PTHREADS_IMPLEMENTED ret = evthread_use_pthreads(); #else #error "unable to determine threading model" #endif if ( ret < 0 ) { ED2KD_LOGERR("failed to init libevent threading model"); return EXIT_FAILURE; } g_srv.evbase_main = event_base_new(); if ( NULL == g_srv.evbase_main ) { ED2KD_LOGERR("failed to create main event loop"); return EXIT_FAILURE; } g_srv.evbase_tcp = event_base_new(); if ( NULL == g_srv.evbase_tcp ) { ED2KD_LOGERR("failed to create tcp event loop"); return EXIT_FAILURE; } evsig_int = evsignal_new(g_srv.evbase_main, SIGINT, sigint_cb, NULL); evsignal_add(evsig_int, NULL); // common timers timevals g_srv.portcheck_timeout_tv = event_base_init_common_timeout(g_srv.evbase_tcp, &g_srv.cfg->portcheck_timeout_tv); g_srv.status_notify_tv = event_base_init_common_timeout(g_srv.evbase_tcp, &g_srv.cfg->status_notify_tv); if ( !db_create() ) { ED2KD_LOGERR("failed to create database"); return EXIT_FAILURE; } g_srv.thread_count = omp_get_num_procs() + 1; pthread_cond_init(&g_srv.job_cond, NULL); pthread_mutex_init(&g_srv.job_mutex, NULL); TAILQ_INIT(&g_srv.jqueue); job_threads = (pthread_t *)malloc(g_srv.thread_count * sizeof(*job_threads)); // start tcp worker threads for ( i=0; i<g_srv.thread_count; ++i ) { pthread_create(&job_threads[i], NULL, server_job_worker, NULL); } // start tcp dispatch thread pthread_create(&tcp_thread, NULL, server_base_worker, g_srv.evbase_tcp); // start tcp listen loop if ( !server_listen() ) { ED2KD_LOGERR("failed to start server listener"); server_stop(); } pthread_join(tcp_thread, NULL); while ( EBUSY == pthread_cond_destroy(&g_srv.job_cond) ) { pthread_cond_broadcast(&g_srv.job_cond); //pthread_yield(); } pthread_mutex_destroy(&g_srv.job_mutex); for ( i=0; i<g_srv.thread_count; ++i ) { pthread_join(job_threads[i], NULL); } free(job_threads); // todo: free job queue items evconnlistener_free(g_srv.tcp_listener); event_free(evsig_int); event_base_free(g_srv.evbase_tcp); event_base_free(g_srv.evbase_main); if ( db_destroy() < 0 ) { ED2KD_LOGERR("failed to destroy database"); } server_free_config(); return EXIT_SUCCESS; }
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; }
int main(int argc, char *argv[]) { /* Richiesta di shutdown server */ if (argc > 1) if (!strcmp(argv[1], "shutdown") || !strcmp(argv[1], "-f")) shutdown(); else { printf("Errore parametro in input\n\n"); exit(0); } /* Avvio del server */ server_start(); int termina = FALSE; do { // Sono il padre if (termina && number_msges_in_queue(msgid) == 0) server_stop(); if (padre == -1) { errorlog(LOG_PATH, "Impossibile eseguire la fork"); server_stop(); } // In attesa di messaggi dal client if(msg_receive(&req, msgl, msgid, 1) < 0) { errorlog(LOG_PATH, "Impossibile ricevere messaggi"); server_stop(); } if (req.pid == -2) termina = TRUE; else { // Statistiche counter_r++; if(req.todo == M_DOWN || req.todo == M_DALL) counter_d++; else if(req.todo == M_ADD || req.todo == M_UPD) counter_u++; else if(req.todo == M_PUSH) counter_p++; else if(req.todo == M_AUTH && req.pwd != -1) //Non conto i logout counter_a++; // Fine Statistiche waitS(SEM_SERVER); //WAIT su semaforo per avere al massimo 5 figli del server padre = fork(); } } while (padre); /* Sono il figlio */ if (!padre) { // Invio di un pacchetto dal server al client if (req.todo == M_DOWN) download_one(); // Riceve un pacchetto dal client da aggiungere else if (req.todo == M_ADD) aggiungi_pkg(); // Riceve un pacchetto dal client da aggiornare else if (req.todo == M_UPD) aggiorna_pkg(); // Richiesta di tutto il repository da parte del cliente else if (req.todo == M_DALL) download_all(); // Autenticazione clienti di upload else if (req.todo == M_AUTH) autentica(); // Registrazione client push else if (req.todo == M_PUSH) registra_push(); else writebuf("(unknow)\t %d Richiesta non riconosciuta [ERRORE] \n", req.pid); //WAIT su semaforo per lasciare la possibilità ad un altro figlio del server di generarsi signalS(SEM_SERVER); } return 0; }
int main(int argc, char* args[]) { //Start up SDL and create window int screenmode = 0; if (argc > 1) { screenmode = std::stoi(args[1]); } if (!init(screenmode)) { printf("Failed to initialize!\n"); } else { Menu menu = Menu(); //Load media if (!menu.init()) { printf("Failed to load media!\n"); } else { //Main loop flag bool quit = false; int state = STATE_MENU; int mode = M_SINGLEPLAYER; rngGfx.seed(time(NULL)); glLoadIdentity(); glTranslated(-1, 1, 0); glScaled(2.0 / SCREEN_WIDTH, -2.0 / SCREEN_HEIGHT, 1.0); const Uint8 *keyboard = SDL_GetKeyboardState(NULL); //Event handler SDL_Event e; frame = 0; unsigned int endTime = SDL_GetTicks(); GameLogic g; //While application is running while (!quit) { endTime = endTime + 17; frame++; if (frame % 3 == 0) endTime--; //Handle events on queue SDL_Scancode keydown = SDL_SCANCODE_UNKNOWN; while (SDL_PollEvent(&e) != 0) { //User requests quit if (e.type == SDL_QUIT) { quit = true; } if (e.type == SDL_MOUSEMOTION) { //Get the mouse offsets mouseX = e.motion.x; mouseY = e.motion.y; if (screenmode == 1 || screenmode == 3) { mouseX /= 1.5; mouseY /= 1.5; } } if (e.type == SDL_MOUSEBUTTONDOWN || e.type == SDL_MOUSEBUTTONUP) { mouseX = e.button.x; mouseY = e.button.y; if (e.button.button == SDL_BUTTON_LEFT) clicked = (e.button.state == SDL_PRESSED); if (screenmode == 1 || screenmode == 3) { mouseX /= 1.5; mouseY /= 1.5; } } if (e.type == SDL_KEYDOWN) { keydown = e.key.keysym.scancode; } } if (keyboard[SDL_SCANCODE_ESCAPE]) { quit = true; } //Clear screen glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); switch (state) { case STATE_MENU: g = GameLogic(); g.write_other_players = SDL_CreateMutex(); mode = menu.step( mouseX, mouseY, clicked, keyboard, keydown);//returns mode if changed, 0 if no change if (mode != 0) { std::cout << mode; state = (mode == M_SERVER) ? STATE_WAIT_FOR_CLIENT : STATE_BEGINGAME; } menu.draw( mouseX, mouseY); break; case STATE_WAIT_FOR_CLIENT: uint32_t rng_seed; IPaddress ip; glColor3f(1.0f, .4f, .9f); menu.draw_text(80, 300, "Waiting for client"); menu.draw_text(180, 400, "to connect"); if (server_begin(&rng_seed, &ip)) { state = STATE_BEGINGAME; g.addOtherPlayer(100, 100, 0, ip); rngGame.seed(rng_seed); SDL_CreateThread(receive_packets, "Network", &g); } break; case STATE_BEGINGAME: if (mode == M_CLIENT) { //Client uint32_t rng_seed = time(NULL); g.addOtherPlayer(100, 100, 0, client_begin(menu.tmpip, rng_seed)); rngGame.seed(rng_seed); SDL_CreateThread(receive_packets, "Network", &g); } if (mode == M_SINGLEPLAYER) { rngGame.seed(time(NULL)); } g.rings.init(); state = STATE_GAMEPLAY;//don't break, continue directly to gameplay case STATE_GAMEPLAY: g.step(keyboard); g.draw(); if (g.rings.thisRing >= 20) { g.haveWon = g.haveWon || ((g.multiplayer && g.opponent_rings < 20) || !g.multiplayer); glColor3f(1.0f, .4f, .9f); if (g.haveWon) menu.draw_text(10, 10, "You won"); else menu.draw_text(10, 10, "You lost"); menu.draw_text(10, 110, "Time taken:"); menu.draw_text(10 + chrw * 11, 110, const_cast<char *>((std::to_string(g.timeFlying)).c_str())); menu.draw_text(10, 200, "Press Enter to return"); menu.draw_text(10, 300, "to menu"); if (keydown == SDL_SCANCODE_RETURN) { state = STATE_MENU; if (mode == M_CLIENT || mode == M_SERVER) server_stop(); } } else { glColor3f(0.0f, 1.0f, 0.0f); if (g.rings.thisRing >= 10) menu.draw_text(10, 10, const_cast<char *>((std::to_string(g.rings.thisRing)).c_str())); else menu.draw_text(10 + chrw, 10, const_cast<char *>((std::to_string(g.rings.thisRing)).c_str())); menu.draw_text(10 + 2 * chrw, 10, "/20"); glColor3f(1.0f, 0.0f, 0.0f); if (g.multiplayer) { if (g.opponent_rings >= 10) menu.draw_text(10, 30, const_cast<char *>((std::to_string(g.opponent_rings)).c_str())); else menu.draw_text(10 + chrw, 30, const_cast<char *>((std::to_string(g.opponent_rings)).c_str())); menu.draw_text(10 + 2 * chrw, 30, "/20"); } } break; } menu.drawGrid(); //Update screen SDL_GL_SwapWindow(gWindow); if (SDL_GetTicks() < endTime) { //Sleep the remaining frame time SDL_Delay(endTime-SDL_GetTicks()); } else { //std::cout << SDL_GetTicks()-endTime << "\n"; } } } } //Free resources and close SDL close(); return 0; }
static void handler(int signo) { server_stop() ; signal(signo, SIG_DFL) ; }
char *test_server_stop() { mu_assert("Stopping server", server_stop() == 0); return 0; }
static void ietadm_request_exec(struct ietadm_req *req, struct ietadm_rsp *rsp) { int err = 0; log_debug(1, "%u %u %" PRIu64 " %u %u", req->rcmnd, req->tid, req->sid, req->cid, req->lun); switch (req->rcmnd) { case C_TRGT_NEW: err = cops->target_add(&req->tid, req->u.trgt.name); break; case C_TRGT_DEL: err = cops->target_del(req->tid); break; case C_TRGT_UPDATE: if (req->u.trgt.type & (1 << key_session)) err = cops->param_set(req->tid, req->sid, key_session, req->u.trgt.session_partial, req->u.trgt.session_param); if (err < 0) goto out; if (req->u.trgt.type & (1 << key_target)) err = cops->param_set(req->tid, req->sid, key_target, req->u.trgt.target_partial, req->u.trgt.target_param); break; case C_TRGT_SHOW: err = ki->param_get(req->tid, req->sid, key_target, req->u.trgt.target_param); break; case C_SESS_NEW: case C_SESS_DEL: case C_SESS_UPDATE: break; case C_SESS_SHOW: err = ki->param_get(req->tid, req->sid, key_session, req->u.trgt.session_param); break; case C_LUNIT_NEW: err = cops->lunit_add(req->tid, req->lun, req->u.lunit.args); break; case C_LUNIT_DEL: err = cops->lunit_del(req->tid, req->lun); break; case C_LUNIT_UPDATE: case C_LUNIT_SHOW: break; case C_CONN_NEW: case C_CONN_DEL: err = ki->conn_destroy(req->tid, req->sid, req->cid); break; case C_CONN_UPDATE: case C_CONN_SHOW: break; case C_ACCT_NEW: err = cops->account_add(req->tid, req->u.acnt.auth_dir, req->u.acnt.user, req->u.acnt.pass); break; case C_ACCT_DEL: err = cops->account_del(req->tid, req->u.acnt.auth_dir, req->u.acnt.user); break; case C_ACCT_UPDATE: case C_ACCT_SHOW: break; case C_SYS_NEW: break; case C_SYS_DEL: err = server_stop(); break; case C_SYS_UPDATE: case C_SYS_SHOW: break; default: break; } out: rsp->err = err; }