void test_database_update_event() { scheduler_t* scheduler; char sql[512]; PGresult* db_result; scheduler = scheduler_init(testdb, NULL); FO_ASSERT_PTR_NULL(scheduler->db_conn); database_init(scheduler); FO_ASSERT_PTR_NOT_NULL(scheduler->db_conn); Prepare_Testing_Data(scheduler); database_update_event(scheduler, NULL); sprintf(sql, "SELECT * FROM job;"); db_result = database_exec(scheduler, sql); //printf("result: %s", PQget(db_result, 0, "job_name")); if(PQresultStatus(db_result) == PGRES_TUPLES_OK && PQntuples(db_result) != 0) { FO_ASSERT_STRING_EQUAL(PQget(db_result, 0, "job_name"), "testing file"); FO_ASSERT_EQUAL(atoi(PQget(db_result, 0, "job_user_fk")), 1); } PQclear(db_result); database_reset_queue(scheduler); scheduler_destroy(scheduler); }
int main() { database_init(3); init_db(); printf("Welcome to eCommerce v0.1\n"); while (1) { char choice = menu(); if (choice == 0) break; else if (choice == 'a') list(); else if (choice == 'b') buy(); else if (choice == 'c') sell(); else printf("Invalid selection\n"); } database_close(); return 0; }
void test_database_init() { scheduler_t* scheduler; PGresult* db_result; GString* sql; scheduler = scheduler_init(testdb, NULL); database_init(scheduler); FO_ASSERT_PTR_NOT_NULL(scheduler->db_conn); sprintf(sqltmp, check_scheduler_tables, PQdb(scheduler->db_conn)); sql = g_string_new(sqltmp); g_string_append(sql, "'users';"); /* get the url for the fossology instance */ db_result = database_exec(scheduler, sql->str); //printf("sql: %s\n", sql->str); // TODO skip this test since the order reported here is random, also it will crash if PQntuples < 5 #if 0 if(PQresultStatus(db_result) == PGRES_TUPLES_OK && PQntuples(db_result) != 0) { //printf("result: %s\n", g_strdup(PQgetvalue(db_result, 0, 0))); FO_ASSERT_STRING_EQUAL(g_strdup(PQgetvalue(db_result, 0, 0)), "user_pk"); FO_ASSERT_STRING_EQUAL(g_strdup(PQgetvalue(db_result, 1, 0)), "user_name"); FO_ASSERT_STRING_EQUAL(g_strdup(PQgetvalue(db_result, 2, 0)), "root_folder_fk"); FO_ASSERT_STRING_EQUAL(g_strdup(PQgetvalue(db_result, 3, 0)), "user_desc"); FO_ASSERT_STRING_EQUAL(g_strdup(PQgetvalue(db_result, 4, 0)), "user_seed"); } #endif PQclear(db_result); g_string_free(sql, TRUE); scheduler_destroy(scheduler); }
EAPI int eolian_init(void) { const char *log_dom = "eolian"; if (_eolian_init_counter > 0) return ++_eolian_init_counter; eina_init(); _eolian_log_dom = eina_log_domain_register(log_dom, EINA_COLOR_LIGHTBLUE); if (_eolian_log_dom < 0) { EINA_LOG_ERR("Could not register log domain: %s", log_dom); return EINA_FALSE; } eina_log_timing(_eolian_log_dom, EINA_LOG_STATE_STOP, EINA_LOG_STATE_INIT); INF("Init"); _eolian_prefix = eina_prefix_new(NULL, eolian_init, "EOLIAN", "eolian", NULL, "", "", PACKAGE_DATA_DIR, ""); if (!_eolian_prefix) { ERR("Could not initialize the Eolian prefix."); return EINA_FALSE; } database_init(); eo_lexer_init(); return ++_eolian_init_counter; }
//main函数 int main(int argc, char *argv[]){ database_init("a","a","a","a"); setlocale(LC_ALL, ""); initscr(); start_menu(); endwin(); database_close(); exit(EXIT_SUCCESS); }
void check_mainloop(void) { time_t now = 0, then = 0; useconds_t sleeptime; int delta = 0; /* init */ status_alerted.alert_load = false; status_alerted.alert_disk = false; status_alerted.alert_cpu = false; sleeptime = 100000; numcpus = num_cpus(); http_fetch_url(hburl); vbprintf("Found %d cpus\n", numcpus); database_init(); /* * XXX: Right here we're just spinning in place. The reason for this * is to be able to have different intervals for the checking process * (disk/cpu/load), and also for the heartbeat-process, which might * check at different intervals. I might separate this out into * another file so we have a rudimentary timer-based scheduler that * can shoot off different functions at variable intervals. */ time(&then); while (1) { int sampletrig = 0, hbtrig = 0; time(&now); delta = (int) now - (int) then; sampletrig = delta % interval; hbtrig = delta % hbinterval; if (!sampletrig) { load_check(); disk_check(diskpaths); cpu_check(); check_alert(); sleep(1); /* make sure trig status is over */ } if (!hbtrig) { http_fetch_url(hburl); sleep(1); /* make sure trig status is over */ } usleep(sleeptime); } }
int main(int argc, char **argv) { MalelfDissect dissect; MalelfInfect infect; Disas disas; Database database; Analyse analyse; _u8 error = MALELF_SUCCESS; if (argc == 1) { _malelf_help(); return -1; } if (strncmp(argv[1], DISSECT, sizeof(DISSECT)) == 0) { error = malelf_dissect_init(&dissect, argc, argv); malelf_dissect_finish(&dissect); } else if (strncmp(argv[1], SHELLCODE, sizeof (SHELLCODE)) == 0) { malelf_shellcode_init(argc, argv); malelf_shellcode_finish(); } else if (strncmp(argv[1], INFECT, sizeof(INFECT)) == 0) { malelf_infect_init(&infect, argc, argv); malelf_infect_finish(&infect); } else if (strncmp(argv[1], DYNAMIC_ANALYSIS, sizeof(DYNAMIC_ANALYSIS)) == 0) { malelf_dynanalyse_init(argc, argv); malelf_dynanalyse_finish(); } else if (strncmp(argv[1], DISAS, sizeof(DISAS)) == 0) { disas_init(&disas, argc, argv); disas_finish(&disas); } else if (strncmp(argv[1], DATABASE, sizeof(DATABASE)) == 0) { database_init(&database, argc, argv); database_finish(&database); } else if (strncmp(argv[1], ANALYSE, sizeof(ANALYSE)) == 0) { error = analyse_init(&analyse, argc, argv); analyse_finish(&analyse); } else if (strncmp(argv[1], "-v", 2) || strncmp(argv[1], "--version", 9)) { show_version(*argv); } else { _malelf_help(); } if (MALELF_SUCCESS != error) { if (MALELF_ERROR != error) { MALELF_PERROR(error); } return error; } return 0; }
/* * XL-COM Server main */ int main(int argc, char **argv) { pthread_t pthr_listener; pthread_t pthr_poller; pthread_t pthr_handler[NUM_THR_HANDLERS]; int i; // initialize global variables Epoll_fd = epoll_create1(0); Queue_client_requests = queue_create(); sem_init(&Sem_client_requests, 0, 0); Active_connections = avl_create(&int_comparator); pthread_mutex_init(&Active_connections_mutex, NULL); // Initialize libraries database_init(); xlcom_init(Database, Active_connections); // create handler threads for(i=0; i<NUM_THR_HANDLERS; i++) { if (pthread_create(&pthr_handler[i], NULL, thr_handler, (void*) NULL) != 0) { printf("[xlcom_server] [M] Error creating handler thread with id %d\n", i); return -1; } } // create poller thread if (pthread_create(&pthr_poller, NULL, thr_poller, (void*) NULL) != 0) { printf("[xlcom_server] [M] Error creating poller thread\n"); return -1; } // create listener thread if (pthread_create(&pthr_listener, NULL, thr_listener, (void*) NULL) != 0) { printf("[xlcom_server] [M] Error creating listener thread\n"); return -1; } printf("[xlcom_server] [M] Successful initialization.\n"); printf("[xlcom_server] [M] Created threads: [%d|handler] [%d|poller] [%d|listener]\n", NUM_THR_HANDLERS, 1, 1); // wait for thread termination pthread_join(pthr_listener, (void**) NULL); printf("[xlcom_server] [M] Listener thread exited.\n"); pthread_join(pthr_poller, (void**) NULL); printf("[xlcom_server] [M] Poller thread exited.\n"); for(i=0; i<NUM_THR_HANDLERS; i++) { pthread_join(pthr_handler[i], (void**) NULL); printf("[xlcom_server] [M] Handler thread with id %d exited.\n", i); } printf("[xlcom_server] [M] Graceful termiation. Bye!\n"); return 0; }
/** Find a database instance for name. * * If no database with this name exists, a new one is created. * * \param name name of the database to find * \return a pointer to the database */ Database* database_find (const char* name) { Database* db = first_db; while (db != NULL) { if (!strcmp(name, db->name)) { loginfo ("%s: Database already open (%d client%s)\n", name, db->ref_count, db->ref_count>1?"s":""); db->ref_count++; return db; } db = db->next; } // need to create a new one Database *self = oml_malloc(sizeof(Database)); logdebug("%s: Creating or opening database\n", name); strncpy(self->name, name, MAX_DB_NAME_SIZE); self->ref_count = 1; self->create = database_create_function (dbbackend); if (self->create (self)) { oml_free(self); return NULL; } if (database_init (self) == -1) { database_release(self); oml_free (self); return NULL; } char *start_time_str = self->get_metadata (self, "start_time"); if (start_time_str == NULL) { /* No start time: this is probably a new database */ database_hook_send_event(self, HOOK_CMD_DBCREATED); } else { database_hook_send_event(self, HOOK_CMD_DBOPENED); self->start_time = strtol (start_time_str, NULL, 0); oml_free (start_time_str); logdebug("%s: Retrieved start-time = %lu\n", name, self->start_time); } // hook this one into the list of active databases self->next = first_db; first_db = self; return self; }
void test_scheduler_sig_handle() { scheduler_t* scheduler; scheduler = scheduler_init(testdb, NULL); FO_ASSERT_PTR_NULL(scheduler->db_conn); database_init(scheduler); FO_ASSERT_PTR_NOT_NULL(scheduler->db_conn); scheduler_sig_handle(1); scheduler_signal(scheduler); scheduler_destroy(scheduler); }
//服务器端执行入口函数 int main(int argc, char*argv[]){ struct sigaction new_action, old_action; message_data message_request; new_action.sa_handler=catch_signals; sigemptyset(&new_action.sa_mask); new_action.sa_flags=0; if ((sigaction(SIGINT, &new_action, &old_action) != 0) || (sigaction(SIGHUP, &new_action, &old_action) != 0) || (sigaction(SIGTERM, &new_action, &old_action) != 0)) { fprintf(stderr, "Server startup error, signal catching failed\n"); exit(EXIT_FAILURE); } char* server_host="localhost"; char* sql_username="******"; char* sql_password="******"; char* db_name="railwaysystem"; if(!database_init(server_host, sql_username, sql_password, db_name)){ fprintf(stderr, "Server error: could not init database. \n"); sys_log("数据库连接失败."); exit(EXIT_FAILURE); } sys_log("数据库连接成功."); if(!server_start()){ sys_log("服务器启动失败."); exit(EXIT_FAILURE); } sys_log("服务器启动成功."); while(server_state){ if(read_request_from_client(&message_request)){ exec_request(message_request); }else{ if(server_state){ fprintf(stderr, "Server ended, cannot read request from message queue. \n"); sys_log("Server ended, cannot read request from message queue."); } server_state=0; } } database_close(); server_end(); sys_log("服务器关闭."); exit(EXIT_SUCCESS); }
void test_database_exec_event() { scheduler_t* scheduler; GString* sql; scheduler = scheduler_init(testdb, NULL); FO_ASSERT_PTR_NULL(scheduler->db_conn); database_init(scheduler); FO_ASSERT_PTR_NOT_NULL(scheduler->db_conn); sprintf(sqltmp, check_scheduler_tables, PQdb(scheduler->db_conn)); sql = g_string_new(sqltmp); g_string_append(sql, "'user';"); database_exec_event(scheduler, sql->str); scheduler_destroy(scheduler); }
void test_scheduler_daemonize() { scheduler_t* scheduler; int res = 0; scheduler = scheduler_init(testdb, NULL); FO_ASSERT_PTR_NULL(scheduler->db_conn); database_init(scheduler); FO_ASSERT_PTR_NOT_NULL(scheduler->db_conn); //res = scheduler_daemonize(scheduler); FO_ASSERT_EQUAL(res, 0); res = kill_scheduler(1); FO_ASSERT_EQUAL(res, -1); scheduler_destroy(scheduler); }
void test_scheduler_clear_config() { scheduler_t* scheduler; scheduler = scheduler_init(testdb, NULL); FO_ASSERT_PTR_NULL(scheduler->db_conn); database_init(scheduler); FO_ASSERT_PTR_NOT_NULL(scheduler->db_conn); scheduler_clear_config(scheduler); FO_ASSERT_PTR_NULL(scheduler->db_conn); FO_ASSERT_PTR_NULL(scheduler->host_queue); FO_ASSERT_PTR_NULL(scheduler->host_url); FO_ASSERT_PTR_NULL(scheduler->email_subject); FO_ASSERT_PTR_NULL(scheduler->sysconfig); scheduler_destroy(scheduler); }
int main(int argc, char *argv[]) { Database db; database_init(&db); if(argv[1]) { database_create(&db, argv[1]); checkDBState(&db); } else database_load(&db, DB_FILE); server(&db); return 0; }
void test_database_job() { scheduler_t* scheduler; job_t* job; arg_int* params; int jq_pk; job_t tmp_job; scheduler = scheduler_init(testdb, NULL); FO_ASSERT_PTR_NULL(scheduler->db_conn); database_init(scheduler); FO_ASSERT_PTR_NOT_NULL(scheduler->db_conn); jq_pk = Prepare_Testing_Data(scheduler); params = g_new0(arg_int, 1); params->second = jq_pk; params->first = g_tree_lookup(scheduler->job_list, ¶ms->second); job = params->first; if(params->first == NULL) { tmp_job.id = params->second; tmp_job.status = JB_NOT_AVAILABLE; tmp_job.running_agents = NULL; tmp_job.message = NULL; job = &tmp_job; } FO_ASSERT_STRING_EQUAL(job_status_strings[job->status], "JOB_NOT_AVAILABLE"); printf("jq: %d\n", jq_pk); database_job_processed(jq_pk, 2); database_job_log(jq_pk, "test log"); database_job_priority(scheduler, job, 1); g_free(params); scheduler_destroy(scheduler); }
void test_email_notify() { scheduler_t* scheduler; job_t* job; int jq_pk; scheduler = scheduler_init(testdb, NULL); FO_ASSERT_PTR_NULL(scheduler->db_conn); database_init(scheduler); email_init(scheduler); FO_ASSERT_PTR_NOT_NULL(scheduler->db_conn); jq_pk = Prepare_Testing_Data(scheduler); job = job_init(scheduler->job_list, scheduler->job_queue, "ununpack", "localhost", -1, 0, 0, 0, 0, NULL); job->id = jq_pk; database_update_job(scheduler, job, JB_FAILED); FO_ASSERT_STRING_EQUAL(job_status_strings[job->status], "JOB_CHECKEDOUT"); scheduler_destroy(scheduler); }
// Entry point // Use the program as: ./mouliserver <port> <sqlitefile> <configfile> int main(int argc, char **argv) { t_mouli mouli; if (argc != 4) { fprintf(stderr, "Usage: %s port sqlitefile configfile\n", *argv); return (1); } // Init config and database mouli_init(&mouli); if (load_config(&mouli, argv[3])) return (1); if (database_init(argv[2])) { mouli_delete(&mouli); fprintf(stderr, "%s\n", database_geterror()); return (1); } // Init network and set main loop if (setup_network(&mouli, argv[1]) || mouli_run(&mouli)) { curl_global_cleanup(); if (database_close()) fprintf(stderr, "Warning: failed to close database properly\n"); mouli_delete(&mouli); return (1); } // Global cleanup mouli_delete(&mouli); curl_global_cleanup(); if (database_close()) fprintf(stderr, "Warning: failed to close database properly\n"); return (0); }
int main(int argc, char *argv[]) { struct stat st; static int socket_serv_fd = -1; char buf[64], shell[PATH_MAX], *result, debuggable[PROPERTY_VALUE_MAX]; char enabled[PROPERTY_VALUE_MAX], build_type[PROPERTY_VALUE_MAX]; char root_settings[PROPERTY_VALUE_MAX]; int i, dballow; mode_t orig_umask; for (i = 1; i < argc; i++) { if (!strcmp(argv[i], "-c") || !strcmp(argv[i], "--command")) { if (++i < argc) { su_to.command = argv[i]; } else { usage(); } } else if (!strcmp(argv[i], "-s") || !strcmp(argv[i], "--shell")) { if (++i < argc) { strncpy(shell, argv[i], sizeof(shell)); shell[sizeof(shell) - 1] = 0; } else { usage(); } } else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--version")) { printf("%s\n", VERSION); exit(EXIT_SUCCESS); } else if (!strcmp(argv[i], "-V")) { printf("%d\n", VERSION_CODE); exit(EXIT_SUCCESS); } else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) { usage(); } else if (!strcmp(argv[i], "-") || !strcmp(argv[i], "-l") || !strcmp(argv[i], "--login")) { ++i; break; } else { break; } } if (i < argc-1) { usage(); } if (i == argc-1) { struct passwd *pw; pw = getpwnam(argv[i]); if (!pw) { su_to.uid = atoi(argv[i]); } else { su_to.uid = pw->pw_uid; } } if (from_init(&su_from) < 0) { deny(); } property_get("ro.debuggable", debuggable, "0"); property_get(ROOT_ACCESS_PROPERTY, enabled, ROOT_ACCESS_DEFAULT); property_get("ro.build.type", build_type, ""); property_get(ROOT_SETTINGS_PROPERTY, root_settings, ""); orig_umask = umask(027); // Root Settings-specific behavior if (strcmp("1", root_settings) == 0) { // only allow su on debuggable builds if (strcmp("1", debuggable) != 0) { LOGE("Root access is disabled on non-debug builds"); deny(); } // enforce persist.sys.root_access on non-eng builds if (strcmp("eng", build_type) != 0 && (atoi(enabled) & 1) != 1 ) { LOGE("Root access is disabled by system setting - enable it under settings -> developer options"); deny(); } // disallow su in a shell if appropriate if (su_from.uid == AID_SHELL && (atoi(enabled) == 1)) { LOGE("Root access is disabled by a system setting - enable it under settings -> developer options"); deny(); } } if (su_from.uid == AID_ROOT || su_from.uid == AID_SHELL) allow(shell, orig_umask); if (stat(REQUESTOR_DATA_PATH, &st) < 0) { PLOGE("stat"); deny(); } if (st.st_gid != st.st_uid) { LOGE("Bad uid/gid %d/%d for Superuser Requestor application", (int)st.st_uid, (int)st.st_gid); deny(); } if (mkdir(REQUESTOR_CACHE_PATH, 0770) >= 0) { chown(REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid); } setgroups(0, NULL); setegid(st.st_gid); seteuid(st.st_uid); LOGE("sudb - Opening database"); db = database_init(); if (!db) { LOGE("sudb - Could not open database, prompt user"); // if the database could not be opened, we can assume we need to // prompt the user dballow = DB_INTERACTIVE; } else { LOGE("sudb - Database opened"); dballow = database_check(db, &su_from, &su_to); // Close the database, we're done with it. If it stays open, // it will cause problems sqlite3_close(db); db = NULL; LOGE("sudb - Database closed"); } switch (dballow) { case DB_DENY: deny(); case DB_ALLOW: allow(shell, orig_umask); case DB_INTERACTIVE: break; default: deny(); } socket_serv_fd = socket_create_temp(); if (socket_serv_fd < 0) { deny(); } signal(SIGHUP, cleanup_signal); signal(SIGPIPE, cleanup_signal); signal(SIGTERM, cleanup_signal); signal(SIGABRT, cleanup_signal); atexit(cleanup); if (send_intent(&su_from, &su_to, socket_path, -1, 0) < 0) { deny(); } if (socket_receive_result(socket_serv_fd, buf, sizeof(buf)) < 0) { deny(); } close(socket_serv_fd); socket_cleanup(); result = buf; if (!strcmp(result, "DENY")) { deny(); } else if (!strcmp(result, "ALLOW")) { allow(shell, orig_umask); } else { LOGE("unknown response from Superuser Requestor: %s", result); deny(); } deny(); return -1; }
//there has to be a better way to do this :/ void Run(void) { char *ce; SetSig (); Banner (); if ((ce = (char *)get_config_entry("?omega", "version"))) { if (CONFIG_VERSION != atoi(ce)) { fprintf(stderr, "\033[1;31mCRITICAL\033[0m: Invalid configuration file version. [Given: %s][Required: %d]", ce, CONFIG_VERSION); Exit(0); } } else { fprintf(stderr, "\033[1;31mERROR\033[0m: Unable to determine the configuration file version. Please make sure you have all <?omega> intact\n"); fprintf(stderr, "Assuming configuration version \033[1;31m%d\033[0m\n\n", CONFIG_VERSION); } #ifdef HAVE_SETPROCTITLE setproctitle("%s", CfgSettings.servername); #endif open_log (); init_uid (); AddEventEx ("House Keeping", 900, EVENT_UNLIMITED, ev_housekeeping); AddEvent ("BURST", burst_local_users); AddEvent ("BURST", burst_local_servers); AddEvent ("CONNECT", introduce_users); if ((Omega->me = new_serv(NULL, CfgSettings.servername))) { strlcpy (Omega->me->sid, CfgSettings.sid, sizeof(Omega->me->sid)); Omega->me->eos = 1; //mark us as already EOS'ed } else { fprintf (stderr, "Unable to create our server entry\n"); exit (0); } /* * Initialize our core for running */ database_init (); protocol_init (); servsock = add_new_socket ((void*) psr_HandleEvent, NULL); servsock->flags |= SOCK_UPLINK; strlcpy (servsock->name, "Uplink", sizeof(servsock->name)); #ifdef HAVE_GNUTLS servsock->tls_enabled = get_config_bool("link", "gnutls", 0); #endif psr_init (); init_access(); init_modules(); introduce_users (0, NULL); /* * Connect to the IRCd if we don't connect Add an event to connect... */ printf ("\r\n"); printf ("Connecting to \033[1;32m%s\033[0m port \033[1;32m%d\033[0m\033[0m\n", CfgSettings.uplink, CfgSettings.port); if (Connect (servsock, CfgSettings.uplink, CfgSettings.local_ip, CfgSettings.port)) ircd_connect (); else AddEventEx ("Connect Uplink", 60, 3, ev_connectuplink); /* * Okay begin */ OneTimeAround (); return; }
/** * main function for FOSSology scheduler, does command line parsing, * Initialization and then simply enters the event loop. * * @param argc the command line argument cound * @param argv the command line argument values * @return if the program ran correctly */ int main(int argc, char** argv) { /* locals */ gboolean db_reset = FALSE; // flag to reset the job queue upon database connection gboolean ki_kill = FALSE; // flag that indicates all schedulers should be forcibly shutdown gboolean ki_shut = FALSE; // flag that indicates all schedulers should be gracefully shutdown gboolean db_init = FALSE; // flag indicating a database test gboolean test_die = FALSE; // flag to run the tests then die gboolean s_daemon = FALSE; // falg to run the scheduler as a daemon gchar* logdir = NULL; // used when a different log from the default is used GOptionContext* options; // option context used for command line parsing GError* error = NULL; // error object used during parsing uint16_t port = 0; gchar* sysconfigdir = DEFAULT_SETUP; /* THE SCHEDULER */ scheduler_t* scheduler; if(getenv("FO_SYSCONFDIR") != NULL) sysconfigdir = getenv("FO_SYSCONFDIR"); /* get this done first */ srand(time(NULL)); #if !(GLIB_MAJOR_VERSION >= 2 && GLIB_MINOR_VERSION >= 32) g_thread_init(NULL); #endif #if !(GLIB_MAJOR_VERSION >= 2 && GLIB_MINOR_VERSION >= 36) g_type_init(); #endif /* the options for the command line parser */ GOptionEntry entries[] = { { "daemon", 'd', 0, G_OPTION_ARG_NONE, &s_daemon, " Run scheduler as daemon" }, { "database", 'i', 0, G_OPTION_ARG_NONE, &db_init, " Initialize database connection and exit" }, { "kill", 'k', 0, G_OPTION_ARG_NONE, &ki_kill, " Forcibly kills all running schedulers" }, { "shutdown", 's', 0, G_OPTION_ARG_NONE, &ki_shut, " Gracefully shutdown of all running schedulers" }, { "log", 'L', 0, G_OPTION_ARG_STRING, &logdir, "[str] Specify location of log file" }, { "port", 'p', 0, G_OPTION_ARG_INT, &port, "[num] Set the interface port" }, { "reset", 'R', 0, G_OPTION_ARG_NONE, &db_reset, " Reset the job queue upon startup" }, { "test", 't', 0, G_OPTION_ARG_NONE, &test_die, " Close the scheduler after running tests" }, { "verbose", 'v', 0, G_OPTION_ARG_INT, &verbose, "[num] Set the scheduler verbose level" }, { "config", 'c', 0, G_OPTION_ARG_STRING, &sysconfigdir, "[str] Specify system configuration directory" }, {NULL} }; /* ********************* */ /* *** parse options *** */ /* ********************* */ options = g_option_context_new("- scheduler for FOSSology"); g_option_context_add_main_entries(options, entries, NULL); g_option_context_parse(options, &argc, &argv, &error); if(error) { fprintf(stderr, "ERROR: %s\n", error->message); fprintf(stderr, "%s", g_option_context_get_help(options, FALSE, NULL)); fflush(stderr); return -1; } g_option_context_free(options); /* check changes to the process first */ if(ki_shut) { return kill_scheduler(FALSE); } if(ki_kill) { return kill_scheduler(TRUE); } /* initialize the scheduler */ scheduler = scheduler_init(sysconfigdir, log_new("stdout", "initializing", getpid())); if(logdir) { scheduler->logdir = logdir; scheduler->logcmdline = TRUE; scheduler->main_log = log_new(scheduler->logdir, NULL, scheduler->s_pid); log_destroy(main_log); main_log = scheduler->main_log; } scheduler->process_name = g_strdup(argv[0]); scheduler->s_daemon = s_daemon; scheduler_foss_config(scheduler); if(s_daemon && scheduler_daemonize(scheduler) == -1) { return -1; } scheduler_agent_config(scheduler); database_init(scheduler); email_init(scheduler); NOTIFY("*****************************************************************"); NOTIFY("*** FOSSology scheduler started ***"); NOTIFY("*** pid: %-33d ***", getpid()); NOTIFY("*** verbose: %-33d ***", verbose); NOTIFY("*** config: %-33s ***", sysconfigdir); NOTIFY("*****************************************************************"); interface_init(scheduler); fo_RepOpenFull(scheduler->sysconfig); signal(SIGCHLD, scheduler_sig_handle); signal(SIGTERM, scheduler_sig_handle); signal(SIGQUIT, scheduler_sig_handle); signal(SIGHUP, scheduler_sig_handle); /* ***************************************************** */ /* *** we have finished initialization without error *** */ /* ***************************************************** */ if(db_reset) database_reset_queue(scheduler); if(test_die) closing = 1; event_loop_enter(scheduler, scheduler_update, scheduler_signal); NOTIFY("*****************************************************************"); NOTIFY("*** FOSSology scheduler closed ***"); NOTIFY("*** pid: %-34d ***", scheduler->s_pid); NOTIFY("*****************************************************************\n"); interface_destroy(scheduler); scheduler_destroy(scheduler); return 0; }
int main( int argc, char *argv[] ) { db_clt_typ *pclt = NULL; char hostname[MAXHOSTNAMELEN+1]; db_data_typ db_data; posix_timer_typ *ptmr; int recv_type; int millisec = 5000; trig_info_typ trig_info; uint64_t ticksPerMilliSec = SYSPAGE_ENTRY(qtime)->cycles_per_sec / 1000000; unsigned count = 0; unsigned total_diff = 0; /* Initialize the database. */ get_local_name(hostname, MAXHOSTNAMELEN); if( (pclt = database_init(argv[0], hostname, DEFAULT_SERVICE, COMM_QNX6_XPORT )) == NULL ) { fprintf(stderr, "Database initialization error in ids_io\n"); veh_done( pclt ); exit( EXIT_FAILURE ); } /* Initialize the timer. */ if ((ptmr = timer_init(millisec, DB_CHANNEL(pclt))) == NULL) { printf("timer_init failed\n"); exit( EXIT_FAILURE ); } print_timer(ptmr); if( setjmp( exit_env ) != 0 ) { printf("average timediff = %u\n", total_diff / count); veh_done( pclt ); exit( EXIT_SUCCESS ); } else sig_ign( sig_list, sig_hand ); for( ;; ) { /* Now wait for a trigger. */ recv_type= clt_ipc_receive(pclt, &trig_info, sizeof(trig_info)); if (recv_type == DB_TIMER) { printf("received timer alarm\n"); } else if(DB_TRIG_VAR(&trig_info) == 200) { fflush(stdout); /* Read DB_DII_OUT_VAR and send DII control * to the hardware. */ if( clt_read( pclt, 200, 200, &db_data ) == FALSE) { fprintf( stderr, "clt_read( DB_DII_OUT_VAR ).\n" ); } else { uint64_t *incoming_time = (uint64_t*) db_data.value.user; uint64_t timediff = ClockCycles() - *incoming_time; timediff /= ticksPerMilliSec; total_diff += timediff; ++count; } } else printf("Unknown trigger, recv_type %d\n", recv_type); } }
int main(int argc, char *argv[]) { errno = 0; //CL args const char *dbfile = NULL, *stn_departure = NULL, *stn_arrival = NULL; int ch,res, consecutive_success = 0; //Handles CURL *curl_hdl = NULL; sqlite3 *db_hdl = NULL; TidyDoc tdoc = NULL; //Query initialisers char *link, *new_link; struct tm tm_dep; time_t last_time_dep = 0; int requery = 0; //Parse result holders struct train_list_t *trains = NULL; size_t n, ntrains; //Output char str_time_dep[20]; size_t total = 0; //Parse cmdline while( (ch = getopt(argc, argv, "d:f:t:")) != -1 ) { debug("ch = %d", ch); switch(ch) { case 'd': debug("d %s", optarg); dbfile = optarg; break; case 'f': debug("f %s", optarg); stn_departure = optarg; break; case 't': debug("t %s", optarg); stn_arrival = optarg; break; case '?': if(optopt=='d' || optopt=='f' || optopt=='t') { log_info("Missing argument for option -%c", optopt); goto usage; } else if(isprint(optopt)) { log_info("Unknown option '-%c'", optopt); } else { log_info("Unknown option character '\\x%x'", optopt); } break; default: debug("err got c=%d (opterr=%d, optopt=%c, optind=%d, optarg=%s)", ch, opterr, optopt, optind, optarg); goto usage; } } if(!dbfile || !stn_departure || !stn_arrival) goto usage; debug("Starting %s with dbfile='%s', stn_dep='%s', stn_arr='%s'", argv[0], dbfile, stn_departure, stn_arrival); //Set up Curl check(curl_tidy_init(&curl_hdl)==0,"Failed to initialise curl"); debug("curl_hdl %p", curl_hdl); //Set up database and get names res = database_init(&db_hdl, dbfile); check(res==0, "Failed to open database"); //Send search query time_t now = time(NULL); localtime_r(&now, &tm_dep); tm_dep.tm_hour++; res = sncf_post_form(curl_hdl, &tdoc, &link, &tm_dep, stn_departure, stn_arrival); check(res==0, "Failed to perform query"); debug("Initialized (%d) - link = %s", res, link); //Fetch, parse, print while(1) { debug("Next link %s", link); tidyRelease(tdoc); res = curl_tidy_get(curl_hdl, link, &tdoc); check(res == 0, "failed to fetch results page"); res = sncf_find_next_results_link(tdoc, &new_link); check(res == 0, "failed to get link to next results"); /* * An error in the SNCF site results in occasionally being * sent to the same results page. This means getting stuck * in a loop. If that happens, a workaround is to start a * new query and continue from there */ if(!strcmp(link, new_link)) { log_info("Next results page is the same as the current one (%d successes)", consecutive_success); if(consecutive_success <= 2) { log_info("less than 3 success before loop, this is the end"); break; } requery = 1; } if(requery) { if(requery == 1) log_info("requerying cos of link loop"); if(requery == 2) log_info("requerying cos of time travel"); requery = 0; localtime_r(&last_time_dep, &tm_dep); consecutive_success = 0; tidyRelease(tdoc); free(link); free(new_link); //FIXME: change tm_dep so the SNCF site is likely to handle it res = sncf_post_form(curl_hdl, &tdoc, &link, &tm_dep, stn_departure, stn_arrival); check(res==0, "Failed to perform query"); continue; } if(trains) { debug("last time dep = %lu - train time dep = %lu", last_time_dep, get_last_train(trains)->train.time_departure); } free_trains(trains); trains = NULL; ntrains = sncf_parse_results(db_hdl, tdoc, &trains); debug("found %lu trains", ntrains); //Check if we're getting the same results over and over again (only iff we have results (ntrains) // and only if last_time_dep was set before (check if it's not 0 as initialized)) if(last_time_dep && ntrains && get_last_train(trains)->train.time_departure < last_time_dep) { requery = 2; continue; } if(last_time_dep && ntrains && get_last_train(trains)->train.time_departure == last_time_dep) { log_info("Got the exact same results twice, finishing up"); break; } if(ntrains) { last_time_dep = get_last_train(trains)->train.time_departure; } else { log_info("No trains found, this is the end"); break; } n = train_store(db_hdl, trains); if(n!=ntrains) { log_info("only stored %lu out of %lu trains, aborting", n, ntrains); goto error; } debug("Stored all %lu trains", n); total+=n; #ifdef NDEBUG localtime_r(&get_last_train(trains)->train.time_departure, &tm_dep); strftime(str_time_dep, 20, "%e-%b-%Y %R", &tm_dep); printf("Processed %6lu trains - Last one departed at %s\r", total, str_time_dep); fflush(stdout); #else print_trains(db_hdl, trains, 0); #endif consecutive_success++; free(link); link = new_link; } free(link); free(new_link); error: if(tdoc) { tidySaveFile(tdoc, "dumpfile-exit.html"); tidyRelease(tdoc); } curl_tidy_cleanup(curl_hdl); database_cleanup(db_hdl); localtime_r(&get_last_train(trains)->train.time_departure, &tm_dep); strftime(str_time_dep, 20, "%e-%b-%Y %R", &tm_dep); log_info("Exiting after storing %lu trains (last one arriving %s)", total, str_time_dep); return 0; usage: printf( "Usage : %s -d <dbfile> -f <stn_dep> -t <stn_arr>\n" "\n" "\t<dbfile>\tThe sqlite3 database filename\n" "\t<stn_dep>\tThe departure station\n" "\t<stn_arr>\tThe arrival station\n" "\n", argv[0]); return 0; }
int main(int ac, char *av[]) { /* create .preloader directory */ char path[500]; sprintf( path, "%s/.preloader", getenv("HOME") ); if( mkdir( path, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH ) < 0 ) /* mkdir failed */ if( errno != EEXIST ) { fprintf( stderr, "error: failed to create %s!\n", path ); exit( 0 ); } CTX ctx; memset( &ctx, 0, sizeof( ctx ) ); snprintf( ctx.filename, sizeof( ctx.filename ), "%s%s", *av[1] == '/' || *av[1] == '.' ? "" : "./", av[1] ); _init_display(); ctx.state = STATE_PROCESSING_SYMS; ctx.db = database_init(); ctx.hash = database_add_target( ctx.db, ctx.filename ); /* add target to db */ /* get symbols from target target */ int fd = open( av[1], O_RDONLY ); DYNSYM *ds = get_dynsyms( fd, DYNSYM_UNDEFINED_ONLY ); close( fd ); /* add symbols to db */ DYNSYM *p_ds = ds; while( p_ds ) { ctx.extra = p_ds->name; _draw_display( &ctx ); database_add_symbol( ctx.db, p_ds->name ); p_ds = p_ds->nxt; } ctx.state = STATE_PROCESSING_LIBS; /* add libs to db */ LL *lib_sym_info = ll_calloc(); LIBS *libs = get_libs(ctx.filename); LIBS *p_libs = libs; while( p_libs ) { ctx.extra = p_libs->path; _draw_display( &ctx ); database_add_lib( ctx.db, p_libs->name, p_libs->path ); p_libs = p_libs->nxt; } ctx.state = STATE_RESOLVING_SYMBOLS; /* match symbols to libs */ /* immensely inefficient, should call get_dynsyms() ONCE for each lib!! (TODO) */ p_ds = ds; while( p_ds ) { /* for each symbol in target */ int found = 0; ctx.extra = p_ds->name; _draw_display( &ctx ); LIBS *p_lib = libs; while( p_lib && !found ) { /* search each lib for match */ int fd_lib = open( p_lib->path, O_RDONLY ); DYNSYM *ds_lib = get_dynsyms( fd_lib, DYNSYM_DEFINED_ONLY ); /* get symbols from lib */ DYNSYM *p_ds_lib = ds_lib; while( p_ds_lib ) { /* for each symbol in library */ if( strcmp( p_ds_lib->name, p_ds->name ) == 0 ) { database_link_sym_lib( ctx.db, p_ds->name, p_lib->path ); found = 1; break; } p_ds_lib = p_ds_lib->nxt; /* move to next symbol in library */ } free_dynsyms( ds_lib ); close( fd_lib ); p_lib = p_lib->nxt; /* move to next library */ } p_ds = p_ds->nxt; /* move to next symbol */ } ll_free( lib_sym_info ); free_libs( libs ); free_dynsyms( ds ); // TODO iter through and free free_dynsyms( ds_lib ); _populate_symbol_list( ctx.db, &ctx.symbols ); ctx.state = STATE_NORMAL; ctx.running = 1; while( ctx.running ) { usleep(1000); _draw_display( &ctx ); _parse_input( &ctx ); } _disable_display(); database_kill( ctx.db ); /* free symbol list */ ll_free( ctx.symbols.func ); ll_free( ctx.symbols.sig ); return 0; }
int main(void) { int status; int sd; struct packet_st pkt; struct sockaddr_in myend, hisend; socklen_t hislen; int val; int ret; int recv_len; database_init(); sd = socket(AF_INET, SOCK_DGRAM, 0); if (sd == -1) { perror("socket()"); goto socket_err; } val = 1; setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)); myend.sin_family = AF_INET; myend.sin_port = SERVER_PORT; myend.sin_addr.s_addr = INADDR_ANY; ret = bind(sd, (struct sockaddr *)&myend, sizeof(myend)); if (ret == -1) { perror("bind()"); goto bind_err; } hislen = sizeof(hisend); status = ST_RECV; while (status != ST_QUIT) { switch (status) { case ST_RECV: recv_len = recvfrom(sd, &pkt, sizeof(pkt), 0, (struct sockaddr *)&hisend, &hislen); if (recv_len == -1) { status = ST_ERROR; break; } if (pkt.major == MAJOR_LOGIN) { status = ST_LOGIN; } else if (pkt.major == MAJOR_MESSAGE) { status = ST_MSG; } else if (pkt.major == MAJOR_LIST) { status = ST_LIST; } else if (pkt.major == MAJOR_HEART) { status = ST_HEART; } else if (pkt.major == MAJOR_MANAGE) { /* fix me */ status = ST_RECV; } else if (pkt.major == MAJOR_ERROR) { status = ST_ERROR; } else { status = ST_ERROR; } break; case ST_LOGIN: ret = login(sd, &pkt, recv_len, &hisend); if (ret == 0) { status = ST_RECV; } else { status = ST_ERROR; } break; case ST_MSG: message(sd, &pkt, recv_len, &hisend); status = ST_RECV; break; case ST_LIST: list(sd, &pkt, recv_len, &hisend); status = ST_RECV; break; case ST_HEART: heart(sd, &pkt, recv_len, &hisend); status = ST_RECV; break; case ST_ERROR: /* fix me */ status = ST_QUIT; break; } } close(sd); database_destroy(); return 0; bind_err: close(sd); socket_err: database_destroy(); return 1; }
int main(int argc, char *argv[]) { int nb_nodes = -1; char *home = NULL; char c; db_handle_t *handles = NULL; int i, j; int err; char db_filename[32]; int nb_lost_objects = 0; while ((c=getopt(argc, argv, "d:n:")) != EOF) { switch (c) { case 'd': home = optarg; break; case 'n': nb_nodes = atoi(optarg); break; default: usage(); return(1); } } if (!home) { fprintf(stderr, "You have to specify a DB directory\n"); usage(); return(1); } if (nb_nodes == -1) { fprintf(stderr, "Invalid number of nodes\n"); usage(); return(1); } handles = (db_handle_t*)malloc(nb_nodes*sizeof(db_handle_t)); if (!handles) { fprintf(stderr, "malloc failed\n"); return(1); } j=0; for (i=0; i<nb_nodes; i++) { snprintf(db_filename, sizeof(db_filename), "hcb%d.db", i+101); err = database_init(handles+j, home, db_filename, 0); if (err) { fprintf(stderr, "Failed to open the db for hcb%d [%d]\n", i+101, err); } else { j++; } } nb_lost_objects = analyze(handles, j); for (i=0; i<j; i++) { database_close(handles+i); } free(handles); handles = NULL; return(nb_lost_objects); }
/* * public: */ void gui_start(Config *config, Cache *cache) { gboolean start_app = FALSE; gboolean database_is_valid = FALSE; gboolean account_is_initialized = FALSE; GtkWidget *dialog = NULL; GError *err = NULL; g_assert(config != NULL); g_assert(cache != NULL); g_debug("Starting GUI..."); #ifdef G_OS_WIN32 gchar *path; /* load windows theme */ g_debug("Parsing MS-Windows theme file"); path = g_build_filename(pathbuilder_get_share_directory(), G_DIR_SEPARATOR_S, "themes", G_DIR_SEPARATOR_S, "MS-Windows", G_DIR_SEPARATOR_S, "gtk-2.0", G_DIR_SEPARATOR_S, "gtkrc", NULL); g_debug("filename: %s", path); gtk_rc_parse(path); g_free(path); #endif /* check if configuration is empty */ if(!(start_app = settings_config_has_account(config))) { /* configuration is empty => start wizard */ g_debug("Configuration doesn't contain at least one account, starting wizard"); if((start_app = wizard_start(config))) { _gui_save_config(config); } } if(start_app) { /* initialize database */ g_debug("Initializing database..."); switch(database_init(&err)) { case DATABASE_INIT_FAILURE: dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_WARNING, GTK_BUTTONS_OK, _("Couldn't initialize %s, database seems to be damaged."), APPLICATION_NAME); break; case DATABASE_INIT_APPLICATION_OUTDATED: dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_WARNING, GTK_BUTTONS_OK, _("Couldn't initialize database, please upgrade %s."), APPLICATION_NAME); break; case DATABASE_INIT_FIRST_INITIALIZATION: case DATABASE_INIT_SUCCESS: case DATABASE_INIT_DATABASE_UPGRADED: database_is_valid = TRUE; break; default: g_warning("Invalid database result code."); break; } /* display failure messages */ if(err) { g_warning("%s", err->message); g_error_free(err); err = NULL; } if(database_is_valid) { /* initialize first account (if neccessary) */ g_debug("Testing account initialization status..."); if(!(account_is_initialized = _gui_check_account_initialization(config))) { g_debug("Starting account initialization"); if((account_is_initialized = _gui_initialize_account(config))) { g_debug("account has been initialized successfully => updating configuration"); _gui_enable_account_initialization(config); _gui_save_config(config); } else { dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_WARNING, GTK_BUTTONS_OK, _("Account initialization failed, please try again later.")); } } /* open mainwindow */ if(account_is_initialized) { g_debug("Opening mainwindow"); mainwindow_start(config, cache); } } /* show warning dialog */ if(dialog) { gtk_window_set_position(GTK_WINDOW(dialog), GTK_WIN_POS_CENTER); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); } } }